Debian Codegraph @

tests/test_inputtransformer2.py

raw
1 """Tests for the token-based transformers in IPython.core.inputtransformer2
2
3 Line-based transformers are the simpler ones; token-based transformers are
4 more complex. See test_inputtransformer2_line for tests for line-based
5 transformations.
6 """
7
8 import platform
9 import string
10 import sys
11 from textwrap import dedent
12
13 import pytest
14
15 from IPython.core import inputtransformer2 as ipt2
16 from IPython.core.inputtransformer2 import _find_assign_op, make_tokens_by_line
17
18 MULTILINE_MAGIC = (
19 """\
20 a = f()
21 %foo \\
22 bar
23 g()
24 """.splitlines(
25 keepends=True
26 ),
27 (2, 0),
28 """\
29 a = f()
30 get_ipython().run_line_magic('foo', ' bar')
31 g()
32 """.splitlines(
33 keepends=True
34 ),
35 )
36
37 INDENTED_MAGIC = (
38 """\
39 for a in range(5):
40 %ls
41 """.splitlines(
42 keepends=True
43 ),
44 (2, 4),
45 """\
46 for a in range(5):
47 get_ipython().run_line_magic('ls', '')
48 """.splitlines(
49 keepends=True
50 ),
51 )
52
53 CRLF_MAGIC = (
54 ["a = f()\n", "%ls\r\n", "g()\n"],
55 (2, 0),
56 ["a = f()\n", "get_ipython().run_line_magic('ls', '')\n", "g()\n"],
57 )
58
59 MULTILINE_MAGIC_ASSIGN = (
60 """\
61 a = f()
62 b = %foo \\
63 bar
64 g()
65 """.splitlines(
66 keepends=True
67 ),
68 (2, 4),
69 """\
70 a = f()
71 b = get_ipython().run_line_magic('foo', ' bar')
72 g()
73 """.splitlines(
74 keepends=True
75 ),
76 )
77
78 MULTILINE_SYSTEM_ASSIGN = (
79 """\
80 a = f()
81 b = !foo \\
82 bar
83 g()
84 """.splitlines(
85 keepends=True
86 ),
87 (2, 4),
88 """\
89 a = f()
90 b = get_ipython().getoutput('foo bar')
91 g()
92 """.splitlines(
93 keepends=True
94 ),
95 )
96
97 #####
98
99 MULTILINE_SYSTEM_ASSIGN_AFTER_DEDENT = (
100 """\
101 def test():
102 for i in range(1):
103 print(i)
104 res =! ls
105 """.splitlines(
106 keepends=True
107 ),
108 (4, 7),
109 """\
110 def test():
111 for i in range(1):
112 print(i)
113 res =get_ipython().getoutput(\' ls\')
114 """.splitlines(
115 keepends=True
116 ),
117 )
118
119 ######
120
121 AUTOCALL_QUOTE = ([",f 1 2 3\n"], (1, 0), ['f("1", "2", "3")\n'])
122
123 AUTOCALL_QUOTE2 = ([";f 1 2 3\n"], (1, 0), ['f("1 2 3")\n'])
124
125 AUTOCALL_PAREN = (["/f 1 2 3\n"], (1, 0), ["f(1, 2, 3)\n"])
126
127 SIMPLE_HELP = (["foo?\n"], (1, 0), ["get_ipython().run_line_magic('pinfo', 'foo')\n"])
128
129 DETAILED_HELP = (
130 ["foo??\n"],
131 (1, 0),
132 ["get_ipython().run_line_magic('pinfo2', 'foo')\n"],
133 )
134
135 MAGIC_HELP = (["%foo?\n"], (1, 0), ["get_ipython().run_line_magic('pinfo', '%foo')\n"])
136
137 HELP_IN_EXPR = (
138 ["a = b + c?\n"],
139 (1, 0),
140 ["get_ipython().run_line_magic('pinfo', 'c')\n"],
141 )
142
143 HELP_CONTINUED_LINE = (
144 """\
145 a = \\
146 zip?
147 """.splitlines(
148 keepends=True
149 ),
150 (1, 0),
151 [r"get_ipython().run_line_magic('pinfo', 'zip')" + "\n"],
152 )
153
154 HELP_MULTILINE = (
155 """\
156 (a,
157 b) = zip?
158 """.splitlines(
159 keepends=True
160 ),
161 (1, 0),
162 [r"get_ipython().run_line_magic('pinfo', 'zip')" + "\n"],
163 )
164
165 HELP_UNICODE = (
166 ["π.foo?\n"],
167 (1, 0),
168 ["get_ipython().run_line_magic('pinfo', 'π.foo')\n"],
169 )
170
171
172 def null_cleanup_transformer(lines):
173 """
174 A cleanup transform that returns an empty list.
175 """
176 return []
177
178
179 def test_check_make_token_by_line_never_ends_empty():
180 """
181 Check that not sequence of single or double characters ends up leading to en empty list of tokens
182 """
183 from string import printable
184
185 for c in printable:
186 assert make_tokens_by_line(c)[-1] != []
187 for k in printable:
188 assert make_tokens_by_line(c + k)[-1] != []
189
190
191 def check_find(transformer, case, match=True):
192 sample, expected_start, _ = case
193 tbl = make_tokens_by_line(sample)
194 res = transformer.find(tbl)
195 if match:
196 # start_line is stored 0-indexed, expected values are 1-indexed
197 assert (res.start_line + 1, res.start_col) == expected_start
198 return res
199 else:
200 assert res is None
201
202
203 def check_transform(transformer_cls, case):
204 lines, start, expected = case
205 transformer = transformer_cls(start)
206 assert transformer.transform(lines) == expected
207
208
209 def test_continued_line():
210 lines = MULTILINE_MAGIC_ASSIGN[0]
211 assert ipt2.find_end_of_continued_line(lines, 1) == 2
212
213 assert ipt2.assemble_continued_line(lines, (1, 5), 2) == "foo bar"
214
215
216 def test_find_assign_magic():
217 check_find(ipt2.MagicAssign, MULTILINE_MAGIC_ASSIGN)
218 check_find(ipt2.MagicAssign, MULTILINE_SYSTEM_ASSIGN, match=False)
219 check_find(ipt2.MagicAssign, MULTILINE_SYSTEM_ASSIGN_AFTER_DEDENT, match=False)
220
221
222 def test_transform_assign_magic():
223 check_transform(ipt2.MagicAssign, MULTILINE_MAGIC_ASSIGN)
224
225
226 def test_find_assign_system():
227 check_find(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN)
228 check_find(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN_AFTER_DEDENT)
229 check_find(ipt2.SystemAssign, (["a = !ls\n"], (1, 5), None))
230 check_find(ipt2.SystemAssign, (["a=!ls\n"], (1, 2), None))
231 check_find(ipt2.SystemAssign, MULTILINE_MAGIC_ASSIGN, match=False)
232
233
234 def test_transform_assign_system():
235 check_transform(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN)
236 check_transform(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN_AFTER_DEDENT)
237
238
239 def test_find_magic_escape():
240 check_find(ipt2.EscapedCommand, MULTILINE_MAGIC)
241 check_find(ipt2.EscapedCommand, INDENTED_MAGIC)
242 check_find(ipt2.EscapedCommand, MULTILINE_MAGIC_ASSIGN, match=False)
243
244
245 def test_transform_magic_escape():
246 check_transform(ipt2.EscapedCommand, MULTILINE_MAGIC)
247 check_transform(ipt2.EscapedCommand, INDENTED_MAGIC)
248 check_transform(ipt2.EscapedCommand, CRLF_MAGIC)
249
250
251 def test_find_autocalls():
252 for case in [AUTOCALL_QUOTE, AUTOCALL_QUOTE2, AUTOCALL_PAREN]:
253 print("Testing %r" % case[0])
254 check_find(ipt2.EscapedCommand, case)
255
256
257 def test_transform_autocall():
258 for case in [AUTOCALL_QUOTE, AUTOCALL_QUOTE2, AUTOCALL_PAREN]:
259 print("Testing %r" % case[0])
260 check_transform(ipt2.EscapedCommand, case)
261
262
263 def test_find_help():
264 for case in [SIMPLE_HELP, DETAILED_HELP, MAGIC_HELP, HELP_IN_EXPR]:
265 check_find(ipt2.HelpEnd, case)
266
267 tf = check_find(ipt2.HelpEnd, HELP_CONTINUED_LINE)
268 assert tf.q_line == 1
269 assert tf.q_col == 3
270
271 tf = check_find(ipt2.HelpEnd, HELP_MULTILINE)
272 assert tf.q_line == 1
273 assert tf.q_col == 8
274
275 # ? in a comment does not trigger help
276 check_find(ipt2.HelpEnd, (["foo # bar?\n"], None, None), match=False)
277 # Nor in a string
278 check_find(ipt2.HelpEnd, (["foo = '''bar?\n"], None, None), match=False)
279
280
281 def test_transform_help():
282 tf = ipt2.HelpEnd((1, 0), (1, 9))
283 assert tf.transform(HELP_IN_EXPR[0]) == HELP_IN_EXPR[2]
284
285 tf = ipt2.HelpEnd((1, 0), (2, 3))
286 assert tf.transform(HELP_CONTINUED_LINE[0]) == HELP_CONTINUED_LINE[2]
287
288 tf = ipt2.HelpEnd((1, 0), (2, 8))
289 assert tf.transform(HELP_MULTILINE[0]) == HELP_MULTILINE[2]
290
291 tf = ipt2.HelpEnd((1, 0), (1, 0))
292 assert tf.transform(HELP_UNICODE[0]) == HELP_UNICODE[2]
293
294
295 def test_find_assign_op_dedent():
296 """
297 be careful that empty token like dedent are not counted as parens
298 """
299
300 class Tk:
301 def __init__(self, s):
302 self.string = s
303
304 assert _find_assign_op([Tk(s) for s in ("", "a", "=", "b")]) == 2
305 assert (
306 _find_assign_op([Tk(s) for s in ("", "(", "a", "=", "b", ")", "=", "5")]) == 6
307 )
308
309
310 extra_closing_paren_param = (
311 pytest.param("(\n))", "invalid", None)
312 if sys.version_info >= (3, 12)
313 else pytest.param("(\n))", "incomplete", 0)
314 )
315 examples = [
316 pytest.param("a = 1", "complete", None),
317 pytest.param("for a in range(5):", "incomplete", 4),
318 pytest.param("for a in range(5):\n if a > 0:", "incomplete", 8),
319 pytest.param("raise = 2", "invalid", None),
320 pytest.param("a = [1,\n2,", "incomplete", 0),
321 extra_closing_paren_param,
322 pytest.param("\\\r\n", "incomplete", 0),
323 pytest.param("a = '''\n hi", "incomplete", 3),
324 pytest.param("def a():\n x=1\n global x", "invalid", None),
325 pytest.param("a \\ ", "invalid", None), # Nothing allowed after backslash,
326 pytest.param("1\\\n+2", "complete", None),
327 ]
328
329
330 @pytest.mark.parametrize("code, expected, number", examples)
331 def test_check_complete_param(code, expected, number):
332 cc = ipt2.TransformerManager().check_complete
333 assert cc(code) == (expected, number)
334
335
336 @pytest.mark.xfail(platform.python_implementation() == "PyPy", reason="fail on pypy")
337 def test_check_complete():
338 cc = ipt2.TransformerManager().check_complete
339
340 example = dedent(
341 """
342 if True:
343 a=1"""
344 )
345
346 assert cc(example) == ("incomplete", 4)
347 assert cc(example + "\n") == ("complete", None)
348 assert cc(example + "\n ") == ("complete", None)
349
350 # no need to loop on all the letters/numbers.
351 short = "12abAB" + string.printable[62:]
352 for c in short:
353 # test does not raise:
354 cc(c)
355 for k in short:
356 cc(c + k)
357
358 assert cc("def f():\n x=0\n \\\n ") == ("incomplete", 2)
359
360
361 @pytest.mark.xfail(platform.python_implementation() == "PyPy", reason="fail on pypy")
362 @pytest.mark.parametrize(
363 "value, expected",
364 [
365 ('''def foo():\n """''', ("incomplete", 4)),
366 ("""async with example:\n pass""", ("incomplete", 4)),
367 ("""async with example:\n pass\n """, ("complete", None)),
368 ],
369 )
370 def test_check_complete_II(value, expected):
371 """
372 Test that multiple line strings are properly handled.
373
374 Separate test function for convenience
375
376 """
377 cc = ipt2.TransformerManager().check_complete
378 assert cc(value) == expected
379
380
381 @pytest.mark.parametrize(
382 "value, expected",
383 [
384 (")", ("invalid", None)),
385 ("]", ("invalid", None)),
386 ("}", ("invalid", None)),
387 (")(", ("invalid", None)),
388 ("][", ("invalid", None)),
389 ("}{", ("invalid", None)),
390 ("]()(", ("invalid", None)),
391 ("())(", ("invalid", None)),
392 (")[](", ("invalid", None)),
393 ("()](", ("invalid", None)),
394 ],
395 )
396 def test_check_complete_invalidates_sunken_brackets(value, expected):
397 """
398 Test that a single line with more closing brackets than the opening ones is
399 interpreted as invalid
400 """
401 cc = ipt2.TransformerManager().check_complete
402 assert cc(value) == expected
403
404
405 def test_null_cleanup_transformer():
406 manager = ipt2.TransformerManager()
407 manager.cleanup_transforms.insert(0, null_cleanup_transformer)
408 assert manager.transform_cell("") == ""
409
410
411 def test_side_effects_I():
412 count = 0
413
414 def counter(lines):
415 nonlocal count
416 count += 1
417 return lines
418
419 counter.has_side_effects = True
420
421 manager = ipt2.TransformerManager()
422 manager.cleanup_transforms.insert(0, counter)
423 assert manager.check_complete("a=1\n") == ("complete", None)
424 assert count == 0
425
426
427 def test_side_effects_II():
428 count = 0
429
430 def counter(lines):
431 nonlocal count
432 count += 1
433 return lines
434
435 counter.has_side_effects = True
436
437 manager = ipt2.TransformerManager()
438 manager.line_transforms.insert(0, counter)
439 assert manager.check_complete("b=1\n") == ("complete", None)
440 assert count == 0