forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtest_typing.py
7144 lines (5832 loc) · 245 KB
/
test_typing.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 contextlib
import collections
from collections import defaultdict
from functools import lru_cache, wraps
import inspect
import itertools
import pickle
import re
import sys
import warnings
from unittest import TestCase, main, skipUnless, skip
from unittest.mock import patch
from copy import copy, deepcopy
from typing import Any, NoReturn, Never, assert_never
from typing import overload, get_overloads, clear_overloads
from typing import TypeVar, TypeVarTuple, Unpack, AnyStr
from typing import T, KT, VT # Not in __all__.
from typing import Union, Optional, Literal
from typing import Tuple, List, Dict, MutableMapping
from typing import Callable
from typing import Generic, ClassVar, Final, final, Protocol
from typing import assert_type, cast, runtime_checkable
from typing import get_type_hints
from typing import get_origin, get_args
from typing import is_typeddict
from typing import reveal_type
from typing import dataclass_transform
from typing import no_type_check, no_type_check_decorator
from typing import Type
from typing import NamedTuple, NotRequired, Required, TypedDict
from typing import IO, TextIO, BinaryIO
from typing import Pattern, Match
from typing import Annotated, ForwardRef
from typing import Self, LiteralString
from typing import TypeAlias
from typing import ParamSpec, Concatenate, ParamSpecArgs, ParamSpecKwargs
from typing import TypeGuard
import abc
import textwrap
import typing
import weakref
import types
from test.support import import_helper, captured_stderr
from test import mod_generics_cache
from test import _typed_dict_helper
py_typing = import_helper.import_fresh_module('typing', blocked=['_typing'])
c_typing = import_helper.import_fresh_module('typing', fresh=['_typing'])
class BaseTestCase(TestCase):
def assertIsSubclass(self, cls, class_or_tuple, msg=None):
if not issubclass(cls, class_or_tuple):
message = '%r is not a subclass of %r' % (cls, class_or_tuple)
if msg is not None:
message += ' : %s' % msg
raise self.failureException(message)
def assertNotIsSubclass(self, cls, class_or_tuple, msg=None):
if issubclass(cls, class_or_tuple):
message = '%r is a subclass of %r' % (cls, class_or_tuple)
if msg is not None:
message += ' : %s' % msg
raise self.failureException(message)
def clear_caches(self):
for f in typing._cleanups:
f()
def all_pickle_protocols(test_func):
"""Runs `test_func` with various values for `proto` argument."""
@wraps(test_func)
def wrapper(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(pickle_proto=proto):
test_func(self, proto=proto)
return wrapper
class Employee:
pass
class Manager(Employee):
pass
class Founder(Employee):
pass
class ManagingFounder(Manager, Founder):
pass
class AnyTests(BaseTestCase):
def test_any_instance_type_error(self):
with self.assertRaises(TypeError):
isinstance(42, Any)
def test_repr(self):
self.assertEqual(repr(Any), 'typing.Any')
def test_errors(self):
with self.assertRaises(TypeError):
issubclass(42, Any)
with self.assertRaises(TypeError):
Any[int] # Any is not a generic type.
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)
def test_cannot_instantiate(self):
with self.assertRaises(TypeError):
Any()
with self.assertRaises(TypeError):
type(Any)()
def test_any_works_with_alias(self):
# These expressions must simply not fail.
typing.Match[Any]
typing.Pattern[Any]
typing.IO[Any]
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)()
class NoReturnTests(BottomTypeTestsMixin, BaseTestCase):
bottom_type = NoReturn
def test_repr(self):
self.assertEqual(repr(NoReturn), 'typing.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):
self.assertEqual(repr(Never), 'typing.Never')
def test_get_type_hints(self):
def some(arg: Never) -> Never: ...
def some_str(arg: 'Never') -> 'typing.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._ASSERT_NEVER_REPR_MAX_LENGTH * 2,
)
class SelfTests(BaseTestCase):
def test_equality(self):
self.assertEqual(Self, Self)
self.assertIs(Self, Self)
self.assertNotEqual(Self, None)
def test_basics(self):
class Foo:
def bar(self) -> Self: ...
class FooStr:
def bar(self) -> 'Self': ...
class FooStrTyping:
def bar(self) -> 'typing.Self': ...
for target in [Foo, FooStr, FooStrTyping]:
with self.subTest(target=target):
self.assertEqual(gth(target.bar), {'return': Self})
self.assertIs(get_origin(Self), None)
def test_repr(self):
self.assertEqual(repr(Self), 'typing.Self')
def test_cannot_subscript(self):
with self.assertRaises(TypeError):
Self[int]
def test_cannot_subclass(self):
with self.assertRaises(TypeError):
class C(type(Self)):
pass
with self.assertRaises(TypeError):
class C(Self):
pass
def test_cannot_init(self):
with self.assertRaises(TypeError):
Self()
with self.assertRaises(TypeError):
type(Self)()
def test_no_isinstance(self):
with self.assertRaises(TypeError):
isinstance(1, Self)
with self.assertRaises(TypeError):
issubclass(int, Self)
def test_alias(self):
# TypeAliases are not actually part of the spec
alias_1 = Tuple[Self, Self]
alias_2 = List[Self]
alias_3 = ClassVar[Self]
self.assertEqual(get_args(alias_1), (Self, Self))
self.assertEqual(get_args(alias_2), (Self,))
self.assertEqual(get_args(alias_3), (Self,))
class LiteralStringTests(BaseTestCase):
def test_equality(self):
self.assertEqual(LiteralString, LiteralString)
self.assertIs(LiteralString, LiteralString)
self.assertNotEqual(LiteralString, None)
def test_basics(self):
class Foo:
def bar(self) -> LiteralString: ...
class FooStr:
def bar(self) -> 'LiteralString': ...
class FooStrTyping:
def bar(self) -> 'typing.LiteralString': ...
for target in [Foo, FooStr, FooStrTyping]:
with self.subTest(target=target):
self.assertEqual(gth(target.bar), {'return': LiteralString})
self.assertIs(get_origin(LiteralString), None)
def test_repr(self):
self.assertEqual(repr(LiteralString), 'typing.LiteralString')
def test_cannot_subscript(self):
with self.assertRaises(TypeError):
LiteralString[int]
def test_cannot_subclass(self):
with self.assertRaises(TypeError):
class C(type(LiteralString)):
pass
with self.assertRaises(TypeError):
class C(LiteralString):
pass
def test_cannot_init(self):
with self.assertRaises(TypeError):
LiteralString()
with self.assertRaises(TypeError):
type(LiteralString)()
def test_no_isinstance(self):
with self.assertRaises(TypeError):
isinstance(1, LiteralString)
with self.assertRaises(TypeError):
issubclass(int, LiteralString)
def test_alias(self):
alias_1 = Tuple[LiteralString, LiteralString]
alias_2 = List[LiteralString]
alias_3 = ClassVar[LiteralString]
self.assertEqual(get_args(alias_1), (LiteralString, LiteralString))
self.assertEqual(get_args(alias_2), (LiteralString,))
self.assertEqual(get_args(alias_3), (LiteralString,))
class TypeVarTests(BaseTestCase):
def test_basic_plain(self):
T = TypeVar('T')
# T equals itself.
self.assertEqual(T, T)
# T is an instance of TypeVar
self.assertIsInstance(T, TypeVar)
def test_typevar_instance_type_error(self):
T = TypeVar('T')
with self.assertRaises(TypeError):
isinstance(42, T)
def test_typevar_subclass_type_error(self):
T = TypeVar('T')
with self.assertRaises(TypeError):
issubclass(int, T)
with self.assertRaises(TypeError):
issubclass(T, int)
def test_constrained_error(self):
with self.assertRaises(TypeError):
X = TypeVar('X', int)
X
def test_union_unique(self):
X = TypeVar('X')
Y = TypeVar('Y')
self.assertNotEqual(X, Y)
self.assertEqual(Union[X], X)
self.assertNotEqual(Union[X], Union[X, Y])
self.assertEqual(Union[X, X], X)
self.assertNotEqual(Union[X, int], Union[X])
self.assertNotEqual(Union[X, int], Union[int])
self.assertEqual(Union[X, int].__args__, (X, int))
self.assertEqual(Union[X, int].__parameters__, (X,))
self.assertIs(Union[X, int].__origin__, Union)
def test_or(self):
X = TypeVar('X')
# use a string because str doesn't implement
# __or__/__ror__ itself
self.assertEqual(X | "x", Union[X, "x"])
self.assertEqual("x" | X, Union["x", X])
# make sure the order is correct
self.assertEqual(get_args(X | "x"), (X, ForwardRef("x")))
self.assertEqual(get_args("x" | X), (ForwardRef("x"), X))
def test_union_constrained(self):
A = TypeVar('A', str, bytes)
self.assertNotEqual(Union[A, str], Union[A])
def test_repr(self):
self.assertEqual(repr(T), '~T')
self.assertEqual(repr(KT), '~KT')
self.assertEqual(repr(VT), '~VT')
self.assertEqual(repr(AnyStr), '~AnyStr')
T_co = TypeVar('T_co', covariant=True)
self.assertEqual(repr(T_co), '+T_co')
T_contra = TypeVar('T_contra', contravariant=True)
self.assertEqual(repr(T_contra), '-T_contra')
def test_no_redefinition(self):
self.assertNotEqual(TypeVar('T'), TypeVar('T'))
self.assertNotEqual(TypeVar('T', int, str), TypeVar('T', int, str))
def test_cannot_subclass_vars(self):
with self.assertRaises(TypeError):
class V(TypeVar('T')):
pass
def test_cannot_subclass_var_itself(self):
with self.assertRaises(TypeError):
class V(TypeVar):
pass
def test_cannot_instantiate_vars(self):
with self.assertRaises(TypeError):
TypeVar('A')()
def test_bound_errors(self):
with self.assertRaises(TypeError):
TypeVar('X', bound=Union)
with self.assertRaises(TypeError):
TypeVar('X', str, float, bound=Employee)
def test_missing__name__(self):
# See bpo-39942
code = ("import typing\n"
"T = typing.TypeVar('T')\n"
)
exec(code, {})
def test_no_bivariant(self):
with self.assertRaises(ValueError):
TypeVar('T', covariant=True, contravariant=True)
def test_var_substitution(self):
T = TypeVar('T')
subst = T.__typing_subst__
self.assertIs(subst(int), int)
self.assertEqual(subst(list[int]), list[int])
self.assertEqual(subst(List[int]), List[int])
self.assertEqual(subst(List), List)
self.assertIs(subst(Any), Any)
self.assertIs(subst(None), type(None))
self.assertIs(subst(T), T)
self.assertEqual(subst(int|str), int|str)
self.assertEqual(subst(Union[int, str]), Union[int, str])
def test_bad_var_substitution(self):
T = TypeVar('T')
P = ParamSpec("P")
bad_args = (
(), (int, str), Union,
Generic, Generic[T], Protocol, Protocol[T],
Final, Final[int], ClassVar, ClassVar[int],
)
for arg in bad_args:
with self.subTest(arg=arg):
with self.assertRaises(TypeError):
T.__typing_subst__(arg)
with self.assertRaises(TypeError):
List[T][arg]
with self.assertRaises(TypeError):
list[T][arg]
def template_replace(templates: list[str], replacements: dict[str, list[str]]) -> list[tuple[str]]:
"""Renders templates with possible combinations of replacements.
Example 1: Suppose that:
templates = ["dog_breed are awesome", "dog_breed are cool"]
replacements = ["dog_breed": ["Huskies", "Beagles"]]
Then we would return:
[
("Huskies are awesome", "Huskies are cool"),
("Beagles are awesome", "Beagles are cool")
]
Example 2: Suppose that:
templates = ["Huskies are word1 but also word2"]
replacements = {"word1": ["playful", "cute"],
"word2": ["feisty", "tiring"]}
Then we would return:
[
("Huskies are playful but also feisty"),
("Huskies are playful but also tiring"),
("Huskies are cute but also feisty"),
("Huskies are cute but also tiring")
]
Note that if any of the replacements do not occur in any template:
templates = ["Huskies are word1", "Beagles!"]
replacements = {"word1": ["playful", "cute"],
"word2": ["feisty", "tiring"]}
Then we do not generate duplicates, returning:
[
("Huskies are playful", "Beagles!"),
("Huskies are cute", "Beagles!")
]
"""
# First, build a structure like:
# [
# [("word1", "playful"), ("word1", "cute")],
# [("word2", "feisty"), ("word2", "tiring")]
# ]
replacement_combos = []
for original, possible_replacements in replacements.items():
original_replacement_tuples = []
for replacement in possible_replacements:
original_replacement_tuples.append((original, replacement))
replacement_combos.append(original_replacement_tuples)
# Second, generate rendered templates, including possible duplicates.
rendered_templates = []
for replacement_combo in itertools.product(*replacement_combos):
# replacement_combo would be e.g.
# [("word1", "playful"), ("word2", "feisty")]
templates_with_replacements = []
for template in templates:
for original, replacement in replacement_combo:
template = template.replace(original, replacement)
templates_with_replacements.append(template)
rendered_templates.append(tuple(templates_with_replacements))
# Finally, remove the duplicates (but keep the order).
rendered_templates_no_duplicates = []
for x in rendered_templates:
# Inefficient, but should be fine for our purposes.
if x not in rendered_templates_no_duplicates:
rendered_templates_no_duplicates.append(x)
return rendered_templates_no_duplicates
class TemplateReplacementTests(BaseTestCase):
def test_two_templates_two_replacements_yields_correct_renders(self):
actual = template_replace(
templates=["Cats are word1", "Dogs are word2"],
replacements={
"word1": ["small", "cute"],
"word2": ["big", "fluffy"],
},
)
expected = [
("Cats are small", "Dogs are big"),
("Cats are small", "Dogs are fluffy"),
("Cats are cute", "Dogs are big"),
("Cats are cute", "Dogs are fluffy"),
]
self.assertEqual(actual, expected)
def test_no_duplicates_if_replacement_not_in_templates(self):
actual = template_replace(
templates=["Cats are word1", "Dogs!"],
replacements={
"word1": ["small", "cute"],
"word2": ["big", "fluffy"],
},
)
expected = [
("Cats are small", "Dogs!"),
("Cats are cute", "Dogs!"),
]
self.assertEqual(actual, expected)
class GenericAliasSubstitutionTests(BaseTestCase):
"""Tests for type variable substitution in generic aliases.
Note that the expected results here are tentative, based on a
still-being-worked-out spec for what we allow at runtime (given that
implementation of *full* substitution logic at runtime would add too much
complexity to typing.py). This spec is currently being discussed at
https://github.com/python/cpython/issues/91162.
"""
def test_one_parameter(self):
T = TypeVar('T')
Ts = TypeVarTuple('Ts')
class C(Generic[T]): pass
generics = ['C', 'list', 'List']
tuple_types = ['tuple', 'Tuple']
tests = [
# Alias # Args # Expected result
('generic[T]', '[()]', 'TypeError'),
('generic[T]', '[int]', 'generic[int]'),
('generic[T]', '[int, str]', 'TypeError'),
('generic[T]', '[tuple_type[int, ...]]', 'generic[tuple_type[int, ...]]'),
# Should raise TypeError: a) according to the tentative spec,
# unpacked types cannot be used as arguments to aliases that expect
# a fixed number of arguments; b) it's equivalent to generic[()].
('generic[T]', '[*tuple[()]]', 'generic[*tuple[()]]'),
('generic[T]', '[*Tuple[()]]', 'TypeError'),
# Should raise TypeError according to the tentative spec: unpacked
# types cannot be used as arguments to aliases that expect a fixed
# number of arguments.
('generic[T]', '[*tuple[int]]', 'generic[*tuple[int]]'),
('generic[T]', '[*Tuple[int]]', 'TypeError'),
# Ditto.
('generic[T]', '[*tuple[int, str]]', 'generic[*tuple[int, str]]'),
('generic[T]', '[*Tuple[int, str]]', 'TypeError'),
# Ditto.
('generic[T]', '[*tuple[int, ...]]', 'generic[*tuple[int, ...]]'),
('generic[T]', '[*Tuple[int, ...]]', 'TypeError'),
('generic[T]', '[*Ts]', 'TypeError'),
('generic[T]', '[T, *Ts]', 'TypeError'),
('generic[T]', '[*Ts, T]', 'TypeError'),
# Raises TypeError because C is not variadic.
# (If C _were_ variadic, it'd be fine.)
('C[T, *tuple_type[int, ...]]', '[int]', 'TypeError'),
# Should definitely raise TypeError: list only takes one argument.
('list[T, *tuple_type[int, ...]]', '[int]', 'list[int, *tuple_type[int, ...]]'),
('List[T, *tuple_type[int, ...]]', '[int]', 'TypeError'),
]
for alias_template, args_template, expected_template in tests:
rendered_templates = template_replace(
templates=[alias_template, args_template, expected_template],
replacements={'generic': generics, 'tuple_type': tuple_types}
)
for alias_str, args_str, expected_str in rendered_templates:
with self.subTest(alias=alias_str, args=args_str, expected=expected_str):
if expected_str == 'TypeError':
with self.assertRaises(TypeError):
eval(alias_str + args_str)
else:
self.assertEqual(
eval(alias_str + args_str),
eval(expected_str)
)
def test_two_parameters(self):
T1 = TypeVar('T1')
T2 = TypeVar('T2')
Ts = TypeVarTuple('Ts')
class C(Generic[T1, T2]): pass
generics = ['C', 'dict', 'Dict']
tuple_types = ['tuple', 'Tuple']
tests = [
# Alias # Args # Expected result
('generic[T1, T2]', '[()]', 'TypeError'),
('generic[T1, T2]', '[int]', 'TypeError'),
('generic[T1, T2]', '[int, str]', 'generic[int, str]'),
('generic[T1, T2]', '[int, str, bool]', 'TypeError'),
('generic[T1, T2]', '[*tuple_type[int]]', 'TypeError'),
('generic[T1, T2]', '[*tuple_type[int, str]]', 'TypeError'),
('generic[T1, T2]', '[*tuple_type[int, str, bool]]', 'TypeError'),
# Should raise TypeError according to the tentative spec: unpacked
# types cannot be used as arguments to aliases that expect a fixed
# number of arguments.
('generic[T1, T2]', '[*tuple[int, str], *tuple[float, bool]]', 'generic[*tuple[int, str], *tuple[float, bool]]'),
('generic[T1, T2]', '[*Tuple[int, str], *Tuple[float, bool]]', 'TypeError'),
('generic[T1, T2]', '[tuple_type[int, ...]]', 'TypeError'),
('generic[T1, T2]', '[tuple_type[int, ...], tuple_type[str, ...]]', 'generic[tuple_type[int, ...], tuple_type[str, ...]]'),
('generic[T1, T2]', '[*tuple_type[int, ...]]', 'TypeError'),
# Ditto.
('generic[T1, T2]', '[*tuple[int, ...], *tuple[str, ...]]', 'generic[*tuple[int, ...], *tuple[str, ...]]'),
('generic[T1, T2]', '[*Tuple[int, ...], *Tuple[str, ...]]', 'TypeError'),
('generic[T1, T2]', '[*Ts]', 'TypeError'),
('generic[T1, T2]', '[T, *Ts]', 'TypeError'),
('generic[T1, T2]', '[*Ts, T]', 'TypeError'),
# Should raise TypeError according to the tentative spec: unpacked
# types cannot be used as arguments to generics that expect a fixed
# number of arguments.
# (None of the things in `generics` were defined using *Ts.)
('generic[T1, *tuple_type[int, ...]]', '[str]', 'generic[str, *tuple_type[int, ...]]'),
]
for alias_template, args_template, expected_template in tests:
rendered_templates = template_replace(
templates=[alias_template, args_template, expected_template],
replacements={'generic': generics, 'tuple_type': tuple_types}
)
for alias_str, args_str, expected_str in rendered_templates:
with self.subTest(alias=alias_str, args=args_str, expected=expected_str):
if expected_str == 'TypeError':
with self.assertRaises(TypeError):
eval(alias_str + args_str)
else:
self.assertEqual(
eval(alias_str + args_str),
eval(expected_str)
)
def test_three_parameters(self):
T1 = TypeVar('T1')
T2 = TypeVar('T2')
T3 = TypeVar('T3')
class C(Generic[T1, T2, T3]): pass
generics = ['C']
tuple_types = ['tuple', 'Tuple']
tests = [
# Alias # Args # Expected result
('generic[T1, bool, T2]', '[int, str]', 'generic[int, bool, str]'),
('generic[T1, bool, T2]', '[*tuple_type[int, str]]', 'TypeError'),
]
for alias_template, args_template, expected_template in tests:
rendered_templates = template_replace(
templates=[alias_template, args_template, expected_template],
replacements={'generic': generics, 'tuple_type': tuple_types}
)
for alias_str, args_str, expected_str in rendered_templates:
with self.subTest(alias=alias_str, args=args_str, expected=expected_str):
if expected_str == 'TypeError':
with self.assertRaises(TypeError):
eval(alias_str + args_str)
else:
self.assertEqual(
eval(alias_str + args_str),
eval(expected_str)
)
def test_variadic_parameters(self):
T1 = TypeVar('T1')
T2 = TypeVar('T2')
Ts = TypeVarTuple('Ts')
class C(Generic[*Ts]): pass
generics = ['C', 'tuple', 'Tuple']
tuple_types = ['tuple', 'Tuple']
# The majority of these have three separate cases for C, tuple and
# Tuple because tuple currently behaves differently.
tests = [
# Alias # Args # Expected result
('C[*Ts]', '[()]', 'C[()]'),
('tuple[*Ts]', '[()]', 'tuple[()]'),
('Tuple[*Ts]', '[()]', 'Tuple[()]'),
('C[*Ts]', '[int]', 'C[int]'),
('tuple[*Ts]', '[int]', 'tuple[int]'),
('Tuple[*Ts]', '[int]', 'Tuple[int]'),
('C[*Ts]', '[int, str]', 'C[int, str]'),
('tuple[*Ts]', '[int, str]', 'tuple[int, str]'),
('Tuple[*Ts]', '[int, str]', 'Tuple[int, str]'),
('C[*Ts]', '[*tuple_type[int]]', 'C[*tuple_type[int]]'), # Should be C[int]
('tuple[*Ts]', '[*tuple_type[int]]', 'tuple[*tuple_type[int]]'), # Should be tuple[int]
('Tuple[*Ts]', '[*tuple_type[int]]', 'Tuple[*tuple_type[int]]'), # Should be Tuple[int]
('C[*Ts]', '[*tuple_type[*Ts]]', 'C[*tuple_type[*Ts]]'), # Should be C[*Ts]
('tuple[*Ts]', '[*tuple_type[*Ts]]', 'tuple[*tuple_type[*Ts]]'), # Should be tuple[*Ts]
('Tuple[*Ts]', '[*tuple_type[*Ts]]', 'Tuple[*tuple_type[*Ts]]'), # Should be Tuple[*Ts]
('C[*Ts]', '[*tuple_type[int, str]]', 'C[*tuple_type[int, str]]'), # Should be C[int, str]
('tuple[*Ts]', '[*tuple_type[int, str]]', 'tuple[*tuple_type[int, str]]'), # Should be tuple[int, str]
('Tuple[*Ts]', '[*tuple_type[int, str]]', 'Tuple[*tuple_type[int, str]]'), # Should be Tuple[int, str]
('C[*Ts]', '[tuple_type[int, ...]]', 'C[tuple_type[int, ...]]'),
('tuple[*Ts]', '[tuple_type[int, ...]]', 'tuple[tuple_type[int, ...]]'),
('Tuple[*Ts]', '[tuple_type[int, ...]]', 'Tuple[tuple_type[int, ...]]'),
('C[*Ts]', '[tuple_type[int, ...], tuple_type[str, ...]]', 'C[tuple_type[int, ...], tuple_type[str, ...]]'),
('tuple[*Ts]', '[tuple_type[int, ...], tuple_type[str, ...]]', 'tuple[tuple_type[int, ...], tuple_type[str, ...]]'),
('Tuple[*Ts]', '[tuple_type[int, ...], tuple_type[str, ...]]', 'Tuple[tuple_type[int, ...], tuple_type[str, ...]]'),
('C[*Ts]', '[*tuple_type[int, ...]]', 'C[*tuple_type[int, ...]]'),
('tuple[*Ts]', '[*tuple_type[int, ...]]', 'tuple[*tuple_type[int, ...]]'),
('Tuple[*Ts]', '[*tuple_type[int, ...]]', 'Tuple[*tuple_type[int, ...]]'),
# Technically, multiple unpackings are forbidden by PEP 646, but we
# choose to be less restrictive at runtime, to allow folks room
# to experiment. So all three of these should be valid.
('C[*Ts]', '[*tuple_type[int, ...], *tuple_type[str, ...]]', 'C[*tuple_type[int, ...], *tuple_type[str, ...]]'),
('tuple[*Ts]', '[*tuple_type[int, ...], *tuple_type[str, ...]]', 'tuple[*tuple_type[int, ...], *tuple_type[str, ...]]'),
('Tuple[*Ts]', '[*tuple_type[int, ...], *tuple_type[str, ...]]', 'Tuple[*tuple_type[int, ...], *tuple_type[str, ...]]'),
('C[*Ts]', '[*Ts]', 'C[*Ts]'),
('tuple[*Ts]', '[*Ts]', 'tuple[*Ts]'),
('Tuple[*Ts]', '[*Ts]', 'Tuple[*Ts]'),
('C[*Ts]', '[T, *Ts]', 'C[T, *Ts]'),
('tuple[*Ts]', '[T, *Ts]', 'tuple[T, *Ts]'),
('Tuple[*Ts]', '[T, *Ts]', 'Tuple[T, *Ts]'),
('C[*Ts]', '[*Ts, T]', 'C[*Ts, T]'),
('tuple[*Ts]', '[*Ts, T]', 'tuple[*Ts, T]'),
('Tuple[*Ts]', '[*Ts, T]', 'Tuple[*Ts, T]'),
('C[T, *Ts]', '[int]', 'C[int]'),
('tuple[T, *Ts]', '[int]', 'tuple[int]'),
('Tuple[T, *Ts]', '[int]', 'Tuple[int]'),
('C[T, *Ts]', '[int, str]', 'C[int, str]'),
('tuple[T, *Ts]', '[int, str]', 'tuple[int, str]'),
('Tuple[T, *Ts]', '[int, str]', 'Tuple[int, str]'),
('C[T, *Ts]', '[int, str, bool]', 'C[int, str, bool]'),
('tuple[T, *Ts]', '[int, str, bool]', 'tuple[int, str, bool]'),
('Tuple[T, *Ts]', '[int, str, bool]', 'Tuple[int, str, bool]'),
('C[T, *Ts]', '[*tuple[int, ...]]', 'C[*tuple[int, ...]]'), # Should be C[int, *tuple[int, ...]]
('C[T, *Ts]', '[*Tuple[int, ...]]', 'TypeError'), # Ditto
('tuple[T, *Ts]', '[*tuple[int, ...]]', 'tuple[*tuple[int, ...]]'), # Should be tuple[int, *tuple[int, ...]]
('tuple[T, *Ts]', '[*Tuple[int, ...]]', 'TypeError'), # Should be tuple[int, *Tuple[int, ...]]
('Tuple[T, *Ts]', '[*tuple[int, ...]]', 'Tuple[*tuple[int, ...]]'), # Should be Tuple[int, *tuple[int, ...]]
('Tuple[T, *Ts]', '[*Tuple[int, ...]]', 'TypeError'), # Should be Tuple[int, *Tuple[int, ...]]
('C[*Ts, T]', '[int]', 'C[int]'),
('tuple[*Ts, T]', '[int]', 'tuple[int]'),
('Tuple[*Ts, T]', '[int]', 'Tuple[int]'),
('C[*Ts, T]', '[int, str]', 'C[int, str]'),
('tuple[*Ts, T]', '[int, str]', 'tuple[int, str]'),
('Tuple[*Ts, T]', '[int, str]', 'Tuple[int, str]'),
('C[*Ts, T]', '[int, str, bool]', 'C[int, str, bool]'),
('tuple[*Ts, T]', '[int, str, bool]', 'tuple[int, str, bool]'),
('Tuple[*Ts, T]', '[int, str, bool]', 'Tuple[int, str, bool]'),
('generic[T, *tuple_type[int, ...]]', '[str]', 'generic[str, *tuple_type[int, ...]]'),
('generic[T1, T2, *tuple_type[int, ...]]', '[str, bool]', 'generic[str, bool, *tuple_type[int, ...]]'),
('generic[T1, *tuple_type[int, ...], T2]', '[str, bool]', 'generic[str, *tuple_type[int, ...], bool]'),
('generic[T1, *tuple_type[int, ...], T2]', '[str, bool, float]', 'TypeError'),
]
for alias_template, args_template, expected_template in tests:
rendered_templates = template_replace(
templates=[alias_template, args_template, expected_template],
replacements={'generic': generics, 'tuple_type': tuple_types}
)
for alias_str, args_str, expected_str in rendered_templates:
with self.subTest(alias=alias_str, args=args_str, expected=expected_str):
if expected_str == 'TypeError':
with self.assertRaises(TypeError):
eval(alias_str + args_str)
else:
self.assertEqual(
eval(alias_str + args_str),
eval(expected_str)
)
class UnpackTests(BaseTestCase):
def test_accepts_single_type(self):
Unpack[Tuple[int]]
def test_rejects_multiple_types(self):
with self.assertRaises(TypeError):
Unpack[Tuple[int], Tuple[str]]
def test_rejects_multiple_parameterization(self):
with self.assertRaises(TypeError):
Unpack[Tuple[int]][Tuple[int]]
def test_cannot_be_called(self):
with self.assertRaises(TypeError):
Unpack()
class TypeVarTupleTests(BaseTestCase):
def assertEndsWith(self, string, tail):
if not string.endswith(tail):
self.fail(f"String {string!r} does not end with {tail!r}")
def test_name(self):
Ts = TypeVarTuple('Ts')
self.assertEqual(Ts.__name__, 'Ts')
Ts2 = TypeVarTuple('Ts2')
self.assertEqual(Ts2.__name__, 'Ts2')
def test_instance_is_equal_to_itself(self):
Ts = TypeVarTuple('Ts')
self.assertEqual(Ts, Ts)
def test_different_instances_are_different(self):
self.assertNotEqual(TypeVarTuple('Ts'), TypeVarTuple('Ts'))
def test_instance_isinstance_of_typevartuple(self):
Ts = TypeVarTuple('Ts')
self.assertIsInstance(Ts, TypeVarTuple)
def test_cannot_call_instance(self):
Ts = TypeVarTuple('Ts')
with self.assertRaises(TypeError):
Ts()
def test_unpacked_typevartuple_is_equal_to_itself(self):
Ts = TypeVarTuple('Ts')
self.assertEqual(Unpack[Ts], Unpack[Ts])
def test_parameterised_tuple_is_equal_to_itself(self):
Ts = TypeVarTuple('Ts')
self.assertEqual(tuple[Unpack[Ts]], tuple[Unpack[Ts]])
self.assertEqual(Tuple[Unpack[Ts]], Tuple[Unpack[Ts]])
def tests_tuple_arg_ordering_matters(self):
Ts1 = TypeVarTuple('Ts1')
Ts2 = TypeVarTuple('Ts2')
self.assertNotEqual(
tuple[Unpack[Ts1], Unpack[Ts2]],
tuple[Unpack[Ts2], Unpack[Ts1]],
)
self.assertNotEqual(
Tuple[Unpack[Ts1], Unpack[Ts2]],
Tuple[Unpack[Ts2], Unpack[Ts1]],
)
def test_tuple_args_and_parameters_are_correct(self):
Ts = TypeVarTuple('Ts')
t1 = tuple[Unpack[Ts]]
self.assertEqual(t1.__args__, (Unpack[Ts],))
self.assertEqual(t1.__parameters__, (Ts,))
t2 = Tuple[Unpack[Ts]]
self.assertEqual(t2.__args__, (Unpack[Ts],))
self.assertEqual(t2.__parameters__, (Ts,))
def test_var_substitution(self):
Ts = TypeVarTuple('Ts')
T = TypeVar('T')
T2 = TypeVar('T2')
class G(Generic[Unpack[Ts]]): pass
for A in G, Tuple, tuple:
B = A[Unpack[Ts]]
self.assertEqual(B[()], A[()])
self.assertEqual(B[float], A[float])
self.assertEqual(B[float, str], A[float, str])
C = List[A[Unpack[Ts]]]
self.assertEqual(C[()], List[A[()]])
self.assertEqual(C[float], List[A[float]])
self.assertEqual(C[float, str], List[A[float, str]])
D = A[T, Unpack[Ts], T2]
with self.assertRaises(TypeError):
D[()]
with self.assertRaises(TypeError):
D[float]
self.assertEqual(D[float, str], A[float, str])
self.assertEqual(D[float, str, int], A[float, str, int])
self.assertEqual(D[float, str, int, bytes], A[float, str, int, bytes])
E = Tuple[List[T], A[Unpack[Ts]], List[T2]]
with self.assertRaises(TypeError):
E[()]
with self.assertRaises(TypeError):
E[float]
if A != Tuple:
self.assertEqual(E[float, str],
Tuple[List[float], A[()], List[str]])
self.assertEqual(E[float, str, int],
Tuple[List[float], A[str], List[int]])
self.assertEqual(E[float, str, int, bytes],
Tuple[List[float], A[str, int], List[bytes]])
def test_bad_var_substitution(self):
Ts = TypeVarTuple('Ts')
T = TypeVar('T')
T2 = TypeVar('T2')
class G(Generic[Unpack[Ts]]): pass
for A in G, Tuple, tuple:
B = A[Ts]
with self.assertRaises(TypeError):
B[int, str]
C = A[T, T2]
with self.assertRaises(TypeError):
C[Unpack[Ts]]
def test_repr_is_correct(self):
Ts = TypeVarTuple('Ts')
T = TypeVar('T')
T2 = TypeVar('T2')
class G(Generic[Unpack[Ts]]): pass