Debian Codegraph @

tests/test_nodes_position.py

raw
1 # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2 # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3 # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5 from __future__ import annotations
6
7 import textwrap
8 from tokenize import TokenError
9 from unittest import mock
10
11 from astroid import builder, nodes
12
13
14 class TestNodePosition:
15 """Test node ``position`` attribute."""
16
17 @staticmethod
18 def test_position_class() -> None:
19 """Position should only include keyword and name.
20
21 >>> class A(Parent):
22 >>> ^^^^^^^
23 """
24 code = textwrap.dedent("""
25 class A: #@
26 ...
27
28 class B(A): #@
29 pass
30
31 class C: #@
32 '''Docstring'''
33
34 class D: #@
35 ...
36
37 class E: #@
38 def f():
39 ...
40
41 @decorator
42 class F: #@
43 ...
44 """).strip()
45 ast_nodes: list[nodes.NodeNG] = builder.extract_node(code) # type: ignore[assignment]
46
47 a = ast_nodes[0]
48 assert isinstance(a, nodes.ClassDef)
49 assert a.position == (1, 0, 1, 7)
50
51 b = ast_nodes[1]
52 assert isinstance(b, nodes.ClassDef)
53 assert b.position == (4, 0, 4, 7)
54
55 c = ast_nodes[2]
56 assert isinstance(c, nodes.ClassDef)
57 assert c.position == (7, 0, 7, 7)
58
59 d = ast_nodes[3]
60 assert isinstance(d, nodes.ClassDef)
61 assert d.position == (10, 4, 10, 11)
62
63 e = ast_nodes[4]
64 assert isinstance(e, nodes.ClassDef)
65 assert e.position == (13, 0, 13, 7)
66
67 f = ast_nodes[5]
68 assert isinstance(f, nodes.ClassDef)
69 assert f.position == (18, 0, 18, 7)
70
71 @staticmethod
72 def test_position_function() -> None:
73 """Position should only include keyword and name.
74
75 >>> def func(var: int = 42):
76 >>> ^^^^^^^^
77 """
78 code = textwrap.dedent("""
79 def a(): #@
80 ...
81
82 def b(): #@
83 '''Docstring'''
84
85 def c( #@
86 var: int = 42
87 ):
88 def d(): #@
89 ...
90
91 @decorator
92 def e(): #@
93 ...
94 """).strip()
95 ast_nodes: list[nodes.NodeNG] = builder.extract_node(code) # type: ignore[assignment]
96
97 a = ast_nodes[0]
98 assert isinstance(a, nodes.FunctionDef)
99 assert a.position == (1, 0, 1, 5)
100
101 b = ast_nodes[1]
102 assert isinstance(b, nodes.FunctionDef)
103 assert b.position == (4, 0, 4, 5)
104
105 c = ast_nodes[2]
106 assert isinstance(c, nodes.FunctionDef)
107 assert c.position == (7, 0, 7, 5)
108
109 d = ast_nodes[3]
110 assert isinstance(d, nodes.FunctionDef)
111 assert d.position == (10, 4, 10, 9)
112
113 e = ast_nodes[4]
114 assert isinstance(e, nodes.FunctionDef)
115 assert e.position == (14, 0, 14, 5)
116
117 @staticmethod
118 def test_position_async_function() -> None:
119 """Position should only include keyword and name.
120
121 >>> async def func(var: int = 42):
122 >>> ^^^^^^^^^^^^^^
123 """
124 code = textwrap.dedent("""
125 async def a(): #@
126 ...
127
128 async def b(): #@
129 '''Docstring'''
130
131 async def c( #@
132 var: int = 42
133 ):
134 async def d(): #@
135 ...
136
137 @decorator
138 async def e(): #@
139 ...
140 """).strip()
141 ast_nodes: list[nodes.NodeNG] = builder.extract_node(code) # type: ignore[assignment]
142
143 a = ast_nodes[0]
144 assert isinstance(a, nodes.FunctionDef)
145 assert a.position == (1, 0, 1, 11)
146
147 b = ast_nodes[1]
148 assert isinstance(b, nodes.FunctionDef)
149 assert b.position == (4, 0, 4, 11)
150
151 c = ast_nodes[2]
152 assert isinstance(c, nodes.FunctionDef)
153 assert c.position == (7, 0, 7, 11)
154
155 d = ast_nodes[3]
156 assert isinstance(d, nodes.FunctionDef)
157 assert d.position == (10, 4, 10, 15)
158
159 e = ast_nodes[4]
160 assert isinstance(e, nodes.FunctionDef)
161 assert e.position == (14, 0, 14, 11)
162
163 @staticmethod
164 def test_position_malformed_tokenize() -> None:
165 """A ``TokenError`` from ``tokenize`` must not crash the build.
166
167 On Python < 3.12 malformed source could make ``generate_tokens``
168 raise a ``TokenError``; ``position`` is simply unavailable then.
169 """
170 with mock.patch(
171 "astroid.rebuilder.generate_tokens",
172 side_effect=TokenError("unexpected EOF in multi-line statement", (1, 0)),
173 ):
174 node = builder.extract_node("class A: #@\n ...")
175 assert isinstance(node, nodes.ClassDef)
176 assert node.position is None
177
178 @staticmethod
179 def test_position_carriage_return_line_endings() -> None:
180 """Lines ending in ``\\r`` must not crash the build (#3091).
181
182 The tokenizer treats a lone ``\\r`` as a line terminator while the
183 source kept by the rebuilder is split on ``\\n`` only, so the slice
184 tokenized for the position can be misaligned and raise
185 ``IndentationError``; ``position`` is simply unavailable then.
186 """
187 module = builder.parse("\rclass C:\n def f():\n 1\n 2")
188 klass = module.body[0]
189 assert isinstance(klass, nodes.ClassDef)
190 func = klass.body[0]
191 assert isinstance(func, nodes.FunctionDef)
192 assert klass.position is None
193 assert func.position is None
194
195 @staticmethod
196 def test_position_unnormalized_name() -> None:
197 """No position info when the name token never matches ``node.name``.
198
199 ``node.name`` is the NFKC-normalized identifier while ``tokenize``
200 yields the raw source spelling (here the ``fi`` ligature), so the
201 name token is never matched and no position can be computed.
202 """
203 node = builder.extract_node("class fi: #@\n ...")
204 assert isinstance(node, nodes.ClassDef)
205 assert node.name == "fi"
206 assert node.position is None