-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtest_stubs.py
More file actions
789 lines (704 loc) · 22.1 KB
/
test_stubs.py
File metadata and controls
789 lines (704 loc) · 22.1 KB
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
import logging
import re
from textwrap import dedent
import libcst as cst
import libcst.matchers as cstm
import pytest
from docstub._stubs import Py2StubTransformer, _dataclass_matcher, _get_docstring_node
class Test_get_docstring_node:
def test_func(self):
docstring = dedent(
'''
"""First line of docstring.
Parameters
----------
a : int
Description of `a`.
b : float, optional
"""
'''
).strip()
code = dedent(
'''
def foo(a, b=None):
"""First line of docstring.
Parameters
----------
a : int
Description of `a`.
b : float, optional
"""
"""Another multiline string
that isn't the docstring.
"""
return a + b
'''
)
module = cst.parse_module(code)
matches = cstm.findall(module, cstm.FunctionDef())
assert len(matches) == 1
func_def = matches[0]
assert isinstance(func_def, cst.FunctionDef)
docstring_node, docstring_result = _get_docstring_node(func_def)
assert isinstance(docstring_node, cst.SimpleString)
assert docstring_node.value == docstring
assert docstring_result == docstring.strip('"')
def test_func_without_docstring(self):
code = '''
def foo(a, b=None):
c = a + b
"""Another multiline string
that isn't the docstring.
"""
return c
'''
code = dedent(code)
module = cst.parse_module(code)
matches = cstm.findall(module, cstm.FunctionDef())
assert len(matches) == 1
func_def = matches[0]
assert isinstance(func_def, cst.FunctionDef)
docstring_node, docstring = _get_docstring_node(func_def)
assert docstring_node is None
assert docstring is None
MODULE_ATTRIBUTE_TEMPLATE = '''\
"""Module docstring.
Attributes
----------
{doctype}
"""
{assign}
'''
CLASS_ATTRIBUTE_TEMPLATE = '''\
class TopLevel:
"""Class docstring.
Attributes
----------
{doctype}
"""
{assign}
'''
NESTED_CLASS_ATTRIBUTE_TEMPLATE = '''\
class TopLevel:
class Nested:
"""Class docstring.
Attributes
----------
{doctype}
"""
{assign}
'''
class Test_Py2StubTransformer:
# TODO Refactor so that there's less overlap between tests
# For many cases, the tests aren't very focused on only a single property.
# A change / fix might affect more tests than it should. Additionally,
# the tests are sensitive to non-meaningful whitespace.
def test_default_None(self):
# Appending `| None` if a doctype is marked as "optional"
# is only correct if the default is actually None
# Ref: https://github.com/scientific-python/docstub/issues/13
# TODO use literal values for simple defaults
# https://typing.readthedocs.io/en/latest/guides/writing_stubs.html#functions-and-methods
source = dedent(
'''
def foo(a=None, b=1):
"""
Parameters
----------
a : int, optional
b : int, optional
"""
'''
)
expected = dedent(
"""
def foo(a: int | None=..., b: int=...) -> None: ...
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
def test_optional_without_default(self):
source = dedent(
'''
def foo(a):
"""
Parameters
----------
a : int, optional
"""
'''
)
expected = dedent(
"""
def foo(a: int) -> None: ...
"""
)
transformer = Py2StubTransformer()
# TODO should warn about a required arg being marked "optional"
result = transformer.python_to_stub(source)
assert expected == result
# fmt: off
@pytest.mark.parametrize(
("assign", "expected"),
[
("annotated: int", "annotated: int"),
# No implicit optional for values of `None`
("annotated_value: int = None", "annotated_value: int"),
("undocumented_assign = None", "undocumented_assign: Incomplete"),
# Type aliases are untouched
("annot_alias: TypeAlias = int", "annot_alias: TypeAlias = int"),
("type type_stmt = int", "type type_stmt = int"),
# Unpacking assignments are expanded
("a, b = (4, 5)", "a: Incomplete; b: Incomplete"),
("x, *y = (4, 5)", "x: Incomplete; y: Incomplete"),
# All is untouched
("__all__ = ['foo']", "__all__ = ['foo']"),
("__all__: list[str] = ['foo']", "__all__: list[str] = ['foo']"),
],
)
@pytest.mark.parametrize("scope", ["module", "class", "nested class"])
def test_attributes_no_doctype(self, assign, expected, scope):
if scope == "module":
src = MODULE_ATTRIBUTE_TEMPLATE.format(assign=assign, doctype="")
elif scope == "class":
src = CLASS_ATTRIBUTE_TEMPLATE.format(assign=assign, doctype="")
else:
assert scope == "nested class"
src = NESTED_CLASS_ATTRIBUTE_TEMPLATE.format(assign=assign, doctype="")
transformer = Py2StubTransformer()
result = transformer.python_to_stub(src)
# Find exactly one occurrence of `expected`
pattern = f"^ *({re.escape(expected)})$"
matches = re.findall(pattern, result, flags=re.MULTILINE)
assert [matches] == [[expected]], result
# Docstrings are stripped
assert "'''" not in result
assert '"""' not in result
if "Any" in result:
assert "from typing import Any" in result
# fmt: on
# fmt: off
@pytest.mark.parametrize(
("assign", "doctype", "expected"),
[
("plain = 3", "plain : int", "plain: int"),
("plain = None", "plain : int", "plain: int"),
("x, y = (1, 2)", "x : int", "x: int; y: Incomplete"),
# Keep pre-existing annotations
("annotated: float = 1.0", "annotated : int", "annotated: float"),
# Type aliases are untouched
("alias: TypeAlias = int", "alias : str", "alias: TypeAlias = int"),
("type alias = int", "alias : str", "type alias = int"),
],
)
@pytest.mark.parametrize("scope", ["module", "class", "nested class"])
def test_attributes_with_doctype(self, assign, doctype, expected, scope):
if scope == "module":
src = MODULE_ATTRIBUTE_TEMPLATE.format(assign=assign, doctype=doctype)
elif scope == "class":
src = CLASS_ATTRIBUTE_TEMPLATE.format(assign=assign, doctype=doctype)
else:
assert scope == "nested class"
src = NESTED_CLASS_ATTRIBUTE_TEMPLATE.format(assign=assign, doctype=doctype)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(src)
# Find exactly one occurrence of `expected`
pattern = f"^ *({re.escape(expected)})$"
matches = re.findall(pattern, result, flags=re.MULTILINE)
assert [matches] == [[expected]], result
# Docstrings are stripped
assert "'''" not in result
assert '"""' not in result
if "Incomplete" in result:
assert "from _typeshed import Incomplete" in result
# fmt: on
def test_class_init_attributes(self):
src = dedent(
"""
class Foo:
'''
Attributes
----------
a : int
b : float
c : tuple
d : ClassVar[bool]
'''
c: list
d = True
def __init__(self, a):
self.a = a
self.e = None
"""
)
expected = dedent(
"""
from _typeshed import Incomplete
from typing import ClassVar
class Foo:
a: int
b: float
c: list
d: ClassVar[bool]
def __init__(self, a: Incomplete) -> None: ...
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(src)
assert result == expected
def test_undocumented_objects(self):
# TODO test undocumented objects
# https://typing.readthedocs.io/en/latest/guides/writing_stubs.html#undocumented-objects
pass
def test_keep_assign_param(self):
source = dedent(
"""
a: str
"""
)
expected = dedent(
"""
a: str
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
def test_module_assign_conflict(self, caplog):
source = dedent(
'''
"""
Attributes
----------
a : int
"""
a: str
'''
)
expected = dedent(
"""
a: str
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
assert caplog.messages == ["Keeping existing inline annotation for assignment"]
assert "ignoring docstring: int" in caplog.records[0].details
assert caplog.records[0].levelno == logging.WARNING
def test_module_assign_no_conflict(self, capsys):
source = dedent(
'''
"""
Attributes
----------
a :
No type info here; it's already inlined.
b : float
"""
a: int
b = 3
'''
)
expected = dedent(
"""
a: int
b: float
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
# No warning should have been raised, since there is no conflict
# between docstring and inline annotation
output = capsys.readouterr()
assert output.out == ""
def test_class_assign_keep_inline_annotation(self):
source = dedent(
"""
class Foo:
a: str
"""
)
expected = dedent(
"""
class Foo:
a: str
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
def test_class_assign_conflict(self, caplog):
source = dedent(
'''
class Foo:
"""
Attributes
----------
a : Sized
"""
a: str
'''
)
expected = dedent(
"""
class Foo:
a: str
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
assert caplog.messages == ["Keeping existing inline annotation for assignment"]
assert caplog.records[0].levelno == logging.WARNING
def test_class_assign_no_conflict(self, caplog):
source = dedent(
'''
class Foo:
"""
Attributes
----------
a :
No type info here; it's already inlined.
b : float
"""
a: int
b = 3
'''
)
expected = dedent(
"""
class Foo:
a: int
b: float
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
# No warning should have been raised, since there is no conflict
# between docstring and inline annotation
assert caplog.messages == []
def test_param_keep_inline_annotation(self):
source = dedent(
"""
def foo(a: str) -> None:
pass
"""
)
expected = dedent(
"""
def foo(a: str) -> None: ...
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
def test_param_conflict(self, caplog):
source = dedent(
'''
def foo(a: int) -> None:
"""
Parameters
----------
a : Sized
"""
pass
'''
)
expected = dedent(
"""
def foo(a: int) -> None: ...
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
assert caplog.messages == ["Keeping existing inline parameter annotation"]
assert "ignoring docstring: Sized" in caplog.records[0].details
assert caplog.records[0].levelno == logging.WARNING
@pytest.mark.parametrize("missing", ["", "b", "b :"])
def test_missing_param(self, missing, caplog):
source = dedent(
f'''
def foo(a, b) -> None:
"""
Parameters
----------
a : int
{missing}
"""
'''
)
expected = dedent(
"""
from _typeshed import Incomplete
def foo(a: int, b: Incomplete) -> None: ...
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
assert caplog.messages == ["Missing annotation for parameter 'b'"]
assert caplog.records[0].levelno == logging.WARNING
def test_missing_param_inline(self, caplog):
source = dedent(
"""
def foo(a: int, b) -> None:
pass
"""
)
expected = dedent(
"""
from _typeshed import Incomplete
def foo(a: int, b: Incomplete) -> None: ...
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
assert caplog.messages == ["Missing annotation for parameter 'b'"]
assert caplog.records[0].levelno == logging.WARNING
@pytest.mark.parametrize("missing", ["", "b", "b :"])
def test_missing_attr(self, missing, caplog):
source = dedent(
f'''
class Foo:
"""
Attributes
----------
a : ClassVar[int]
{missing}
"""
a = 3
b = True
'''
)
expected = dedent(
"""
from _typeshed import Incomplete
from typing import ClassVar
class Foo:
a: ClassVar[int]
b: Incomplete
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
assert caplog.messages == ["Missing annotation for assignment 'b'"]
assert caplog.records[0].levelno == logging.WARNING
def test_missing_attr_inline(self, caplog):
source = dedent(
"""
from typing import ClassVar
class Foo:
a: ClassVar[int] = 3
b = True
"""
)
expected = dedent(
"""
from _typeshed import Incomplete
from typing import ClassVar
class Foo:
a: ClassVar[int]
b: Incomplete
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
assert caplog.messages == ["Missing annotation for assignment 'b'"]
assert caplog.records[0].levelno == logging.WARNING
def test_return_keep_inline_annotation(self):
source = dedent(
"""
def foo() -> str:
pass
"""
)
expected = dedent(
"""
def foo() -> str: ...
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
def test_return_conflict(self, caplog):
source = dedent(
'''
def foo() -> int:
"""
Returns
-------
out : Sized
"""
pass
'''
)
expected = dedent(
"""
def foo() -> int: ...
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
assert caplog.messages == ["Keeping existing inline return annotation"]
assert "ignoring docstring: Sized" in caplog.records[0].details
assert caplog.records[0].levelno == logging.WARNING
def test_preserved_type_comment(self):
source = dedent(
"""
# Import untyped library
import untyped # type: ignore
"""
)
expected = dedent(
"""
import untyped # type: ignore
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
@pytest.mark.xfail(reason="not supported yet")
def test_preserved_comments_extended(self):
source = dedent(
"""
# Import untyped library
import untyped # type: ignore
class Foo:
a = 3 # type: int
def bar(x: str) -> None: # undocumented
pass
"""
)
expected = dedent(
"""
import untyped # type: ignore
class Foo:
a = 3 # type: int
def bar(x: str) -> None: ... # undocumented
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
def test_on_off_comment(self):
source = dedent(
"""
class Foo:
'''
Parameters
----------
a
b
c
d
'''
# docstub: off
a: int = None
b: str = ""
# docstub: on
c: int = None
d: str = ""
"""
)
expected = dedent(
"""
class Foo:
a: int = None
b: str = ""
c: int
d: str
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
# Removing the comments leaves the whitespace from the indent,
# remove these empty lines from the result too
result = dedent(result)
assert expected == result
@pytest.mark.parametrize("decorator", ["dataclass", "dataclasses.dataclass"])
def test_dataclass(self, decorator):
source = dedent(
f"""
@{decorator}
class Foo:
a: float
b: int = 3
c: str = None
_: KW_ONLY
d: dict[str, Any] = field(default_factory=dict)
e: InitVar[tuple] = tuple()
f: ClassVar
g: ClassVar[float]
h: Final[ClassVar[int]] = 1
"""
)
expected = dedent(
f"""
@{decorator}
class Foo:
a: float
b: int = ...
c: str = ...
_: KW_ONLY
d: dict[str, Any] = ...
e: InitVar[tuple] = ...
f: ClassVar
g: ClassVar[float]
h: Final[ClassVar[int]]
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
def test_args_kwargs(self):
# Unpack and TypedDict (PEP 692) are not yet considered / supported
source = dedent(
"""
def foo(*args, **kwargs):
'''
Parameters
----------
*args : str
**kwargs : int
'''
"""
)
expected = dedent(
"""
def foo(*args: str, **kwargs: int) -> None: ...
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
@pytest.mark.parametrize(
("decorators", "expected"),
[
("@dataclass", True),
("@dataclass(frozen=True)", True),
("@dataclasses.dataclass(frozen=True)", True),
("@dc.dataclass", True),
("", False),
("@other", False),
("@other(dataclass=True)", False),
],
)
def test_dataclass_matcher(decorators, expected):
source = dedent(
"""
{decorators}
class Foo:
pass
"""
).format(decorators=decorators)
class_def = cst.parse_statement(source)
assert cstm.matches(class_def, _dataclass_matcher) is expected