-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
teststubgen.py
1412 lines (1201 loc) · 50.9 KB
/
teststubgen.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 io
import os.path
import re
import shutil
import sys
import tempfile
import unittest
from types import ModuleType
from typing import Any
import pytest
from mypy.errors import CompileError
from mypy.moduleinspect import InspectError, ModuleInspect
from mypy.stubdoc import (
ArgSig,
FunctionSig,
build_signature,
find_unique_signatures,
infer_arg_sig_from_anon_docstring,
infer_prop_type_from_docstring,
infer_sig_from_docstring,
is_valid_type,
parse_all_signatures,
parse_signature,
)
from mypy.stubgen import (
Options,
collect_build_targets,
generate_stubs,
is_blacklisted_path,
is_non_library_module,
mypy_options,
parse_options,
)
from mypy.stubgenc import InspectionStubGenerator, infer_c_method_args
from mypy.stubutil import (
ClassInfo,
common_dir_prefix,
infer_method_ret_type,
remove_misplaced_type_comments,
walk_packages,
)
from mypy.test.data import DataDrivenTestCase, DataSuite
from mypy.test.helpers import assert_equal, assert_string_arrays_equal, local_sys_path_set
class StubgenCmdLineSuite(unittest.TestCase):
"""Test cases for processing command-line options and finding files."""
@unittest.skipIf(sys.platform == "win32", "clean up fails on Windows")
def test_files_found(self) -> None:
current = os.getcwd()
with tempfile.TemporaryDirectory() as tmp:
try:
os.chdir(tmp)
os.mkdir("subdir")
self.make_file("subdir", "a.py")
self.make_file("subdir", "b.py")
os.mkdir(os.path.join("subdir", "pack"))
self.make_file("subdir", "pack", "__init__.py")
opts = parse_options(["subdir"])
py_mods, pyi_mods, c_mods = collect_build_targets(opts, mypy_options(opts))
assert_equal(pyi_mods, [])
assert_equal(c_mods, [])
files = {mod.path for mod in py_mods}
assert_equal(
files,
{
os.path.join("subdir", "pack", "__init__.py"),
os.path.join("subdir", "a.py"),
os.path.join("subdir", "b.py"),
},
)
finally:
os.chdir(current)
@unittest.skipIf(sys.platform == "win32", "clean up fails on Windows")
def test_packages_found(self) -> None:
current = os.getcwd()
with tempfile.TemporaryDirectory() as tmp:
try:
os.chdir(tmp)
os.mkdir("pack")
self.make_file("pack", "__init__.py", content="from . import a, b")
self.make_file("pack", "a.py")
self.make_file("pack", "b.py")
opts = parse_options(["-p", "pack"])
py_mods, pyi_mods, c_mods = collect_build_targets(opts, mypy_options(opts))
assert_equal(pyi_mods, [])
assert_equal(c_mods, [])
files = {os.path.relpath(mod.path or "FAIL") for mod in py_mods}
assert_equal(
files,
{
os.path.join("pack", "__init__.py"),
os.path.join("pack", "a.py"),
os.path.join("pack", "b.py"),
},
)
finally:
os.chdir(current)
@unittest.skipIf(sys.platform == "win32", "clean up fails on Windows")
def test_module_not_found(self) -> None:
current = os.getcwd()
captured_output = io.StringIO()
sys.stdout = captured_output
with tempfile.TemporaryDirectory() as tmp:
try:
os.chdir(tmp)
self.make_file(tmp, "mymodule.py", content="import a")
opts = parse_options(["-m", "mymodule"])
collect_build_targets(opts, mypy_options(opts))
assert captured_output.getvalue() == ""
finally:
sys.stdout = sys.__stdout__
os.chdir(current)
def make_file(self, *path: str, content: str = "") -> None:
file = os.path.join(*path)
with open(file, "w") as f:
f.write(content)
def run(self, result: Any | None = None) -> Any | None:
with local_sys_path_set():
return super().run(result)
class StubgenCliParseSuite(unittest.TestCase):
def test_walk_packages(self) -> None:
with ModuleInspect() as m:
assert_equal(set(walk_packages(m, ["mypy.errors"])), {"mypy.errors"})
assert_equal(
set(walk_packages(m, ["mypy.errors", "mypy.stubgen"])),
{"mypy.errors", "mypy.stubgen"},
)
all_mypy_packages = set(walk_packages(m, ["mypy"]))
self.assertTrue(
all_mypy_packages.issuperset(
{"mypy", "mypy.errors", "mypy.stubgen", "mypy.test", "mypy.test.helpers"}
)
)
class StubgenUtilSuite(unittest.TestCase):
"""Unit tests for stubgen utility functions."""
def test_parse_signature(self) -> None:
self.assert_parse_signature("func()", ("func", [], []))
def test_parse_signature_with_args(self) -> None:
self.assert_parse_signature("func(arg)", ("func", ["arg"], []))
self.assert_parse_signature("do(arg, arg2)", ("do", ["arg", "arg2"], []))
def test_parse_signature_with_optional_args(self) -> None:
self.assert_parse_signature("func([arg])", ("func", [], ["arg"]))
self.assert_parse_signature("func(arg[, arg2])", ("func", ["arg"], ["arg2"]))
self.assert_parse_signature("func([arg[, arg2]])", ("func", [], ["arg", "arg2"]))
def test_parse_signature_with_default_arg(self) -> None:
self.assert_parse_signature("func(arg=None)", ("func", [], ["arg"]))
self.assert_parse_signature("func(arg, arg2=None)", ("func", ["arg"], ["arg2"]))
self.assert_parse_signature('func(arg=1, arg2="")', ("func", [], ["arg", "arg2"]))
def test_parse_signature_with_qualified_function(self) -> None:
self.assert_parse_signature("ClassName.func(arg)", ("func", ["arg"], []))
def test_parse_signature_with_kw_only_arg(self) -> None:
self.assert_parse_signature(
"ClassName.func(arg, *, arg2=1)", ("func", ["arg", "*"], ["arg2"])
)
def test_parse_signature_with_star_arg(self) -> None:
self.assert_parse_signature("ClassName.func(arg, *args)", ("func", ["arg", "*args"], []))
def test_parse_signature_with_star_star_arg(self) -> None:
self.assert_parse_signature("ClassName.func(arg, **args)", ("func", ["arg", "**args"], []))
def assert_parse_signature(self, sig: str, result: tuple[str, list[str], list[str]]) -> None:
assert_equal(parse_signature(sig), result)
def test_build_signature(self) -> None:
assert_equal(build_signature([], []), "()")
assert_equal(build_signature(["arg"], []), "(arg)")
assert_equal(build_signature(["arg", "arg2"], []), "(arg, arg2)")
assert_equal(build_signature(["arg"], ["arg2"]), "(arg, arg2=...)")
assert_equal(build_signature(["arg"], ["arg2", "**x"]), "(arg, arg2=..., **x)")
def test_parse_all_signatures(self) -> None:
assert_equal(
parse_all_signatures(
[
"random text",
".. function:: fn(arg",
".. function:: fn()",
" .. method:: fn2(arg)",
]
),
([("fn", "()"), ("fn2", "(arg)")], []),
)
def test_find_unique_signatures(self) -> None:
assert_equal(
find_unique_signatures(
[
("func", "()"),
("func", "()"),
("func2", "()"),
("func2", "(arg)"),
("func3", "(arg, arg2)"),
]
),
[("func", "()"), ("func3", "(arg, arg2)")],
)
def test_infer_sig_from_docstring(self) -> None:
assert_equal(
infer_sig_from_docstring("\nfunc(x) - y", "func"),
[FunctionSig(name="func", args=[ArgSig(name="x")], ret_type="Any")],
)
assert_equal(
infer_sig_from_docstring("\nfunc(x)", "func"),
[FunctionSig(name="func", args=[ArgSig(name="x")], ret_type="Any")],
)
assert_equal(
infer_sig_from_docstring("\nfunc(x, Y_a=None)", "func"),
[
FunctionSig(
name="func",
args=[ArgSig(name="x"), ArgSig(name="Y_a", default=True)],
ret_type="Any",
)
],
)
assert_equal(
infer_sig_from_docstring("\nfunc(x, Y_a=3)", "func"),
[
FunctionSig(
name="func",
args=[ArgSig(name="x"), ArgSig(name="Y_a", default=True)],
ret_type="Any",
)
],
)
assert_equal(
infer_sig_from_docstring("\nfunc(x, Y_a=[1, 2, 3])", "func"),
[
FunctionSig(
name="func",
args=[ArgSig(name="x"), ArgSig(name="Y_a", default=True)],
ret_type="Any",
)
],
)
assert_equal(infer_sig_from_docstring("\nafunc(x) - y", "func"), [])
assert_equal(infer_sig_from_docstring("\nfunc(x, y", "func"), [])
assert_equal(
infer_sig_from_docstring("\nfunc(x=z(y))", "func"),
[FunctionSig(name="func", args=[ArgSig(name="x", default=True)], ret_type="Any")],
)
assert_equal(infer_sig_from_docstring("\nfunc x", "func"), [])
# Try to infer signature from type annotation.
assert_equal(
infer_sig_from_docstring("\nfunc(x: int)", "func"),
[FunctionSig(name="func", args=[ArgSig(name="x", type="int")], ret_type="Any")],
)
assert_equal(
infer_sig_from_docstring("\nfunc(x: int=3)", "func"),
[
FunctionSig(
name="func", args=[ArgSig(name="x", type="int", default=True)], ret_type="Any"
)
],
)
assert_equal(
infer_sig_from_docstring("\nfunc(x=3)", "func"),
[
FunctionSig(
name="func", args=[ArgSig(name="x", type=None, default=True)], ret_type="Any"
)
],
)
assert_equal(
infer_sig_from_docstring("\nfunc() -> int", "func"),
[FunctionSig(name="func", args=[], ret_type="int")],
)
assert_equal(
infer_sig_from_docstring("\nfunc(x: int=3) -> int", "func"),
[
FunctionSig(
name="func", args=[ArgSig(name="x", type="int", default=True)], ret_type="int"
)
],
)
assert_equal(
infer_sig_from_docstring("\nfunc(x: int=3) -> int \n", "func"),
[
FunctionSig(
name="func", args=[ArgSig(name="x", type="int", default=True)], ret_type="int"
)
],
)
assert_equal(
infer_sig_from_docstring("\nfunc(x: Tuple[int, str]) -> str", "func"),
[
FunctionSig(
name="func", args=[ArgSig(name="x", type="Tuple[int,str]")], ret_type="str"
)
],
)
assert_equal(
infer_sig_from_docstring(
"\nfunc(x: Tuple[int, Tuple[str, int], str], y: int) -> str", "func"
),
[
FunctionSig(
name="func",
args=[
ArgSig(name="x", type="Tuple[int,Tuple[str,int],str]"),
ArgSig(name="y", type="int"),
],
ret_type="str",
)
],
)
assert_equal(
infer_sig_from_docstring("\nfunc(x: foo.bar)", "func"),
[FunctionSig(name="func", args=[ArgSig(name="x", type="foo.bar")], ret_type="Any")],
)
assert_equal(
infer_sig_from_docstring("\nfunc(x: list=[1,2,[3,4]])", "func"),
[
FunctionSig(
name="func", args=[ArgSig(name="x", type="list", default=True)], ret_type="Any"
)
],
)
assert_equal(
infer_sig_from_docstring('\nfunc(x: str="nasty[")', "func"),
[
FunctionSig(
name="func", args=[ArgSig(name="x", type="str", default=True)], ret_type="Any"
)
],
)
assert_equal(infer_sig_from_docstring("\nfunc[(x: foo.bar, invalid]", "func"), [])
assert_equal(
infer_sig_from_docstring("\nfunc(x: invalid::type<with_template>)", "func"),
[FunctionSig(name="func", args=[ArgSig(name="x", type=None)], ret_type="Any")],
)
assert_equal(
infer_sig_from_docstring('\nfunc(x: str="")', "func"),
[
FunctionSig(
name="func", args=[ArgSig(name="x", type="str", default=True)], ret_type="Any"
)
],
)
def test_infer_sig_from_docstring_duplicate_args(self) -> None:
assert_equal(
infer_sig_from_docstring("\nfunc(x, x) -> str\nfunc(x, y) -> int", "func"),
[FunctionSig(name="func", args=[ArgSig(name="x"), ArgSig(name="y")], ret_type="int")],
)
def test_infer_sig_from_docstring_bad_indentation(self) -> None:
assert_equal(
infer_sig_from_docstring(
"""
x
x
x
""",
"func",
),
None,
)
def test_infer_arg_sig_from_anon_docstring(self) -> None:
assert_equal(
infer_arg_sig_from_anon_docstring("(*args, **kwargs)"),
[ArgSig(name="*args"), ArgSig(name="**kwargs")],
)
assert_equal(
infer_arg_sig_from_anon_docstring(
"(x: Tuple[int, Tuple[str, int], str]=(1, ('a', 2), 'y'), y: int=4)"
),
[
ArgSig(name="x", type="Tuple[int,Tuple[str,int],str]", default=True),
ArgSig(name="y", type="int", default=True),
],
)
def test_infer_prop_type_from_docstring(self) -> None:
assert_equal(infer_prop_type_from_docstring("str: A string."), "str")
assert_equal(infer_prop_type_from_docstring("Optional[int]: An int."), "Optional[int]")
assert_equal(
infer_prop_type_from_docstring("Tuple[int, int]: A tuple."), "Tuple[int, int]"
)
assert_equal(infer_prop_type_from_docstring("\nstr: A string."), None)
def test_infer_sig_from_docstring_square_brackets(self) -> None:
assert (
infer_sig_from_docstring("fetch_row([maxrows, how]) -- Fetches stuff", "fetch_row")
== []
)
def test_remove_misplaced_type_comments_1(self) -> None:
good = """
\u1234
def f(x): # type: (int) -> int
def g(x):
# type: (int) -> int
def h():
# type: () int
x = 1 # type: int
"""
assert_equal(remove_misplaced_type_comments(good), good)
def test_remove_misplaced_type_comments_2(self) -> None:
bad = """
def f(x):
# type: Callable[[int], int]
pass
# type: "foo"
# type: 'bar'
x = 1
# type: int
"""
bad_fixed = """
def f(x):
pass
x = 1
"""
assert_equal(remove_misplaced_type_comments(bad), bad_fixed)
def test_remove_misplaced_type_comments_3(self) -> None:
bad = '''
def f(x):
"""docstring"""
# type: (int) -> int
pass
def g(x):
"""docstring
"""
# type: (int) -> int
pass
'''
bad_fixed = '''
def f(x):
"""docstring"""
pass
def g(x):
"""docstring
"""
pass
'''
assert_equal(remove_misplaced_type_comments(bad), bad_fixed)
def test_remove_misplaced_type_comments_4(self) -> None:
bad = """
def f(x):
'''docstring'''
# type: (int) -> int
pass
def g(x):
'''docstring
'''
# type: (int) -> int
pass
"""
bad_fixed = """
def f(x):
'''docstring'''
pass
def g(x):
'''docstring
'''
pass
"""
assert_equal(remove_misplaced_type_comments(bad), bad_fixed)
def test_remove_misplaced_type_comments_5(self) -> None:
bad = """
def f(x):
# type: (int, List[Any],
# float, bool) -> int
pass
def g(x):
# type: (int, List[Any])
pass
"""
bad_fixed = """
def f(x):
# float, bool) -> int
pass
def g(x):
pass
"""
assert_equal(remove_misplaced_type_comments(bad), bad_fixed)
def test_remove_misplaced_type_comments_bytes(self) -> None:
original = b"""
\xbf
def f(x): # type: (int) -> int
def g(x):
# type: (int) -> int
pass
def h():
# type: int
pass
x = 1 # type: int
"""
dest = b"""
\xbf
def f(x): # type: (int) -> int
def g(x):
# type: (int) -> int
pass
def h():
pass
x = 1 # type: int
"""
assert_equal(remove_misplaced_type_comments(original), dest)
@unittest.skipIf(sys.platform == "win32", "Tests building the paths common ancestor on *nix")
def test_common_dir_prefix_unix(self) -> None:
assert common_dir_prefix([]) == "."
assert common_dir_prefix(["x.pyi"]) == "."
assert common_dir_prefix(["./x.pyi"]) == "."
assert common_dir_prefix(["foo/bar/x.pyi"]) == "foo/bar"
assert common_dir_prefix(["foo/bar/x.pyi", "foo/bar/y.pyi"]) == "foo/bar"
assert common_dir_prefix(["foo/bar/x.pyi", "foo/y.pyi"]) == "foo"
assert common_dir_prefix(["foo/x.pyi", "foo/bar/y.pyi"]) == "foo"
assert common_dir_prefix(["foo/bar/zar/x.pyi", "foo/y.pyi"]) == "foo"
assert common_dir_prefix(["foo/x.pyi", "foo/bar/zar/y.pyi"]) == "foo"
assert common_dir_prefix(["foo/bar/zar/x.pyi", "foo/bar/y.pyi"]) == "foo/bar"
assert common_dir_prefix(["foo/bar/x.pyi", "foo/bar/zar/y.pyi"]) == "foo/bar"
assert common_dir_prefix([r"foo/bar\x.pyi"]) == "foo"
assert common_dir_prefix([r"foo\bar/x.pyi"]) == r"foo\bar"
@unittest.skipIf(
sys.platform != "win32", "Tests building the paths common ancestor on Windows"
)
def test_common_dir_prefix_win(self) -> None:
assert common_dir_prefix(["x.pyi"]) == "."
assert common_dir_prefix([r".\x.pyi"]) == "."
assert common_dir_prefix([r"foo\bar\x.pyi"]) == r"foo\bar"
assert common_dir_prefix([r"foo\bar\x.pyi", r"foo\bar\y.pyi"]) == r"foo\bar"
assert common_dir_prefix([r"foo\bar\x.pyi", r"foo\y.pyi"]) == "foo"
assert common_dir_prefix([r"foo\x.pyi", r"foo\bar\y.pyi"]) == "foo"
assert common_dir_prefix([r"foo\bar\zar\x.pyi", r"foo\y.pyi"]) == "foo"
assert common_dir_prefix([r"foo\x.pyi", r"foo\bar\zar\y.pyi"]) == "foo"
assert common_dir_prefix([r"foo\bar\zar\x.pyi", r"foo\bar\y.pyi"]) == r"foo\bar"
assert common_dir_prefix([r"foo\bar\x.pyi", r"foo\bar\zar\y.pyi"]) == r"foo\bar"
assert common_dir_prefix([r"foo/bar\x.pyi"]) == r"foo\bar"
assert common_dir_prefix([r"foo\bar/x.pyi"]) == r"foo\bar"
assert common_dir_prefix([r"foo/bar/x.pyi"]) == r"foo\bar"
class StubgenHelpersSuite(unittest.TestCase):
def test_is_blacklisted_path(self) -> None:
assert not is_blacklisted_path("foo/bar.py")
assert not is_blacklisted_path("foo.py")
assert not is_blacklisted_path("foo/xvendor/bar.py")
assert not is_blacklisted_path("foo/vendorx/bar.py")
assert is_blacklisted_path("foo/vendor/bar.py")
assert is_blacklisted_path("foo/vendored/bar.py")
assert is_blacklisted_path("foo/vendored/bar/thing.py")
assert is_blacklisted_path("foo/six.py")
def test_is_non_library_module(self) -> None:
assert not is_non_library_module("foo")
assert not is_non_library_module("foo.bar")
# The following could be test modules, but we are very conservative and
# don't treat them as such since they could plausibly be real modules.
assert not is_non_library_module("foo.bartest")
assert not is_non_library_module("foo.bartests")
assert not is_non_library_module("foo.testbar")
assert is_non_library_module("foo.test")
assert is_non_library_module("foo.test.foo")
assert is_non_library_module("foo.tests")
assert is_non_library_module("foo.tests.foo")
assert is_non_library_module("foo.testing.foo")
assert is_non_library_module("foo.SelfTest.foo")
assert is_non_library_module("foo.test_bar")
assert is_non_library_module("foo.bar_tests")
assert is_non_library_module("foo.testing")
assert is_non_library_module("foo.conftest")
assert is_non_library_module("foo.bar_test_util")
assert is_non_library_module("foo.bar_test_utils")
assert is_non_library_module("foo.bar_test_base")
assert is_non_library_module("foo.setup")
assert is_non_library_module("foo.__main__")
class StubgenPythonSuite(DataSuite):
"""Data-driven end-to-end test cases that generate stub files.
You can use these magic test case name suffixes:
*_semanal
Run semantic analysis (slow as this uses real stubs -- only use
when necessary)
*_import
Import module and perform runtime introspection (in the current
process!)
You can use these magic comments:
# flags: --some-stubgen-option ...
Specify custom stubgen options
# modules: module1 module2 ...
Specify which modules to output (by default only 'main')
"""
required_out_section = True
base_path = "."
files = ["stubgen.test"]
@unittest.skipIf(sys.platform == "win32", "clean up fails on Windows")
def run_case(self, testcase: DataDrivenTestCase) -> None:
with local_sys_path_set():
self.run_case_inner(testcase)
def run_case_inner(self, testcase: DataDrivenTestCase) -> None:
extra = [] # Extra command-line args
mods = [] # Module names to process
source = "\n".join(testcase.input)
for file, content in testcase.files + [("./main.py", source)]:
# Strip ./ prefix and .py suffix.
mod = file[2:-3].replace("/", ".")
if mod.endswith(".__init__"):
mod, _, _ = mod.rpartition(".")
mods.append(mod)
if "-p " not in source:
extra.extend(["-m", mod])
with open(file, "w") as f:
f.write(content)
options = self.parse_flags(source, extra)
if sys.version_info < options.pyversion:
pytest.skip()
modules = self.parse_modules(source)
out_dir = "out"
try:
try:
if testcase.name.endswith("_inspect"):
options.inspect = True
else:
if not testcase.name.endswith("_import"):
options.no_import = True
if not testcase.name.endswith("_semanal"):
options.parse_only = True
generate_stubs(options)
a: list[str] = []
for module in modules:
fnam = module_to_path(out_dir, module)
self.add_file(fnam, a, header=len(modules) > 1)
except CompileError as e:
a = e.messages
assert_string_arrays_equal(
testcase.output, a, f"Invalid output ({testcase.file}, line {testcase.line})"
)
finally:
for mod in mods:
if mod in sys.modules:
del sys.modules[mod]
shutil.rmtree(out_dir)
def parse_flags(self, program_text: str, extra: list[str]) -> Options:
flags = re.search("# flags: (.*)$", program_text, flags=re.MULTILINE)
pyversion = None
if flags:
flag_list = flags.group(1).split()
for i, flag in enumerate(flag_list):
if flag.startswith("--python-version="):
pyversion = flag.split("=", 1)[1]
del flag_list[i]
break
else:
flag_list = []
options = parse_options(flag_list + extra)
if pyversion:
# A hack to allow testing old python versions with new language constructs
# This should be rarely used in general as stubgen output should not be version-specific
major, minor = pyversion.split(".", 1)
options.pyversion = (int(major), int(minor))
if "--verbose" not in flag_list:
options.quiet = True
else:
options.verbose = True
return options
def parse_modules(self, program_text: str) -> list[str]:
modules = re.search("# modules: (.*)$", program_text, flags=re.MULTILINE)
if modules:
return modules.group(1).split()
else:
return ["main"]
def add_file(self, path: str, result: list[str], header: bool) -> None:
if not os.path.exists(path):
result.append("<%s was not generated>" % path.replace("\\", "/"))
return
if header:
result.append(f"# {path[4:]}")
with open(path, encoding="utf8") as file:
result.extend(file.read().splitlines())
self_arg = ArgSig(name="self")
class TestBaseClass:
pass
class TestClass(TestBaseClass):
pass
class StubgencSuite(unittest.TestCase):
"""Unit tests for stub generation from C modules using introspection.
Note that these don't cover a lot!
"""
def test_infer_hash_sig(self) -> None:
assert_equal(infer_c_method_args("__hash__"), [self_arg])
assert_equal(infer_method_ret_type("__hash__"), "int")
def test_infer_getitem_sig(self) -> None:
assert_equal(infer_c_method_args("__getitem__"), [self_arg, ArgSig(name="index")])
def test_infer_setitem_sig(self) -> None:
assert_equal(
infer_c_method_args("__setitem__"),
[self_arg, ArgSig(name="index"), ArgSig(name="object")],
)
assert_equal(infer_method_ret_type("__setitem__"), "None")
def test_infer_eq_op_sig(self) -> None:
for op in ("eq", "ne", "lt", "le", "gt", "ge"):
assert_equal(
infer_c_method_args(f"__{op}__"), [self_arg, ArgSig(name="other", type="object")]
)
def test_infer_binary_op_sig(self) -> None:
for op in ("add", "radd", "sub", "rsub", "mul", "rmul"):
assert_equal(infer_c_method_args(f"__{op}__"), [self_arg, ArgSig(name="other")])
def test_infer_equality_op_sig(self) -> None:
for op in ("eq", "ne", "lt", "le", "gt", "ge", "contains"):
assert_equal(infer_method_ret_type(f"__{op}__"), "bool")
def test_infer_unary_op_sig(self) -> None:
for op in ("neg", "pos"):
assert_equal(infer_c_method_args(f"__{op}__"), [self_arg])
def test_infer_cast_sig(self) -> None:
for op in ("float", "bool", "bytes", "int"):
assert_equal(infer_method_ret_type(f"__{op}__"), op)
def test_generate_class_stub_no_crash_for_object(self) -> None:
output: list[str] = []
mod = ModuleType("module", "") # any module is fine
gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)
gen.generate_class_stub("alias", object, output)
assert_equal(gen.get_imports().splitlines(), [])
assert_equal(output[0], "class alias:")
def test_generate_class_stub_variable_type_annotation(self) -> None:
# This class mimics the stubgen unit test 'testClassVariable'
class TestClassVariableCls:
x = 1
output: list[str] = []
mod = ModuleType("module", "") # any module is fine
gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)
gen.generate_class_stub("C", TestClassVariableCls, output)
assert_equal(gen.get_imports().splitlines(), ["from typing import ClassVar"])
assert_equal(output, ["class C:", " x: ClassVar[int] = ..."])
def test_generate_c_type_inheritance(self) -> None:
class TestClass(KeyError):
pass
output: list[str] = []
mod = ModuleType("module, ")
gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)
gen.generate_class_stub("C", TestClass, output)
assert_equal(output, ["class C(KeyError): ..."])
assert_equal(gen.get_imports().splitlines(), [])
def test_generate_c_type_inheritance_same_module(self) -> None:
output: list[str] = []
mod = ModuleType(TestBaseClass.__module__, "")
gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)
gen.generate_class_stub("C", TestClass, output)
assert_equal(output, ["class C(TestBaseClass): ..."])
assert_equal(gen.get_imports().splitlines(), [])
def test_generate_c_type_inheritance_other_module(self) -> None:
import argparse
class TestClass(argparse.Action):
pass
output: list[str] = []
mod = ModuleType("module", "")
gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)
gen.generate_class_stub("C", TestClass, output)
assert_equal(output, ["class C(argparse.Action): ..."])
assert_equal(gen.get_imports().splitlines(), ["import argparse"])
def test_generate_c_type_inheritance_builtin_type(self) -> None:
class TestClass(type):
pass
output: list[str] = []
mod = ModuleType("module", "")
gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)
gen.generate_class_stub("C", TestClass, output)
assert_equal(output, ["class C(type): ..."])
assert_equal(gen.get_imports().splitlines(), [])
def test_generate_c_type_with_docstring(self) -> None:
class TestClass:
def test(self, arg0: str) -> None:
"""
test(self: TestClass, arg0: int)
"""
output: list[str] = []
mod = ModuleType(TestClass.__module__, "")
gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)
gen.generate_function_stub(
"test",
TestClass.test,
output=output,
class_info=ClassInfo(self_var="self", cls=TestClass, name="TestClass"),
)
assert_equal(output, ["def test(self, arg0: int) -> Any: ..."])
assert_equal(gen.get_imports().splitlines(), [])
def test_generate_c_type_with_docstring_no_self_arg(self) -> None:
class TestClass:
def test(self, arg0: str) -> None:
"""
test(arg0: int)
"""
output: list[str] = []
mod = ModuleType(TestClass.__module__, "")
gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)
gen.generate_function_stub(
"test",
TestClass.test,
output=output,
class_info=ClassInfo(self_var="self", cls=TestClass, name="TestClass"),
)
assert_equal(output, ["def test(self, arg0: int) -> Any: ..."])
assert_equal(gen.get_imports().splitlines(), [])
def test_generate_c_type_classmethod(self) -> None:
class TestClass:
@classmethod
def test(cls, arg0: str) -> None:
pass
output: list[str] = []
mod = ModuleType(TestClass.__module__, "")
gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)
gen.generate_function_stub(
"test",
TestClass.test,
output=output,
class_info=ClassInfo(self_var="cls", cls=TestClass, name="TestClass"),
)
assert_equal(output, ["@classmethod", "def test(cls, *args, **kwargs): ..."])
assert_equal(gen.get_imports().splitlines(), [])
def test_generate_c_type_classmethod_with_overloads(self) -> None:
class TestClass:
@classmethod
def test(self, arg0: str) -> None:
"""
test(cls, arg0: str)
test(cls, arg0: int)
"""
pass
output: list[str] = []
mod = ModuleType(TestClass.__module__, "")
gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)
gen.generate_function_stub(
"test",
TestClass.test,
output=output,
class_info=ClassInfo(self_var="cls", cls=TestClass, name="TestClass"),
)
assert_equal(
output,
[
"@overload",
"@classmethod",
"def test(cls, arg0: str) -> Any: ...",
"@overload",
"@classmethod",
"def test(cls, arg0: int) -> Any: ...",
],
)
assert_equal(gen.get_imports().splitlines(), ["from typing import overload"])
def test_generate_c_type_with_docstring_empty_default(self) -> None:
class TestClass:
def test(self, arg0: str = "") -> None:
"""
test(self: TestClass, arg0: str = "")
"""
output: list[str] = []
mod = ModuleType(TestClass.__module__, "")
gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)
gen.generate_function_stub(
"test",
TestClass.test,
output=output,
class_info=ClassInfo(self_var="self", cls=TestClass, name="TestClass"),
)
assert_equal(output, ["def test(self, arg0: str = ...) -> Any: ..."])
assert_equal(gen.get_imports().splitlines(), [])
def test_generate_c_function_other_module_arg(self) -> None:
"""Test that if argument references type from other module, module will be imported."""