Debian Codegraph @

tests/test_pycode/test_pycode_ast.py

raw
1 """Test pycode.ast"""
2
3 from __future__ import annotations
4
5 import ast
6
7 import pytest
8
9 from sphinx.pycode.ast import unparse as ast_unparse
10
11
12 @pytest.mark.parametrize(
13 ('source', 'expected'),
14 [
15 ('a + b', 'a + b'), # Add
16 ('a and b', 'a and b'), # And
17 ('os.path', 'os.path'), # Attribute
18 ('1 * 2', '1 * 2'), # BinOp
19 ('a & b', 'a & b'), # BitAnd
20 ('a | b', 'a | b'), # BitOr
21 ('a ^ b', 'a ^ b'), # BitXor
22 ('a and b and c', 'a and b and c'), # BoolOp
23 ("b'bytes'", "b'bytes'"), # Bytes
24 ('object()', 'object()'), # Call
25 ('1234', '1234'), # Constant, Num
26 ("{'key1': 'value1', 'key2': 'value2'}",
27 "{'key1': 'value1', 'key2': 'value2'}"), # Dict
28 ('a / b', 'a / b'), # Div
29 ('...', '...'), # Ellipsis
30 ('a // b', 'a // b'), # FloorDiv
31 ('Tuple[int, int]', 'Tuple[int, int]'), # Index, Subscript
32 ('~1', '~1'), # Invert
33 ('lambda x, y: x + y',
34 'lambda x, y: ...'), # Lambda
35 ('[1, 2, 3]', '[1, 2, 3]'), # List
36 ('a << b', 'a << b'), # LShift
37 ('a @ b', 'a @ b'), # MatMult
38 ('a % b', 'a % b'), # Mod
39 ('a * b', 'a * b'), # Mult
40 ('sys', 'sys'), # Name, NameConstant
41 ('not a', 'not a'), # Not
42 ('a or b', 'a or b'), # Or
43 ('a**b', 'a**b'), # Pow
44 ('a >> b', 'a >> b'), # RShift
45 ('{1, 2, 3}', '{1, 2, 3}'), # Set
46 ('a - b', 'a - b'), # Sub
47 ("'str'", "'str'"), # Str
48 ('+a', '+a'), # UAdd
49 ('-1', '-1'), # UnaryOp
50 ('-a', '-a'), # USub
51 ('(1, 2, 3)', '(1, 2, 3)'), # Tuple
52 ('()', '()'), # Tuple (empty)
53 ('(1,)', '(1,)'), # Tuple (single item)
54 ('lambda x=0, /, y=1, *args, z, **kwargs: x + y + z',
55 'lambda x=0, /, y=1, *args, z, **kwargs: ...'), # posonlyargs
56 ('0x1234', '0x1234'), # Constant
57 ('1_000_000', '1_000_000'), # Constant
58 ('Tuple[:,:]', 'Tuple[:, :]'), # Index, Subscript, 2x Slice
59 ('Tuple[1:2]', 'Tuple[1:2]'), # Index, Subscript, Slice(no-step)
60 ('Tuple[1:2:3]', 'Tuple[1:2:3]'), # Index, Subscript, Slice
61 ('x[:, np.newaxis, :, :]',
62 'x[:, np.newaxis, :, :]'), # Index, Subscript, numpy extended syntax
63 ('y[:, 1:3][np.array([0, 2, 4]), :]',
64 'y[:, 1:3][np.array([0, 2, 4]), :]'), # Index, 2x Subscript, numpy extended syntax
65 ('*tuple[str, int]', '*tuple[str, int]'), # Starred
66 ],
67 ) # fmt: skip
68 def test_unparse(source: str, expected: str) -> None:
69 expr = ast.parse(source).body[0]
70 assert isinstance(expr, ast.Expr)
71 assert ast_unparse(expr.value, source) == expected
72
73
74 def test_unparse_None() -> None:
75 assert ast_unparse(None) is None