-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
teststubtest.py
1628 lines (1521 loc) · 51.2 KB
/
teststubtest.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
from __future__ import annotations
import contextlib
import inspect
import io
import os
import re
import sys
import tempfile
import textwrap
import unittest
from typing import Any, Callable, Iterator
import mypy.stubtest
from mypy.stubtest import parse_options, test_stubs
from mypy.test.data import root_dir
@contextlib.contextmanager
def use_tmp_dir(mod_name: str) -> Iterator[str]:
current = os.getcwd()
current_syspath = sys.path[:]
with tempfile.TemporaryDirectory() as tmp:
try:
os.chdir(tmp)
if sys.path[0] != tmp:
sys.path.insert(0, tmp)
yield tmp
finally:
sys.path = current_syspath[:]
if mod_name in sys.modules:
del sys.modules[mod_name]
os.chdir(current)
TEST_MODULE_NAME = "test_module"
stubtest_typing_stub = """
Any = object()
class _SpecialForm:
def __getitem__(self, typeargs: Any) -> object: ...
Callable: _SpecialForm = ...
Generic: _SpecialForm = ...
Protocol: _SpecialForm = ...
Union: _SpecialForm = ...
class TypeVar:
def __init__(self, name, covariant: bool = ..., contravariant: bool = ...) -> None: ...
class ParamSpec:
def __init__(self, name: str) -> None: ...
AnyStr = TypeVar("AnyStr", str, bytes)
_T = TypeVar("_T")
_T_co = TypeVar("_T_co", covariant=True)
_K = TypeVar("_K")
_V = TypeVar("_V")
_S = TypeVar("_S", contravariant=True)
_R = TypeVar("_R", covariant=True)
class Coroutine(Generic[_T_co, _S, _R]): ...
class Iterable(Generic[_T_co]): ...
class Mapping(Generic[_K, _V]): ...
class Match(Generic[AnyStr]): ...
class Sequence(Iterable[_T_co]): ...
class Tuple(Sequence[_T_co]): ...
def overload(func: _T) -> _T: ...
"""
stubtest_builtins_stub = """
from typing import Generic, Mapping, Sequence, TypeVar, overload
T = TypeVar('T')
T_co = TypeVar('T_co', covariant=True)
KT = TypeVar('KT')
VT = TypeVar('VT')
class object:
__module__: str
def __init__(self) -> None: pass
class type: ...
class tuple(Sequence[T_co], Generic[T_co]): ...
class dict(Mapping[KT, VT]): ...
class function: pass
class ellipsis: pass
class int: ...
class float: ...
class bool(int): ...
class str: ...
class bytes: ...
class list(Sequence[T]): ...
def property(f: T) -> T: ...
def classmethod(f: T) -> T: ...
def staticmethod(f: T) -> T: ...
"""
def run_stubtest(
stub: str, runtime: str, options: list[str], config_file: str | None = None
) -> str:
with use_tmp_dir(TEST_MODULE_NAME) as tmp_dir:
with open("builtins.pyi", "w") as f:
f.write(stubtest_builtins_stub)
with open("typing.pyi", "w") as f:
f.write(stubtest_typing_stub)
with open(f"{TEST_MODULE_NAME}.pyi", "w") as f:
f.write(stub)
with open(f"{TEST_MODULE_NAME}.py", "w") as f:
f.write(runtime)
if config_file:
with open(f"{TEST_MODULE_NAME}_config.ini", "w") as f:
f.write(config_file)
options = options + ["--mypy-config-file", f"{TEST_MODULE_NAME}_config.ini"]
output = io.StringIO()
with contextlib.redirect_stdout(output):
test_stubs(parse_options([TEST_MODULE_NAME] + options), use_builtins_fixtures=True)
# remove cwd as it's not available from outside
return (
output.getvalue()
.replace(os.path.realpath(tmp_dir) + os.sep, "")
.replace(tmp_dir + os.sep, "")
)
class Case:
def __init__(self, stub: str, runtime: str, error: str | None):
self.stub = stub
self.runtime = runtime
self.error = error
def collect_cases(fn: Callable[..., Iterator[Case]]) -> Callable[..., None]:
"""run_stubtest used to be slow, so we used this decorator to combine cases.
If you're reading this and bored, feel free to refactor this and make it more like
other mypy tests.
"""
def test(*args: Any, **kwargs: Any) -> None:
cases = list(fn(*args, **kwargs))
expected_errors = set()
for c in cases:
if c.error is None:
continue
expected_error = c.error
if expected_error == "":
expected_error = TEST_MODULE_NAME
elif not expected_error.startswith(f"{TEST_MODULE_NAME}."):
expected_error = f"{TEST_MODULE_NAME}.{expected_error}"
assert expected_error not in expected_errors, (
"collect_cases merges cases into a single stubtest invocation; we already "
"expect an error for {}".format(expected_error)
)
expected_errors.add(expected_error)
output = run_stubtest(
stub="\n\n".join(textwrap.dedent(c.stub.lstrip("\n")) for c in cases),
runtime="\n\n".join(textwrap.dedent(c.runtime.lstrip("\n")) for c in cases),
options=["--generate-allowlist"],
)
actual_errors = set(output.splitlines())
assert actual_errors == expected_errors, output
return test
class StubtestUnit(unittest.TestCase):
@collect_cases
def test_basic_good(self) -> Iterator[Case]:
yield Case(
stub="def f(number: int, text: str) -> None: ...",
runtime="def f(number, text): pass",
error=None,
)
yield Case(
stub="""
class X:
def f(self, number: int, text: str) -> None: ...
""",
runtime="""
class X:
def f(self, number, text): pass
""",
error=None,
)
@collect_cases
def test_types(self) -> Iterator[Case]:
yield Case(
stub="def mistyped_class() -> None: ...",
runtime="class mistyped_class: pass",
error="mistyped_class",
)
yield Case(
stub="class mistyped_fn: ...", runtime="def mistyped_fn(): pass", error="mistyped_fn"
)
yield Case(
stub="""
class X:
def mistyped_var(self) -> int: ...
""",
runtime="""
class X:
mistyped_var = 1
""",
error="X.mistyped_var",
)
@collect_cases
def test_coroutines(self) -> Iterator[Case]:
yield Case(stub="def bar() -> int: ...", runtime="async def bar(): return 5", error="bar")
# Don't error for this one -- we get false positives otherwise
yield Case(stub="async def foo() -> int: ...", runtime="def foo(): return 5", error=None)
yield Case(stub="def baz() -> int: ...", runtime="def baz(): return 5", error=None)
yield Case(
stub="async def bingo() -> int: ...", runtime="async def bingo(): return 5", error=None
)
@collect_cases
def test_arg_name(self) -> Iterator[Case]:
yield Case(
stub="def bad(number: int, text: str) -> None: ...",
runtime="def bad(num, text) -> None: pass",
error="bad",
)
if sys.version_info >= (3, 8):
yield Case(
stub="def good_posonly(__number: int, text: str) -> None: ...",
runtime="def good_posonly(num, /, text): pass",
error=None,
)
yield Case(
stub="def bad_posonly(__number: int, text: str) -> None: ...",
runtime="def bad_posonly(flag, /, text): pass",
error="bad_posonly",
)
yield Case(
stub="""
class BadMethod:
def f(self, number: int, text: str) -> None: ...
""",
runtime="""
class BadMethod:
def f(self, n, text): pass
""",
error="BadMethod.f",
)
yield Case(
stub="""
class GoodDunder:
def __exit__(self, t, v, tb) -> None: ...
""",
runtime="""
class GoodDunder:
def __exit__(self, exc_type, exc_val, exc_tb): pass
""",
error=None,
)
@collect_cases
def test_arg_kind(self) -> Iterator[Case]:
yield Case(
stub="def runtime_kwonly(number: int, text: str) -> None: ...",
runtime="def runtime_kwonly(number, *, text): pass",
error="runtime_kwonly",
)
yield Case(
stub="def stub_kwonly(number: int, *, text: str) -> None: ...",
runtime="def stub_kwonly(number, text): pass",
error="stub_kwonly",
)
yield Case(
stub="def stub_posonly(__number: int, text: str) -> None: ...",
runtime="def stub_posonly(number, text): pass",
error="stub_posonly",
)
if sys.version_info >= (3, 8):
yield Case(
stub="def good_posonly(__number: int, text: str) -> None: ...",
runtime="def good_posonly(number, /, text): pass",
error=None,
)
yield Case(
stub="def runtime_posonly(number: int, text: str) -> None: ...",
runtime="def runtime_posonly(number, /, text): pass",
error="runtime_posonly",
)
yield Case(
stub="def stub_posonly_570(number: int, /, text: str) -> None: ...",
runtime="def stub_posonly_570(number, text): pass",
error="stub_posonly_570",
)
@collect_cases
def test_default_value(self) -> Iterator[Case]:
yield Case(
stub="def f1(text: str = ...) -> None: ...",
runtime="def f1(text = 'asdf'): pass",
error=None,
)
yield Case(
stub="def f2(text: str = ...) -> None: ...", runtime="def f2(text): pass", error="f2"
)
yield Case(
stub="def f3(text: str) -> None: ...",
runtime="def f3(text = 'asdf'): pass",
error="f3",
)
yield Case(
stub="def f4(text: str = ...) -> None: ...",
runtime="def f4(text = None): pass",
error="f4",
)
yield Case(
stub="def f5(data: bytes = ...) -> None: ...",
runtime="def f5(data = 'asdf'): pass",
error="f5",
)
yield Case(
stub="""
from typing import TypeVar
_T = TypeVar("_T", bound=str)
def f6(text: _T = ...) -> None: ...
""",
runtime="def f6(text = None): pass",
error="f6",
)
@collect_cases
def test_static_class_method(self) -> Iterator[Case]:
yield Case(
stub="""
class Good:
@classmethod
def f(cls, number: int, text: str) -> None: ...
""",
runtime="""
class Good:
@classmethod
def f(cls, number, text): pass
""",
error=None,
)
yield Case(
stub="""
class Bad1:
def f(cls, number: int, text: str) -> None: ...
""",
runtime="""
class Bad1:
@classmethod
def f(cls, number, text): pass
""",
error="Bad1.f",
)
yield Case(
stub="""
class Bad2:
@classmethod
def f(cls, number: int, text: str) -> None: ...
""",
runtime="""
class Bad2:
@staticmethod
def f(self, number, text): pass
""",
error="Bad2.f",
)
yield Case(
stub="""
class Bad3:
@staticmethod
def f(cls, number: int, text: str) -> None: ...
""",
runtime="""
class Bad3:
@classmethod
def f(self, number, text): pass
""",
error="Bad3.f",
)
yield Case(
stub="""
class GoodNew:
def __new__(cls, *args, **kwargs): ...
""",
runtime="""
class GoodNew:
def __new__(cls, *args, **kwargs): pass
""",
error=None,
)
@collect_cases
def test_arg_mismatch(self) -> Iterator[Case]:
yield Case(
stub="def f1(a, *, b, c) -> None: ...", runtime="def f1(a, *, b, c): pass", error=None
)
yield Case(
stub="def f2(a, *, b) -> None: ...", runtime="def f2(a, *, b, c): pass", error="f2"
)
yield Case(
stub="def f3(a, *, b, c) -> None: ...", runtime="def f3(a, *, b): pass", error="f3"
)
yield Case(
stub="def f4(a, *, b, c) -> None: ...", runtime="def f4(a, b, *, c): pass", error="f4"
)
yield Case(
stub="def f5(a, b, *, c) -> None: ...", runtime="def f5(a, *, b, c): pass", error="f5"
)
@collect_cases
def test_varargs_varkwargs(self) -> Iterator[Case]:
yield Case(
stub="def f1(*args, **kwargs) -> None: ...",
runtime="def f1(*args, **kwargs): pass",
error=None,
)
yield Case(
stub="def f2(*args, **kwargs) -> None: ...",
runtime="def f2(**kwargs): pass",
error="f2",
)
yield Case(
stub="def g1(a, b, c, d) -> None: ...", runtime="def g1(a, *args): pass", error=None
)
yield Case(
stub="def g2(a, b, c, d, *args) -> None: ...", runtime="def g2(a): pass", error="g2"
)
yield Case(
stub="def g3(a, b, c, d, *args) -> None: ...",
runtime="def g3(a, *args): pass",
error=None,
)
yield Case(
stub="def h1(a) -> None: ...", runtime="def h1(a, b, c, d, *args): pass", error="h1"
)
yield Case(
stub="def h2(a, *args) -> None: ...", runtime="def h2(a, b, c, d): pass", error="h2"
)
yield Case(
stub="def h3(a, *args) -> None: ...",
runtime="def h3(a, b, c, d, *args): pass",
error="h3",
)
yield Case(
stub="def j1(a: int, *args) -> None: ...", runtime="def j1(a): pass", error="j1"
)
yield Case(
stub="def j2(a: int) -> None: ...", runtime="def j2(a, *args): pass", error="j2"
)
yield Case(
stub="def j3(a, b, c) -> None: ...", runtime="def j3(a, *args, c): pass", error="j3"
)
yield Case(stub="def k1(a, **kwargs) -> None: ...", runtime="def k1(a): pass", error="k1")
yield Case(
# In theory an error, but led to worse results in practice
stub="def k2(a) -> None: ...",
runtime="def k2(a, **kwargs): pass",
error=None,
)
yield Case(
stub="def k3(a, b) -> None: ...", runtime="def k3(a, **kwargs): pass", error="k3"
)
yield Case(
stub="def k4(a, *, b) -> None: ...", runtime="def k4(a, **kwargs): pass", error=None
)
yield Case(
stub="def k5(a, *, b) -> None: ...",
runtime="def k5(a, *, b, c, **kwargs): pass",
error="k5",
)
yield Case(
stub="def k6(a, *, b, **kwargs) -> None: ...",
runtime="def k6(a, *, b, c, **kwargs): pass",
error="k6",
)
@collect_cases
def test_overload(self) -> Iterator[Case]:
yield Case(
stub="""
from typing import overload
@overload
def f1(a: int, *, c: int = ...) -> int: ...
@overload
def f1(a: int, b: int, c: int = ...) -> str: ...
""",
runtime="def f1(a, b = 0, c = 0): pass",
error=None,
)
yield Case(
stub="""
@overload
def f2(a: int, *, c: int = ...) -> int: ...
@overload
def f2(a: int, b: int, c: int = ...) -> str: ...
""",
runtime="def f2(a, b, c = 0): pass",
error="f2",
)
yield Case(
stub="""
@overload
def f3(a: int) -> int: ...
@overload
def f3(a: int, b: str) -> str: ...
""",
runtime="def f3(a, b = None): pass",
error="f3",
)
yield Case(
stub="""
@overload
def f4(a: int, *args, b: int, **kwargs) -> int: ...
@overload
def f4(a: str, *args, b: int, **kwargs) -> str: ...
""",
runtime="def f4(a, *args, b, **kwargs): pass",
error=None,
)
if sys.version_info >= (3, 8):
yield Case(
stub="""
@overload
def f5(__a: int) -> int: ...
@overload
def f5(__b: str) -> str: ...
""",
runtime="def f5(x, /): pass",
error=None,
)
@collect_cases
def test_property(self) -> Iterator[Case]:
yield Case(
stub="""
class Good:
@property
def read_only_attr(self) -> int: ...
""",
runtime="""
class Good:
@property
def read_only_attr(self): return 1
""",
error=None,
)
yield Case(
stub="""
class Bad:
@property
def f(self) -> int: ...
""",
runtime="""
class Bad:
def f(self) -> int: return 1
""",
error="Bad.f",
)
yield Case(
stub="""
class GoodReadOnly:
@property
def f(self) -> int: ...
""",
runtime="""
class GoodReadOnly:
f = 1
""",
error=None,
)
yield Case(
stub="""
class BadReadOnly:
@property
def f(self) -> str: ...
""",
runtime="""
class BadReadOnly:
f = 1
""",
error="BadReadOnly.f",
)
yield Case(
stub="""
class Y:
@property
def read_only_attr(self) -> int: ...
@read_only_attr.setter
def read_only_attr(self, val: int) -> None: ...
""",
runtime="""
class Y:
@property
def read_only_attr(self): return 5
""",
error="Y.read_only_attr",
)
yield Case(
stub="""
class Z:
@property
def read_write_attr(self) -> int: ...
@read_write_attr.setter
def read_write_attr(self, val: int) -> None: ...
""",
runtime="""
class Z:
@property
def read_write_attr(self): return self._val
@read_write_attr.setter
def read_write_attr(self, val): self._val = val
""",
error=None,
)
yield Case(
stub="""
class FineAndDandy:
@property
def attr(self) -> int: ...
""",
runtime="""
class _EvilDescriptor:
def __get__(self, instance, ownerclass=None):
if instance is None:
raise AttributeError('no')
return 42
def __set__(self, instance, value):
raise AttributeError('no')
class FineAndDandy:
attr = _EvilDescriptor()
""",
error=None,
)
@collect_cases
def test_var(self) -> Iterator[Case]:
yield Case(stub="x1: int", runtime="x1 = 5", error=None)
yield Case(stub="x2: str", runtime="x2 = 5", error="x2")
yield Case("from typing import Tuple", "", None) # dummy case
yield Case(
stub="""
x3: Tuple[int, int]
""",
runtime="x3 = (1, 3)",
error=None,
)
yield Case(
stub="""
x4: Tuple[int, int]
""",
runtime="x4 = (1, 3, 5)",
error="x4",
)
yield Case(stub="x5: int", runtime="def x5(a, b): pass", error="x5")
yield Case(
stub="def foo(a: int, b: int) -> None: ...\nx6 = foo",
runtime="def foo(a, b): pass\ndef x6(c, d): pass",
error="x6",
)
yield Case(
stub="""
class X:
f: int
""",
runtime="""
class X:
def __init__(self):
self.f = "asdf"
""",
error=None,
)
yield Case(
stub="""
class Y:
read_only_attr: int
""",
runtime="""
class Y:
@property
def read_only_attr(self): return 5
""",
error="Y.read_only_attr",
)
yield Case(
stub="""
class Z:
read_write_attr: int
""",
runtime="""
class Z:
@property
def read_write_attr(self): return self._val
@read_write_attr.setter
def read_write_attr(self, val): self._val = val
""",
error=None,
)
@collect_cases
def test_type_alias(self) -> Iterator[Case]:
yield Case(
stub="""
class X:
def f(self) -> None: ...
Y = X
""",
runtime="""
class X:
def f(self) -> None: ...
class Y: ...
""",
error="Y.f",
)
yield Case(
stub="""
from typing import Tuple
A = Tuple[int, str]
""",
runtime="A = (int, str)",
error="A",
)
# Error if an alias isn't present at runtime...
yield Case(stub="B = str", runtime="", error="B")
# ... but only if the alias isn't private
yield Case(stub="_C = int", runtime="", error=None)
yield Case(
stub="""
from typing import Tuple
D = tuple[str, str]
E = Tuple[int, int, int]
F = Tuple[str, int]
""",
runtime="""
from typing import List, Tuple
D = Tuple[str, str]
E = Tuple[int, int, int]
F = List[str]
""",
error="F",
)
yield Case(
stub="""
from typing import Union
G = str | int
H = Union[str, bool]
I = str | int
""",
runtime="""
from typing import Union
G = Union[str, int]
H = Union[str, bool]
I = str
""",
error="I",
)
yield Case(
stub="""
import typing
from collections.abc import Iterable
from typing import Dict
K = dict[str, str]
L = Dict[int, int]
KK = Iterable[str]
LL = typing.Iterable[str]
""",
runtime="""
from typing import Iterable, Dict
K = Dict[str, str]
L = Dict[int, int]
KK = Iterable[str]
LL = Iterable[str]
""",
error=None,
)
yield Case(
stub="""
from typing import Generic, TypeVar
_T = TypeVar("_T")
class _Spam(Generic[_T]):
def foo(self) -> None: ...
IntFood = _Spam[int]
""",
runtime="""
from typing import Generic, TypeVar
_T = TypeVar("_T")
class _Bacon(Generic[_T]):
def foo(self, arg): pass
IntFood = _Bacon[int]
""",
error="IntFood.foo",
)
yield Case(stub="StrList = list[str]", runtime="StrList = ['foo', 'bar']", error="StrList")
yield Case(
stub="""
import collections.abc
from typing import Callable
N = Callable[[str], bool]
O = collections.abc.Callable[[int], str]
P = Callable[[str], bool]
""",
runtime="""
from typing import Callable
N = Callable[[str], bool]
O = Callable[[int], str]
P = int
""",
error="P",
)
yield Case(
stub="""
class Foo:
class Bar: ...
BarAlias = Foo.Bar
""",
runtime="""
class Foo:
class Bar: pass
BarAlias = Foo.Bar
""",
error=None,
)
yield Case(
stub="""
from io import StringIO
StringIOAlias = StringIO
""",
runtime="""
from _io import StringIO
StringIOAlias = StringIO
""",
error=None,
)
yield Case(
stub="""
from typing import Match
M = Match[str]
""",
runtime="""
from typing import Match
M = Match[str]
""",
error=None,
)
yield Case(
stub="""
class Baz:
def fizz(self) -> None: ...
BazAlias = Baz
""",
runtime="""
class Baz:
def fizz(self): pass
BazAlias = Baz
Baz.__name__ = Baz.__qualname__ = Baz.__module__ = "New"
""",
error=None,
)
yield Case(
stub="""
class FooBar:
__module__: None # type: ignore
def fizz(self) -> None: ...
FooBarAlias = FooBar
""",
runtime="""
class FooBar:
def fizz(self): pass
FooBarAlias = FooBar
FooBar.__module__ = None
""",
error=None,
)
if sys.version_info >= (3, 10):
yield Case(
stub="""
import collections.abc
import re
from typing import Callable, Dict, Match, Iterable, Tuple, Union
Q = Dict[str, str]
R = dict[int, int]
S = Tuple[int, int]
T = tuple[str, str]
U = int | str
V = Union[int, str]
W = Callable[[str], bool]
Z = collections.abc.Callable[[str], bool]
QQ = Iterable[str]
RR = collections.abc.Iterable[str]
MM = Match[str]
MMM = re.Match[str]
""",
runtime="""
from collections.abc import Callable, Iterable
from re import Match
Q = dict[str, str]
R = dict[int, int]
S = tuple[int, int]
T = tuple[str, str]
U = int | str
V = int | str
W = Callable[[str], bool]
Z = Callable[[str], bool]
QQ = Iterable[str]
RR = Iterable[str]
MM = Match[str]
MMM = Match[str]
""",
error=None,
)
@collect_cases
def test_enum(self) -> Iterator[Case]:
yield Case(
stub="""
import enum
class X(enum.Enum):
a: int
b: str
c: str
""",
runtime="""
import enum
class X(enum.Enum):
a = 1
b = "asdf"
c = 2
""",
error="X.c",
)
@collect_cases
def test_decorator(self) -> Iterator[Case]:
yield Case(
stub="""
from typing import Any, Callable
def decorator(f: Callable[[], int]) -> Callable[..., Any]: ...
@decorator
def f() -> Any: ...
""",
runtime="""
def decorator(f): return f
@decorator
def f(): return 3
""",
error=None,
)
@collect_cases
def test_all_at_runtime_not_stub(self) -> Iterator[Case]:
yield Case(
stub="Z: int",
runtime="""
__all__ = []
Z = 5""",
error=None,
)
@collect_cases
def test_all_in_stub_not_at_runtime(self) -> Iterator[Case]:
yield Case(stub="__all__ = ()", runtime="", error="__all__")
@collect_cases
def test_all_in_stub_different_to_all_at_runtime(self) -> Iterator[Case]:
# We *should* emit an error with the module name itself,
# if the stub *does* define __all__,
# but the stub's __all__ is inconsistent with the runtime's __all__
yield Case(
stub="""
__all__ = ['foo']
foo: str
""",
runtime="""
__all__ = []
foo = 'foo'
""",
error="",
)
@collect_cases
def test_missing(self) -> Iterator[Case]:
yield Case(stub="x = 5", runtime="", error="x")
yield Case(stub="def f(): ...", runtime="", error="f")
yield Case(stub="class X: ...", runtime="", error="X")
yield Case(
stub="""
from typing import overload