-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtest_stubs.py
More file actions
481 lines (415 loc) · 13.5 KB
/
test_stubs.py
File metadata and controls
481 lines (415 loc) · 13.5 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
import re
from textwrap import dedent
import libcst as cst
import libcst.matchers as cstm
import pytest
from docstub._stubs import Py2StubTransformer, _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 = _get_docstring_node(func_def)
assert isinstance(docstring_node, cst.SimpleString)
assert docstring_node.value == docstring
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 = _get_docstring_node(func_def)
assert docstring_node 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"),
# Replace pre-existing annotations
("annotated: float = 1.0", "annotated : int", "annotated: int"),
# 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 typing import ClassVar
class Foo:
a: int
b: float
c: tuple
d: ClassVar[bool]
def __init__(self, a) -> 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_existing_typed_return(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_overwriting_typed_return(self, capsys):
source = dedent(
'''
def foo() -> dict[str, int]:
"""
Returns
-------
out : int
"""
pass
'''
)
expected = dedent(
"""
def foo() -> int: ...
"""
)
transformer = Py2StubTransformer()
result = transformer.python_to_stub(source)
assert expected == result
captured = capsys.readouterr()
assert "Replacing existing inline return annotation" in captured.out
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