-
Notifications
You must be signed in to change notification settings - Fork 117
/
Copy pathtest_checkers.py
1525 lines (1228 loc) · 45.8 KB
/
test_checkers.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 collections.abc
import sys
import types
from contextlib import nullcontext
from datetime import timedelta
from functools import partial
from io import BytesIO, StringIO
from pathlib import Path
from typing import (
IO,
AbstractSet,
Annotated,
Any,
AnyStr,
BinaryIO,
Callable,
Collection,
ContextManager,
Dict,
ForwardRef,
FrozenSet,
Iterable,
Iterator,
List,
Literal,
Mapping,
MutableMapping,
Optional,
Protocol,
Sequence,
Set,
Sized,
TextIO,
Tuple,
Type,
TypeVar,
Union,
)
import pytest
from typing_extensions import LiteralString
from typeguard import (
CollectionCheckStrategy,
ForwardRefPolicy,
TypeCheckError,
TypeCheckMemo,
TypeHintWarning,
check_type,
check_type_internal,
suppress_type_checks,
)
from typeguard._checkers import is_typeddict
from typeguard._utils import qualified_name
from . import (
Child,
Employee,
JSONType,
Parent,
TChild,
TIntStr,
TParent,
TTypingConstrained,
myint,
mylist,
)
if sys.version_info >= (3, 11):
SubclassableAny = Any
else:
from typing_extensions import Any as SubclassableAny
if sys.version_info >= (3, 10):
from typing import Concatenate, ParamSpec, TypeGuard
else:
from typing_extensions import Concatenate, ParamSpec, TypeGuard
P = ParamSpec("P")
@pytest.mark.skipif(
sys.version_info >= (3, 13), reason="AnyStr is deprecated on Python 3.13"
)
class TestAnyStr:
@pytest.mark.parametrize(
"value", [pytest.param("bar", id="str"), pytest.param(b"bar", id="bytes")]
)
def test_valid(self, value):
check_type(value, AnyStr)
def test_bad_type(self):
pytest.raises(TypeCheckError, check_type, 4, AnyStr).match(
r"does not match any of the constraints \(bytes, str\)"
)
class TestBytesLike:
@pytest.mark.parametrize(
"value",
[
pytest.param(b"test", id="bytes"),
pytest.param(bytearray(b"test"), id="bytearray"),
pytest.param(memoryview(b"test"), id="memoryview"),
],
)
def test_valid(self, value):
check_type(value, bytes)
def test_fail(self):
pytest.raises(TypeCheckError, check_type, "test", bytes).match(
r"str is not bytes-like"
)
class TestFloat:
@pytest.mark.parametrize(
"value", [pytest.param(3, id="int"), pytest.param(3.87, id="float")]
)
def test_valid(self, value):
check_type(value, float)
def test_bad_type(self):
pytest.raises(TypeCheckError, check_type, "foo", float).match(
r"str is neither float or int"
)
class TestComplexNumber:
@pytest.mark.parametrize(
"value",
[
pytest.param(3, id="int"),
pytest.param(3.87, id="float"),
pytest.param(3.87 + 8j, id="complex"),
],
)
def test_valid(self, value):
check_type(value, complex)
def test_bad_type(self):
pytest.raises(TypeCheckError, check_type, "foo", complex).match(
"str is neither complex, float or int"
)
class TestCallable:
def test_any_args(self):
def some_callable(x: int, y: str) -> int:
pass
check_type(some_callable, Callable[..., int])
def test_exact_arg_count(self):
def some_callable(x: int, y: str) -> int:
pass
check_type(some_callable, Callable[[int, str], int])
def test_bad_type(self):
pytest.raises(TypeCheckError, check_type, 5, Callable[..., int]).match(
"is not callable"
)
def test_too_few_arguments(self):
def some_callable(x: int) -> int:
pass
pytest.raises(
TypeCheckError, check_type, some_callable, Callable[[int, str], int]
).match(
r"has too few arguments in its declaration; expected 2 but 1 argument\(s\) "
r"declared"
)
def test_too_many_arguments(self):
def some_callable(x: int, y: str, z: float) -> int:
pass
pytest.raises(
TypeCheckError, check_type, some_callable, Callable[[int, str], int]
).match(
r"has too many mandatory positional arguments in its declaration; expected "
r"2 but 3 mandatory positional argument\(s\) declared"
)
def test_mandatory_kwonlyargs(self):
def some_callable(x: int, y: str, *, z: float, bar: str) -> int:
pass
pytest.raises(
TypeCheckError, check_type, some_callable, Callable[[int, str], int]
).match(r"has mandatory keyword-only arguments in its declaration: z, bar")
def test_class(self):
"""
Test that passing a class as a callable does not count the "self" argument
against the ones declared in the Callable specification.
"""
class SomeClass:
def __init__(self, x: int, y: str):
pass
check_type(SomeClass, Callable[[int, str], Any])
def test_plain(self):
def callback(a):
pass
check_type(callback, Callable)
def test_partial_class(self):
"""
Test that passing a bound method as a callable does not count the "self"
argument against the ones declared in the Callable specification.
"""
class SomeClass:
def __init__(self, x: int, y: str):
pass
check_type(partial(SomeClass, y="foo"), Callable[[int], Any])
def test_bound_method(self):
"""
Test that passing a bound method as a callable does not count the "self"
argument against the ones declared in the Callable specification.
"""
check_type(Child().method, Callable[[int], Any])
def test_partial_bound_method(self):
"""
Test that passing a bound method as a callable does not count the "self"
argument against the ones declared in the Callable specification.
"""
check_type(partial(Child().method, 1), Callable[[], Any])
def test_defaults(self):
"""
Test that a callable having "too many" arguments don't raise an error if the
extra arguments have default values.
"""
def some_callable(x: int, y: str, z: float = 1.2) -> int:
pass
check_type(some_callable, Callable[[int, str], Any])
def test_builtin(self):
"""
Test that checking a Callable annotation against a builtin callable does not
raise an error.
"""
check_type([].append, Callable[[int], Any])
def test_concatenate(self):
"""Test that ``Concatenate`` in the arglist is ignored."""
check_type([].append, Callable[Concatenate[object, P], Any])
def test_positional_only_arg_with_default(self):
def some_callable(x: int = 1, /) -> None:
pass
check_type(some_callable, Callable[[int], Any])
class TestLiteral:
def test_literal_union(self):
annotation = Union[str, Literal[1, 6, 8]]
check_type(6, annotation)
pytest.raises(TypeCheckError, check_type, 4, annotation).match(
r"int did not match any element in the union:\n"
r" str: is not an instance of str\n"
r" Literal\[1, 6, 8\]: is not any of \(1, 6, 8\)$"
)
def test_literal_nested(self):
annotation = Literal[1, Literal["x", "a", Literal["z"]], 6, 8]
check_type("z", annotation)
pytest.raises(TypeCheckError, check_type, 4, annotation).match(
r"int is not any of \(1, 'x', 'a', 'z', 6, 8\)$"
)
def test_literal_int_as_bool(self):
pytest.raises(TypeCheckError, check_type, 0, Literal[False])
pytest.raises(TypeCheckError, check_type, 1, Literal[True])
def test_literal_illegal_value(self):
pytest.raises(TypeError, check_type, 4, Literal[1, 1.1]).match(
r"Illegal literal value: 1.1$"
)
class TestMapping:
class DummyMapping(collections.abc.Mapping):
_values = {"a": 1, "b": 10, "c": 100}
def __getitem__(self, index: str):
return self._values[index]
def __iter__(self):
return iter(self._values)
def __len__(self) -> int:
return len(self._values)
def test_bad_type(self):
pytest.raises(TypeCheckError, check_type, 5, Mapping[str, int]).match(
"is not a mapping"
)
def test_bad_key_type(self):
pytest.raises(
TypeCheckError, check_type, TestMapping.DummyMapping(), Mapping[int, int]
).match(
f"key 'a' of {__name__}.TestMapping.DummyMapping is not an instance of int"
)
def test_bad_value_type(self):
pytest.raises(
TypeCheckError, check_type, TestMapping.DummyMapping(), Mapping[str, str]
).match(
f"value of key 'a' of {__name__}.TestMapping.DummyMapping is not an "
f"instance of str"
)
def test_bad_key_type_full_check(self):
pytest.raises(
TypeCheckError,
check_type,
{"x": 1, 3: 2},
Mapping[str, int],
collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS,
).match("key 3 of dict is not an instance of str")
def test_bad_value_type_full_check(self):
pytest.raises(
TypeCheckError,
check_type,
{"x": 1, "y": "a"},
Mapping[str, int],
collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS,
).match("value of key 'y' of dict is not an instance of int")
def test_any_value_type(self):
check_type(TestMapping.DummyMapping(), Mapping[str, Any])
class TestMutableMapping:
class DummyMutableMapping(collections.abc.MutableMapping):
_values = {"a": 1, "b": 10, "c": 100}
def __getitem__(self, index: str):
return self._values[index]
def __setitem__(self, key, value):
self._values[key] = value
def __delitem__(self, key):
del self._values[key]
def __iter__(self):
return iter(self._values)
def __len__(self) -> int:
return len(self._values)
def test_bad_type(self):
pytest.raises(TypeCheckError, check_type, 5, MutableMapping[str, int]).match(
"is not a mutable mapping"
)
def test_bad_key_type(self):
pytest.raises(
TypeCheckError,
check_type,
TestMutableMapping.DummyMutableMapping(),
MutableMapping[int, int],
).match(
f"key 'a' of {__name__}.TestMutableMapping.DummyMutableMapping is not an "
f"instance of int"
)
def test_bad_value_type(self):
pytest.raises(
TypeCheckError,
check_type,
TestMutableMapping.DummyMutableMapping(),
MutableMapping[str, str],
).match(
f"value of key 'a' of {__name__}.TestMutableMapping.DummyMutableMapping "
f"is not an instance of str"
)
class TestDict:
def test_bad_type(self):
pytest.raises(TypeCheckError, check_type, 5, Dict[str, int]).match(
"int is not a dict"
)
def test_bad_key_type(self):
pytest.raises(TypeCheckError, check_type, {1: 2}, Dict[str, int]).match(
"key 1 of dict is not an instance of str"
)
def test_bad_value_type(self):
pytest.raises(TypeCheckError, check_type, {"x": "a"}, Dict[str, int]).match(
"value of key 'x' of dict is not an instance of int"
)
def test_bad_key_type_full_check(self):
pytest.raises(
TypeCheckError,
check_type,
{"x": 1, 3: 2},
Dict[str, int],
collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS,
).match("key 3 of dict is not an instance of str")
def test_bad_value_type_full_check(self):
pytest.raises(
TypeCheckError,
check_type,
{"x": 1, "y": "a"},
Dict[str, int],
collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS,
).match("value of key 'y' of dict is not an instance of int")
def test_custom_dict_generator_items(self):
class CustomDict(dict):
def items(self):
for key in self:
yield key, self[key]
check_type(CustomDict(a=1), Dict[str, int])
class TestTypedDict:
@pytest.mark.parametrize(
"value, total, error_re",
[
pytest.param({"x": 6, "y": "foo"}, True, None, id="correct"),
pytest.param(
{"y": "foo"},
True,
r'dict is missing required key\(s\): "x"',
id="missing_x",
),
pytest.param(
{"x": 6, "y": 3}, True, "dict is not an instance of str", id="wrong_y"
),
pytest.param(
{"x": 6},
True,
r'is missing required key\(s\): "y"',
id="missing_y_error",
),
pytest.param({"x": 6}, False, None, id="missing_y_ok"),
pytest.param(
{"x": "abc"}, False, "dict is not an instance of int", id="wrong_x"
),
pytest.param(
{"x": 6, "foo": "abc"},
False,
r'dict has unexpected extra key\(s\): "foo"',
id="unknown_key",
),
pytest.param(
None,
True,
"is not a dict",
id="not_dict",
),
],
)
def test_typed_dict(
self, value, total: bool, error_re: Optional[str], typing_provider
):
class DummyDict(typing_provider.TypedDict, total=total):
x: int
y: str
if error_re:
pytest.raises(TypeCheckError, check_type, value, DummyDict).match(error_re)
else:
check_type(value, DummyDict)
def test_inconsistent_keys_invalid(self, typing_provider):
class DummyDict(typing_provider.TypedDict):
x: int
pytest.raises(
TypeCheckError, check_type, {"x": 1, "y": 2, b"z": 3}, DummyDict
).match(r'dict has unexpected extra key\(s\): "y", "b\'z\'"')
def test_notrequired_pass(self, typing_provider):
try:
NotRequired = typing_provider.NotRequired
except AttributeError:
pytest.skip(f"'NotRequired' not found in {typing_provider.__name__!r}")
class DummyDict(typing_provider.TypedDict):
x: int
y: NotRequired[int]
z: "NotRequired[int]"
check_type({"x": 8}, DummyDict)
def test_notrequired_fail(self, typing_provider):
try:
NotRequired = typing_provider.NotRequired
except AttributeError:
pytest.skip(f"'NotRequired' not found in {typing_provider.__name__!r}")
class DummyDict(typing_provider.TypedDict):
x: int
y: NotRequired[int]
z: "NotRequired[int]"
with pytest.raises(
TypeCheckError, match=r"value of key 'y' of dict is not an instance of int"
):
check_type({"x": 1, "y": "foo"}, DummyDict)
with pytest.raises(
TypeCheckError, match=r"value of key 'z' of dict is not an instance of int"
):
check_type({"x": 1, "y": 6, "z": "foo"}, DummyDict)
def test_is_typeddict(self, typing_provider):
# Ensure both typing.TypedDict and typing_extensions.TypedDict are recognized
class DummyDict(typing_provider.TypedDict):
x: int
assert is_typeddict(DummyDict)
assert not is_typeddict(dict)
class TestList:
def test_bad_type(self):
pytest.raises(TypeCheckError, check_type, 5, List[int]).match(
"int is not a list"
)
def test_first_check_success(self):
check_type(
["aa", "bb", 1],
List[str],
collection_check_strategy=CollectionCheckStrategy.FIRST_ITEM,
)
def test_first_check_empty(self):
check_type([], List[str])
def test_first_check_fail(self):
pytest.raises(TypeCheckError, check_type, ["bb"], List[int]).match(
"list is not an instance of int"
)
def test_full_check_fail(self):
pytest.raises(
TypeCheckError,
check_type,
[1, 2, "bb"],
List[int],
collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS,
).match("list is not an instance of int")
class TestSequence:
def test_bad_type(self):
pytest.raises(TypeCheckError, check_type, 5, Sequence[int]).match(
"int is not a sequence"
)
@pytest.mark.parametrize(
"value",
[pytest.param([1, "bb"], id="list"), pytest.param((1, "bb"), id="tuple")],
)
def test_first_check_success(self, value):
check_type(
value,
Sequence[int],
collection_check_strategy=CollectionCheckStrategy.FIRST_ITEM,
)
def test_first_check_empty(self):
check_type([], Sequence[int])
def test_first_check_fail(self):
pytest.raises(TypeCheckError, check_type, ["bb"], Sequence[int]).match(
"list is not an instance of int"
)
def test_full_check_fail(self):
pytest.raises(
TypeCheckError,
check_type,
[1, 2, "bb"],
Sequence[int],
).match("list is not an instance of int")
class TestAbstractSet:
def test_custom_type(self):
class DummySet(AbstractSet[int]):
def __contains__(self, x: object) -> bool:
return x == 1
def __len__(self) -> int:
return 1
def __iter__(self) -> Iterator[int]:
yield 1
check_type(DummySet(), AbstractSet[int])
def test_bad_type(self):
pytest.raises(TypeCheckError, check_type, 5, AbstractSet[int]).match(
"int is not a set"
)
def test_first_check_fail(self, sample_set):
# Create a set which, when iterated, returns "bb" as the first item
pytest.raises(TypeCheckError, check_type, sample_set, AbstractSet[int]).match(
"set is not an instance of int"
)
def test_full_check_fail(self):
pytest.raises(
TypeCheckError,
check_type,
{1, 2, "bb"},
AbstractSet[int],
collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS,
).match("set is not an instance of int")
class TestSet:
def test_bad_type(self):
pytest.raises(TypeCheckError, check_type, 5, Set[int]).match("int is not a set")
def test_valid(self):
check_type({1, 2}, Set[int])
def test_first_check_empty(self):
check_type(set(), Set[int])
def test_first_check_fail(self, sample_set: set):
pytest.raises(TypeCheckError, check_type, sample_set, Set[int]).match(
"set is not an instance of int"
)
def test_full_check_fail(self):
pytest.raises(
TypeCheckError,
check_type,
{1, 2, "bb"},
Set[int],
collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS,
).match("set is not an instance of int")
class TestFrozenSet:
def test_bad_type(self):
pytest.raises(TypeCheckError, check_type, 5, FrozenSet[int]).match(
"int is not a frozenset"
)
def test_valid(self):
check_type(frozenset({1, 2}), FrozenSet[int])
def test_first_check_empty(self):
check_type(frozenset(), FrozenSet[int])
def test_first_check_fail(self, sample_set: set):
pytest.raises(
TypeCheckError, check_type, frozenset(sample_set), FrozenSet[int]
).match("set is not an instance of int")
def test_full_check_fail(self):
pytest.raises(
TypeCheckError,
check_type,
frozenset({1, 2, "bb"}),
FrozenSet[int],
collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS,
).match("set is not an instance of int")
def test_set_against_frozenset(self, sample_set: set):
pytest.raises(TypeCheckError, check_type, sample_set, FrozenSet[int]).match(
"set is not a frozenset"
)
@pytest.mark.parametrize(
"annotated_type",
[
pytest.param(Tuple, id="typing"),
pytest.param(
tuple,
id="builtin",
marks=[
pytest.mark.skipif(
sys.version_info < (3, 9),
reason="builtins.tuple is not parametrizable before Python 3.9",
)
],
),
],
)
class TestTuple:
def test_bad_type(self, annotated_type: Any):
pytest.raises(TypeCheckError, check_type, 5, annotated_type[int]).match(
"int is not a tuple"
)
def test_first_check_empty(self, annotated_type: Any):
check_type((), annotated_type[int, ...])
def test_unparametrized_tuple(self, annotated_type: Any):
check_type((5, "foo"), annotated_type)
def test_unparametrized_tuple_fail(self, annotated_type: Any):
pytest.raises(TypeCheckError, check_type, 5, annotated_type).match(
"int is not a tuple"
)
def test_too_many_elements(self, annotated_type: Any):
pytest.raises(
TypeCheckError, check_type, (1, "aa", 2), annotated_type[int, str]
).match(r"tuple has wrong number of elements \(expected 2, got 3 instead\)")
def test_too_few_elements(self, annotated_type: Any):
pytest.raises(TypeCheckError, check_type, (1,), annotated_type[int, str]).match(
r"tuple has wrong number of elements \(expected 2, got 1 instead\)"
)
def test_bad_element(self, annotated_type: Any):
pytest.raises(
TypeCheckError, check_type, (1, 2), annotated_type[int, str]
).match("tuple is not an instance of str")
def test_ellipsis_bad_element(self, annotated_type: Any):
pytest.raises(
TypeCheckError, check_type, ("blah",), annotated_type[int, ...]
).match("tuple is not an instance of int")
def test_ellipsis_bad_element_full_check(self, annotated_type: Any):
pytest.raises(
TypeCheckError,
check_type,
(1, 2, "blah"),
annotated_type[int, ...],
collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS,
).match("tuple is not an instance of int")
def test_empty_tuple(self, annotated_type: Any):
check_type((), annotated_type[()])
def test_empty_tuple_fail(self, annotated_type: Any):
pytest.raises(TypeCheckError, check_type, (1,), annotated_type[()]).match(
"tuple is not an empty tuple"
)
class TestNamedTuple:
def test_valid(self):
check_type(Employee("bob", 1), Employee)
def test_type_mismatch(self):
pytest.raises(TypeCheckError, check_type, ("bob", 1), Employee).match(
r"tuple is not a named tuple of type tests.Employee"
)
def test_wrong_field_type(self):
pytest.raises(TypeCheckError, check_type, Employee(2, 1), Employee).match(
r"Employee is not an instance of str"
)
class TestUnion:
@pytest.mark.parametrize(
"value", [pytest.param(6, id="int"), pytest.param("aa", id="str")]
)
def test_valid(self, value):
check_type(value, Union[str, int])
def test_typing_type_fail(self):
pytest.raises(TypeCheckError, check_type, 1, Union[str, Collection]).match(
"int did not match any element in the union:\n"
" str: is not an instance of str\n"
" Collection: is not an instance of collections.abc.Collection"
)
@pytest.mark.parametrize(
"annotation",
[
pytest.param(Union[str, int], id="pep484"),
pytest.param(
ForwardRef("str | int"),
id="pep604",
marks=[
pytest.mark.skipif(
sys.version_info < (3, 10), reason="Requires Python 3.10+"
)
],
),
],
)
@pytest.mark.parametrize(
"value", [pytest.param(6.5, id="float"), pytest.param(b"aa", id="bytes")]
)
def test_union_fail(self, annotation, value):
qualname = qualified_name(value)
pytest.raises(TypeCheckError, check_type, value, annotation).match(
f"{qualname} did not match any element in the union:\n"
f" str: is not an instance of str\n"
f" int: is not an instance of int"
)
@pytest.mark.skipif(
sys.implementation.name != "cpython",
reason="Test relies on CPython's reference counting behavior",
)
def test_union_reference_leak(self):
class Leak:
def __del__(self):
nonlocal leaked
leaked = False
def inner1():
leak = Leak() # noqa: F841
check_type(b"asdf", Union[str, bytes])
leaked = True
inner1()
assert not leaked
def inner2():
leak = Leak() # noqa: F841
check_type(b"asdf", Union[bytes, str])
leaked = True
inner2()
assert not leaked
def inner3():
leak = Leak() # noqa: F841
with pytest.raises(TypeCheckError, match="any element in the union:"):
check_type(1, Union[str, bytes])
leaked = True
inner3()
assert not leaked
@pytest.mark.skipif(
sys.implementation.name != "cpython",
reason="Test relies on CPython's reference counting behavior",
)
@pytest.mark.skipif(sys.version_info < (3, 10), reason="UnionType requires 3.10")
def test_uniontype_reference_leak(self):
class Leak:
def __del__(self):
nonlocal leaked
leaked = False
def inner1():
leak = Leak() # noqa: F841
check_type(b"asdf", str | bytes)
leaked = True
inner1()
assert not leaked
def inner2():
leak = Leak() # noqa: F841
check_type(b"asdf", bytes | str)
leaked = True
inner2()
assert not leaked
def inner3():
leak = Leak() # noqa: F841
with pytest.raises(TypeCheckError, match="any element in the union:"):
check_type(1, Union[str, bytes])
leaked = True
inner3()
assert not leaked
@pytest.mark.skipif(sys.version_info < (3, 10), reason="UnionType requires 3.10")
def test_raw_uniontype_success(self):
check_type(str | int, types.UnionType)
@pytest.mark.skipif(sys.version_info < (3, 10), reason="UnionType requires 3.10")
def test_raw_uniontype_fail(self):
with pytest.raises(
TypeCheckError, match=r"class str is not an instance of \w+\.UnionType$"
):
check_type(str, types.UnionType)
class TestTypevar:
def test_bound(self):
check_type(Child(), TParent)
def test_bound_fail(self):
with pytest.raises(TypeCheckError, match="is not an instance of tests.Child"):
check_type(Parent(), TChild)
@pytest.mark.parametrize(
"value", [pytest.param([6, 7], id="int"), pytest.param({"aa", "bb"}, id="str")]
)
def test_collection_constraints(self, value):
check_type(value, TTypingConstrained)
def test_collection_constraints_fail(self):
pytest.raises(TypeCheckError, check_type, {1, 2}, TTypingConstrained).match(
r"set does not match any of the constraints \(List\[int\], "
r"AbstractSet\[str\]\)"
)
def test_constraints_fail(self):
pytest.raises(TypeCheckError, check_type, 2.5, TIntStr).match(
r"float does not match any of the constraints \(int, str\)"
)
class TestNewType:
def test_simple_valid(self):
check_type(1, myint)
def test_simple_bad_value(self):
pytest.raises(TypeCheckError, check_type, "a", myint).match(
r"str is not an instance of int"
)
def test_generic_valid(self):
check_type([1], mylist)
def test_generic_bad_value(self):
pytest.raises(TypeCheckError, check_type, ["a"], mylist).match(
r"item 0 of list is not an instance of int"
)
class TestType:
@pytest.mark.parametrize("annotation", [pytest.param(Type), pytest.param(type)])
def test_unparametrized(self, annotation: Any):
check_type(TestNewType, annotation)
@pytest.mark.parametrize("annotation", [pytest.param(Type), pytest.param(type)])
def test_unparametrized_fail(self, annotation: Any):
pytest.raises(TypeCheckError, check_type, 1, annotation).match(
"int is not a class"
)
@pytest.mark.parametrize(
"value", [pytest.param(Parent, id="exact"), pytest.param(Child, id="subclass")]
)
def test_parametrized(self, value):
check_type(value, Type[Parent])
def test_parametrized_fail(self):
pytest.raises(TypeCheckError, check_type, int, Type[str]).match(
"class int is not a subclass of str"
)
@pytest.mark.parametrize(
"value", [pytest.param(str, id="str"), pytest.param(int, id="int")]
)
def test_union(self, value):
check_type(value, Type[Union[str, int, list]])
def test_union_any(self):
check_type(list, Type[Union[str, int, Any]])
def test_any(self):
check_type(list, Type[Any])
def test_union_fail(self):
pytest.raises(
TypeCheckError, check_type, dict, Type[Union[str, int, list]]
).match(
"class dict did not match any element in the union:\n"
" str: is not a subclass of str\n"
" int: is not a subclass of int\n"
" list: is not a subclass of list"
)