Debian Codegraph @

pypy/interpreter/astcompiler/test/apptest_misc.py

raw symbols SCIP
1 import pytest
2 import warnings
3
4 def test_warning_to_error_translation():
5 statement = """\
6 def wrong1():
7 a = 1
8 b = 2
9 global a
10 global b
11 """
12 with warnings.catch_warnings():
13 warnings.filterwarnings("error", module="<test string>")
14 try:
15 compile(statement, '<test string>', 'exec')
16 except SyntaxError as err:
17 assert err.lineno is not None
18 assert err.filename is not None
19 assert err.offset is not None
20 assert err.msg is not None
21
22 def test_error_message_ast():
23 import ast
24 pos = dict(lineno=2, col_offset=3)
25 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)], [])
26 with pytest.raises(TypeError) as excinfo:
27 compile(m, 'fn', 'exec')
28 assert "expected some sort of expr, but got" in str(excinfo.value)
29
30 def test_weird_exec_bug():
31 with pytest.raises(SyntaxError) as excinfo:
32 compile('exec {1:(foo.)}', 'fn', 'exec')
33 assert excinfo.value.offset == 6
34
35 def test_warning_decimal():
36 with warnings.catch_warnings(record=True) as w:
37 warnings.simplefilter("always")
38 compile("0x1for 2", "fn", "exec")
39 assert len(w) == 1
40 assert str(w[0].message) == "invalid hexadecimal literal"
41 assert issubclass(w[0].category, SyntaxWarning)
42 assert w[0].lineno == 1
43
44 # Compiling with a SyntaxError may or may not emit the warning first
45 # depending on the implementation (CPython does, PyPy does not).
46 with warnings.catch_warnings(record=True) as w:
47 with pytest.raises(SyntaxError):
48 warnings.simplefilter("always")
49 compile("0x1for 2 a b c", "fn", "exec")
50 assert len(w) in (0, 1)
51
52 def test_warn_assert_tuple():
53 for sourceline in ["assert(False, 'abc')", "assert(x, 'abc')"]:
54 with warnings.catch_warnings(record=True) as w:
55 warnings.simplefilter("always")
56 compile(sourceline, "fn", "exec")
57 assert len(w) == 1
58 assert "perhaps remove parentheses" in str(w[0].message)
59 assert w[0].lineno == 1
60
61 def test_warn_wrong_indices():
62 for sourceline in ["(1, 2) [2, 3]", "(x, y) [a, b]"]:
63 with warnings.catch_warnings(record=True) as w:
64 warnings.simplefilter("always")
65 compile(sourceline, "fn", "exec")
66 assert len(w) == 1
67 assert "indices must be" in str(w[0].message)
68 assert w[0].lineno == 1
69
70 def test_error_position_unicode():
71 source = "ááá ßßß úúú"
72 try:
73 compile(source, 'fn', 'exec')
74 except SyntaxError as e:
75 assert e.lineno == e.end_lineno == 1
76 assert e.offset == 5
77 assert e.end_offset == 8
78
79
80 def test_crash_debug():
81 import ast
82 tree = ast.parse("@deco1\n@deco2()\n@deco3(1)\ndef f(): pass")
83 compile(tree, '<string>', 'exec')
84
85
86 def test_compile_nonascii_char_in_bytes_error():
87 with pytest.raises(SyntaxError) as excinfo:
88 compile("b = b'café'", "long-filename.py", "exec")
89 assert excinfo.value.filename == "long-filename.py"
90 assert excinfo.value.msg == "bytes can only contain ASCII literal characters"
91
92 def test_decorator_error_lineno():
93 # The traceback for a failing decorator should point to the decorator
94 # line, not the def line. See https://github.com/pypy/pypy/issues/5213
95 import traceback
96
97 def dec_error(func):
98 raise TypeError("boom")
99 def dec_fine(func):
100 return func
101
102 def applydecs():
103 @dec_error # line 12 relative to start of applydecs body
104 @dec_fine
105 def g(): pass
106
107 try:
108 applydecs()
109 except TypeError:
110 tb = traceback.extract_tb(__import__('sys').exc_info()[2])
111 else:
112 assert False, "expected TypeError"
113
114 # find the frame for applydecs
115 frame = [f for f in tb if f.name == 'applydecs']
116 assert len(frame) == 1, frame
117 # The line text should be the decorator, not the def
118 assert frame[0].line is not None
119 assert frame[0].line.strip().startswith('@dec_error'), (
120 "expected decorator line, got: %r" % frame[0].line)
121
122
123 def test_decorated_function_store_on_def_line():
124 # After applying all decorators, the STORE instruction for the function
125 # name should be attributed to the 'def' line, not the outermost decorator.
126 # This matches CPython's behaviour and makes sys.settrace count the def
127 # line twice per decorated function definition.
128 import sys
129
130 src = """\
131 def id1(f): return f
132 def id2(f): return f
133 @id1
134 @id2
135 def g(): pass
136 """
137 ns = {}
138 traced_lines = []
139 code = compile(src, '<test_decorated_store>', 'exec')
140
141 def tracer(frame, event, arg):
142 if event == 'line' and frame.f_code is code:
143 traced_lines.append(frame.f_lineno)
144 return tracer
145
146 sys.settrace(tracer)
147 try:
148 exec(code, ns)
149 finally:
150 sys.settrace(None)
151
152 # line 5 is 'def g(): pass'
153 # it should be traced twice: once for MAKE_FUNCTION and once for STORE_NAME
154 assert traced_lines.count(5) == 2, (
155 "expected 'def g' line (5) traced twice (MAKE_FUNCTION + STORE_NAME), "
156 "got traced_lines=%r" % (traced_lines,))
157
158
159 def test_prep_reraise_star_no_import_trace():
160 # PREP_RERAISE_STAR must not trigger import-machinery trace events.
161 # If it calls app-level __import__, sys.settrace will fire call/line events
162 # inside <frozen importlib._bootstrap>, confusing pdb (GH-101517).
163 import sys
164
165 call_events = []
166
167 def tracer(frame, event, arg):
168 if event == 'call':
169 call_events.append(frame.f_code.co_filename)
170 return tracer
171
172 def func_with_except_star():
173 try:
174 raise KeyError("test")
175 except* Exception:
176 pass
177
178 sys.settrace(tracer)
179 try:
180 func_with_except_star()
181 finally:
182 sys.settrace(None)
183
184 import_calls = [f for f in call_events if 'importlib' in f or 'frozen' in f]
185 assert not import_calls, (
186 "PREP_RERAISE_STAR triggered import-machinery trace events: %r" % import_calls)
187
188
189 def test_gen_resume_no_spurious_line_event():
190 # After resuming a generator (which fires a 'call' event at the yield line),
191 # the first line event should be for the line AFTER the yield, not the yield
192 # line itself. This matches CPython's RESUME instruction behaviour.
193 #
194 # The bug triggers only when the generator was previously entered under a
195 # tracer that returned None for the call event (creating debugdata with
196 # f_lineno=-1 but no local trace, so line events never updated d.f_lineno).
197 # On the next resumption with a full tracer, old_lineno=-1 is restored after
198 # the call event, causing a spurious line event on the POP_TOP that follows
199 # YIELD_VALUE (same source line as the yield).
200 import sys
201
202 def gen():
203 yield 1
204 yield 2
205
206 gen_lineno_yield1 = gen.__code__.co_firstlineno + 1
207 gen_lineno_yield2 = gen.__code__.co_firstlineno + 2
208
209 first_gen_line = []
210
211 # Phase 1: run gen's first next() under a tracer that returns None for gen.
212 # This creates gen's debugdata via the call event but leaves f_lineno=-1
213 # (no local trace means no line events update it).
214 def non_stepping_tracer(frame, event, arg):
215 if frame.f_code is gen.__code__:
216 return None # no local trace -- debugdata.f_lineno stays -1
217 return non_stepping_tracer
218
219 # Phase 2: resume gen under a full tracer, record first line event in gen.
220 def stepping_tracer(frame, event, arg):
221 if event == 'line' and frame.f_code is gen.__code__:
222 if not first_gen_line:
223 first_gen_line.append(frame.f_lineno)
224 return stepping_tracer
225
226 g = gen()
227
228 sys.settrace(non_stepping_tracer)
229 next(g) # runs to yield 1; creates debugdata with f_lineno=-1
230 sys.settrace(None)
231
232 # Phase 2: resume gen -- call event fires at yield-1 line; first subsequent
233 # line event must be the yield-2 line, not yield-1 again.
234 sys.settrace(stepping_tracer)
235 try:
236 next(g) # runs from after yield 1 to yield 2
237 except StopIteration:
238 pass
239 sys.settrace(None)
240
241 assert first_gen_line, "expected a line event inside gen, got none"
242 assert first_gen_line[0] != gen_lineno_yield1, (
243 "first line event after resumption was yield-1 line again "
244 "(lineno %d); expected yield-2 line (%d)"
245 % (first_gen_line[0], gen_lineno_yield2))
246
247
248 def test_star_in_slice():
249 class A:
250 def __getitem__(self, index):
251 return index
252 def __setitem__(self, index, value):
253 self.index = index
254 self.value = value
255 def __delitem__(self, index):
256 self.delindex = index
257 a = A()
258 assert a[1] == 1
259 assert a[*(1, 2, 3)] == (1, 2, 3)
260 a[*(1, 2, 3)] = 12
261 assert a.index == (1, 2, 3)
262 del a[*(1, 2, 8)]
263 assert a.delindex == (1, 2, 8)
264
265 def test_named_expr_in_fstring_annotation_forbidden():
266 # NamedExpr (walrus) inside an f-string format value inside an annotation
267 # must raise SyntaxError, not SystemError (regression: PyPy hit default_visitor).
268 with pytest.raises(SyntaxError):
269 exec("from __future__ import annotations\ntest: f'{(x := 10):=10}'\n")