Debian Codegraph @

pypy/interpreter/test/apptest_exceptions.py

raw symbols SCIP
1 import pytest
2
3 def _lineno_after_raise(f, *expected):
4 try:
5 f()
6 except Exception as ex:
7 t = ex.__traceback__
8 else:
9 assert False, "No exception raised"
10 lines = []
11 t = t.tb_next # skip _lineno_after_raise frame
12 while t:
13 frame = t.tb_frame
14 lines.append(
15 None if frame.f_lineno is None else
16 frame.f_lineno - frame.f_code.co_firstlineno
17 )
18 t = t.tb_next
19 assert tuple(lines) == expected
20
21 def test_lineno_in_named_except():
22 # PEP 626: traceback lineno should point at the re-raise inside except,
23 # not at the implicit cleanup code generated for "except X as name"
24 def in_named_except():
25 try:
26 1/0
27 except Exception as ex:
28 1/0
29 pass
30 _lineno_after_raise(in_named_except, 4)
31
32 def test_lineno_after_with():
33 # PEP 626: traceback lineno after a with block should point at the line
34 # after the with suite, not at the implicit __exit__ call
35 class Noop:
36 def __enter__(self):
37 return self
38 def __exit__(self, *args):
39 pass
40 def after_with():
41 with Noop():
42 1/0
43 pass
44 _lineno_after_raise(after_with, 2)
45
46 def test_lineno_reraise_through_finally():
47 # Exception propagating through a try/finally should report the lineno of
48 # the finally cleanup code (matching CPython), not the implicit RERAISE.
49 def func():
50 try:
51 raise ValueError("x")
52 finally:
53 pass
54 _lineno_after_raise(func, 4)
55
56 def test_yield_in_nested_try_excepts():
57 #Issue #25612
58 class MainError(Exception):
59 pass
60
61 class SubError(Exception):
62 pass
63
64 def main():
65 try:
66 raise MainError()
67 except MainError:
68 try:
69 yield
70 except SubError:
71 pass
72 raise
73
74 coro = main()
75 coro.send(None)
76 with pytest.raises(MainError):
77 coro.throw(SubError())
78
79 def test_generator_doesnt_retain_old_exc2():
80 # Issue bpo 28884#msg282532
81 # Fixed in CPython via https://github.com/python/cpython/pull/1773
82 import sys
83 def g():
84 try:
85 raise ValueError
86 except ValueError:
87 yield 1
88 assert sys.exc_info() == (None, None, None)
89 yield 2
90
91 gen = g()
92
93 try:
94 raise IndexError
95 except IndexError:
96 assert next(gen) == 1
97 assert next(gen) == 2
98
99 def test_raise_in_generator():
100 #Issue 25612#msg304117
101 def g():
102 yield 1
103 raise
104 yield 2
105
106 with pytest.raises(ZeroDivisionError):
107 i = g()
108 try:
109 1/0
110 except:
111 next(i)
112 next(i)
113
114 def test_with_break_exit_raises():
115 # sync with whose __exit__ raises, body exits via break.
116 # The exception from __exit__ should propagate; __exit__ must not be called twice.
117 called = []
118 class CM:
119 def __enter__(self): return self
120 def __exit__(self, *e):
121 called.append(1)
122 raise ValueError("exit raised")
123
124 def foo():
125 for i in range(2):
126 with CM():
127 break
128
129 try:
130 foo()
131 assert False, "expected ValueError"
132 except ValueError as e:
133 assert str(e) == "exit raised"
134 assert called == [1], "expected __exit__ called exactly once, got %r" % called
135
136 def test_with_try_except_reraise():
137 # 'with' block containing try/except that catches one exception and raises
138 # another -- __exit__ must receive the new exception, not an internal wrapper.
139 # Root cause: SETUP_WITH FinallyBlock survives into the with-exception handler;
140 # RERAISE inside the handler re-enters via old block-stack mode with
141 # SApplicationException instead of propagating out of the frame.
142 # Fixed by Phase 6 (SETUP_WITH stops pushing FinallyBlock).
143 class CM:
144 def __enter__(self): pass
145 def __exit__(self, *a): pass
146
147 try:
148 with CM():
149 try:
150 raise ImportError("original")
151 except ImportError as e:
152 raise ValueError(str(e))
153 except ValueError:
154 pass # expected: ValueError propagates through __exit__ correctly
155 # if TypeError raised instead, the bug is present (SApplicationException leaked)
156
157 def test_assertion_error_global_ignored():
158 if hasattr(pytest, 'py3k_skip'):
159 pytest.py3k_skip('only untranslated')
160 global AssertionError
161
162 class Foo(Exception):
163 pass
164 OrigAssertionError = AssertionError
165 AssertionError = Foo
166 try:
167 with pytest.raises(OrigAssertionError): # not Foo!
168 exec("assert 0") # to stop the pytest ast rewriting from touching it
169 finally:
170 AssertionError = OrigAssertionError
171
172
173 def test_sys_exc_info_restore_direct():
174 import sys
175 assert sys.exc_info() == (None, None, None)
176 try:
177 raise KeyError('foo')
178 except KeyError:
179 pass
180 assert sys.exc_info() == (None, None, None), sys.exc_info()
181
182 def test_sys_exc_info_restore_nested():
183 import sys
184 assert sys.exc_info() == (None, None, None)
185 def inner():
186 try:
187 raise KeyError('foo')
188 except KeyError:
189 pass
190 inner()
191 assert sys.exc_info() == (None, None, None), sys.exc_info()
192
193
194 def test_sys_exc_info_restore_class_body():
195 import sys
196 assert sys.exc_info() == (None, None, None)
197 class Foo:
198 try:
199 raise KeyError('foo')
200 except KeyError:
201 pass
202 assert sys.exc_info() == (None, None, None), sys.exc_info()
203
204 def test_sys_exc_info_restore_reraise_caught():
205 import sys
206 assert sys.exc_info() == (None, None, None)
207 def inner():
208 try:
209 raise ValueError('outer')
210 except ValueError:
211 try:
212 raise KeyError('inner')
213 except KeyError:
214 pass
215 inner()
216 assert sys.exc_info() == (None, None, None), sys.exc_info()
217
218 def test_sys_exc_info_finally_reraise():
219 import sys
220 assert sys.exc_info() == (None, None, None)
221 def inner():
222 try:
223 try:
224 raise KeyError('a')
225 finally:
226 pass
227 except KeyError:
228 pass
229 inner()
230 assert sys.exc_info() == (None, None, None), sys.exc_info()
231
232 def test_sys_exc_info_finally_nested():
233 import sys
234 assert sys.exc_info() == (None, None, None)
235 def inner():
236 try:
237 try:
238 raise KeyError('a')
239 except KeyError:
240 raise ValueError('b')
241 except ValueError:
242 pass
243 inner()
244 assert sys.exc_info() == (None, None, None), sys.exc_info()
245
246 def test_sys_exc_info_finally_nested_as_name():
247 import sys
248 assert sys.exc_info() == (None, None, None)
249 def inner():
250 try:
251 try:
252 raise KeyError('a')
253 except KeyError as k:
254 raise ValueError('b')
255 except ValueError:
256 pass
257 inner()
258 assert sys.exc_info() == (None, None, None), sys.exc_info()
259
260 def test_exception_trivial():
261 def f():
262 try:
263 raise Exception()
264 except Exception as e:
265 return 1
266 return 2
267 assert f() == 1
268
269
270 def test_exception_as_name():
271 def f():
272 try:
273 raise Exception(1)
274 except Exception as e:
275 return e.args[0]
276 assert f() == 1
277
278
279 def test_finally_return():
280 def f(a):
281 try:
282 if a:
283 raise Exception
284 a = -12
285 finally:
286 return a
287 assert f(0) == -12
288 assert f(1) == 1
289
290
291 def test_raise_non_exception():
292 try:
293 raise 1
294 except TypeError as e:
295 assert "exceptions must derive from BaseException" in str(e)
296 else:
297 assert False, "expected TypeError"
298
299
300 def test_nested_except_raise_stored():
301 # CPython 3.11 exception table for this pattern:
302 # try body -> outer_handler
303 # inner try body -> inner_handler
304 # inner handler check+STORE -> inner outer_cleanup
305 # inner handler body (incl RAISE_VARARGS) -> inner cleanup_end
306 # inner cleanup_end -> inner outer_cleanup
307 # outer handler check -> outer outer_cleanup
308 import dis
309 def f():
310 try:
311 z = 0
312 try:
313 "x" + 1
314 except TypeError as e:
315 z = 5
316 raise e
317 except TypeError:
318 return z
319 print()
320 dis.dis(f)
321 assert f() == 5
322
323
324 def test_except_zero_division():
325 def f(v):
326 z = 0
327 try:
328 z = 1 // v
329 except ZeroDivisionError as e:
330 z = "infinite result"
331 return z
332 assert f(2) == 0
333 assert f(0) == "infinite result"
334 try:
335 f('x')
336 except TypeError as e:
337 assert "unsupported operand type" in str(e)
338 else:
339 assert False, "expected TypeError"
340
341
342 def test_try_finally_break():
343 def f(n):
344 total = 0
345 for i in range(n):
346 try:
347 if i == 4:
348 break
349 finally:
350 total += i
351 return total
352 assert f(4) == 1+2+3
353 assert f(9) == 1+2+3+4
354
355
356 def test_try_finally_continue():
357 def f(n):
358 total = 0
359 for i in range(n):
360 try:
361 if i == 4:
362 continue
363 finally:
364 total += 100
365 total += i
366 return total
367 assert f(4) == 1+2+3+400
368 assert f(9) == 1+2+3 + 5+6+7+8+900
369
370
371 def test_try_except_finally_nested():
372 import dis
373 def run():
374 x = 5
375 try:
376 try:
377 if x > 2:
378 raise ValueError
379 finally:
380 x += 1
381 except ValueError:
382 x *= 7
383 return x
384 print()
385 dis.dis(run)
386 assert run() == 42
387
388
389 def test_sys_exc_info_with_propagates():
390 # Regression: a with-statement whose __exit__ returns falsy must not
391 # leak sys.exc_info when the body raises and the outer frame catches.
392 # The exception-table entry for the with-cleanup block must cover the
393 # RERAISE 2 instruction so the outer_cleanup (COPY 3; POP_EXCEPT;
394 # RERAISE 1) runs and restores sys.exc_info before re-raising.
395 import sys
396 assert sys.exc_info() == (None, None, None)
397 class CM:
398 def __enter__(self):
399 return self
400 def __exit__(self, *args):
401 return False # propagate
402 def inner():
403 try:
404 with CM():
405 raise ImportError("boom")
406 except ImportError:
407 pass
408 inner()
409 assert sys.exc_info() == (None, None, None), sys.exc_info()