Debian Codegraph @

lib-python/3/test/test_sys_settrace.py

raw symbols SCIP
1 # Testing the line trace facility.
2
3 from test import support
4 import unittest
5 from unittest.mock import MagicMock
6 import sys
7 import difflib
8 import gc
9 from functools import wraps
10 import asyncio
11 from test.support import import_helper
12
13 support.requires_working_socket(module=True)
14
15 class tracecontext:
16 """Context manager that traces its enter and exit."""
17 def __init__(self, output, value):
18 self.output = output
19 self.value = value
20
21 def __enter__(self):
22 self.output.append(self.value)
23
24 def __exit__(self, *exc_info):
25 self.output.append(-self.value)
26
27 class asynctracecontext:
28 """Asynchronous context manager that traces its aenter and aexit."""
29 def __init__(self, output, value):
30 self.output = output
31 self.value = value
32
33 async def __aenter__(self):
34 self.output.append(self.value)
35
36 async def __aexit__(self, *exc_info):
37 self.output.append(-self.value)
38
39 async def asynciter(iterable):
40 """Convert an iterable to an asynchronous iterator."""
41 for x in iterable:
42 yield x
43
44 def clean_asynciter(test):
45 @wraps(test)
46 async def wrapper(*args, **kwargs):
47 cleanups = []
48 def wrapped_asynciter(iterable):
49 it = asynciter(iterable)
50 cleanups.append(it.aclose)
51 return it
52 try:
53 return await test(*args, **kwargs, asynciter=wrapped_asynciter)
54 finally:
55 while cleanups:
56 await cleanups.pop()()
57 return wrapper
58
59 # A very basic example. If this fails, we're in deep trouble.
60 def basic():
61 return 1
62
63 basic.events = [(0, 'call'),
64 (1, 'line'),
65 (1, 'return')]
66
67 # Many of the tests below are tricky because they involve pass statements.
68 # If there is implicit control flow around a pass statement (in an except
69 # clause or else clause) under what conditions do you set a line number
70 # following that clause?
71
72
73 # Some constructs like "while 0:", "if 0:" or "if 1:...else:..." could be optimized
74 # away. Make sure that those lines aren't skipped.
75 def arigo_example0():
76 x = 1
77 del x
78 while 0:
79 pass
80 x = 1
81
82 arigo_example0.events = [(0, 'call'),
83 (1, 'line'),
84 (2, 'line'),
85 (3, 'line'),
86 (5, 'line'),
87 (5, 'return')]
88
89 def arigo_example1():
90 x = 1
91 del x
92 if 0:
93 pass
94 x = 1
95
96 arigo_example1.events = [(0, 'call'),
97 (1, 'line'),
98 (2, 'line'),
99 (3, 'line'),
100 (5, 'line'),
101 (5, 'return')]
102
103 def arigo_example2():
104 x = 1
105 del x
106 if 1:
107 x = 1
108 else:
109 pass
110 return None
111
112 arigo_example2.events = [(0, 'call'),
113 (1, 'line'),
114 (2, 'line'),
115 (3, 'line'),
116 (4, 'line'),
117 (7, 'line'),
118 (7, 'return')]
119
120
121 # check that lines consisting of just one instruction get traced:
122 def one_instr_line():
123 x = 1
124 del x
125 x = 1
126
127 one_instr_line.events = [(0, 'call'),
128 (1, 'line'),
129 (2, 'line'),
130 (3, 'line'),
131 (3, 'return')]
132
133 def no_pop_tops(): # 0
134 x = 1 # 1
135 for a in range(2): # 2
136 if a: # 3
137 x = 1 # 4
138 else: # 5
139 x = 1 # 6
140
141 no_pop_tops.events = [(0, 'call'),
142 (1, 'line'),
143 (2, 'line'),
144 (3, 'line'),
145 (6, 'line'),
146 (2, 'line'),
147 (3, 'line'),
148 (4, 'line'),
149 (2, 'line'),
150 (2, 'return')]
151
152 def no_pop_blocks():
153 y = 1
154 while not y:
155 bla
156 x = 1
157
158 no_pop_blocks.events = [(0, 'call'),
159 (1, 'line'),
160 (2, 'line'),
161 (4, 'line'),
162 (4, 'return')]
163
164 def called(): # line -3
165 x = 1
166
167 def call(): # line 0
168 called()
169
170 call.events = [(0, 'call'),
171 (1, 'line'),
172 (-3, 'call'),
173 (-2, 'line'),
174 (-2, 'return'),
175 (1, 'return')]
176
177 def raises():
178 raise Exception
179
180 def test_raise():
181 try:
182 raises()
183 except Exception:
184 pass
185
186 test_raise.events = [(0, 'call'),
187 (1, 'line'),
188 (2, 'line'),
189 (-3, 'call'),
190 (-2, 'line'),
191 (-2, 'exception'),
192 (-2, 'return'),
193 (2, 'exception'),
194 (3, 'line'),
195 (4, 'line'),
196 (4, 'return')]
197
198 def _settrace_and_return(tracefunc):
199 sys.settrace(tracefunc)
200 sys._getframe().f_back.f_trace = tracefunc
201 def settrace_and_return(tracefunc):
202 _settrace_and_return(tracefunc)
203
204 settrace_and_return.events = [(1, 'return')]
205
206 def _settrace_and_raise(tracefunc):
207 sys.settrace(tracefunc)
208 sys._getframe().f_back.f_trace = tracefunc
209 raise RuntimeError
210 def settrace_and_raise(tracefunc):
211 try:
212 _settrace_and_raise(tracefunc)
213 except RuntimeError:
214 pass
215
216 settrace_and_raise.events = [(2, 'exception'),
217 (3, 'line'),
218 (4, 'line'),
219 (4, 'return')]
220
221 # implicit return example
222 # This test is interesting because of the else: pass
223 # part of the code. The code generate for the true
224 # part of the if contains a jump past the else branch.
225 # The compiler then generates an implicit "return None"
226 # Internally, the compiler visits the pass statement
227 # and stores its line number for use on the next instruction.
228 # The next instruction is the implicit return None.
229 def ireturn_example():
230 a = 5
231 b = 5
232 if a == b:
233 b = a+1
234 else:
235 pass
236
237 ireturn_example.events = [(0, 'call'),
238 (1, 'line'),
239 (2, 'line'),
240 (3, 'line'),
241 (4, 'line'),
242 (4, 'return')]
243
244 # Tight loop with while(1) example (SF #765624)
245 def tightloop_example():
246 items = range(0, 3)
247 try:
248 i = 0
249 while 1:
250 b = items[i]; i+=1
251 except IndexError:
252 pass
253
254 tightloop_example.events = [(0, 'call'),
255 (1, 'line'),
256 (2, 'line'),
257 (3, 'line'),
258 (4, 'line'),
259 (5, 'line'),
260 (4, 'line'),
261 (5, 'line'),
262 (4, 'line'),
263 (5, 'line'),
264 (4, 'line'),
265 (5, 'line'),
266 (5, 'exception'),
267 (6, 'line'),
268 (7, 'line'),
269 (7, 'return')]
270
271 def tighterloop_example():
272 items = range(1, 4)
273 try:
274 i = 0
275 while 1: i = items[i]
276 except IndexError:
277 pass
278
279 tighterloop_example.events = [(0, 'call'),
280 (1, 'line'),
281 (2, 'line'),
282 (3, 'line'),
283 (4, 'line'),
284 (4, 'line'),
285 (4, 'line'),
286 (4, 'line'),
287 (4, 'exception'),
288 (5, 'line'),
289 (6, 'line'),
290 (6, 'return')]
291
292 def generator_function():
293 try:
294 yield True
295 "continued"
296 finally:
297 "finally"
298 def generator_example():
299 # any() will leave the generator before its end
300 x = any(generator_function()); gc.collect()
301
302 # the following lines were not traced
303 for x in range(10):
304 y = x
305
306 # On CPython, when the generator is decref'ed to zero, we see the trace
307 # for the "finally:" portion. On PyPy, we don't see it before the next
308 # garbage collection. That's why we put gc.collect() on the same line
309 # above.
310
311 generator_example.events = ([(0, 'call'),
312 (2, 'line'),
313 (-6, 'call'),
314 (-5, 'line'),
315 (-4, 'line'),
316 (-4, 'return'),
317 (-4, 'call'),
318 (-4, 'exception'),
319 (-1, 'line'),
320 (-1, 'return')] +
321 [(5, 'line'), (6, 'line')] * 10 +
322 [(5, 'line'), (5, 'return')])
323
324
325 class Tracer:
326 def __init__(self, trace_line_events=None, trace_opcode_events=None):
327 self.trace_line_events = trace_line_events
328 self.trace_opcode_events = trace_opcode_events
329 self.events = []
330
331 def _reconfigure_frame(self, frame):
332 if self.trace_line_events is not None:
333 frame.f_trace_lines = self.trace_line_events
334 if self.trace_opcode_events is not None:
335 frame.f_trace_opcodes = self.trace_opcode_events
336
337 def trace(self, frame, event, arg):
338 self._reconfigure_frame(frame)
339 self.events.append((frame.f_lineno, event))
340 return self.trace
341
342 def traceWithGenexp(self, frame, event, arg):
343 self._reconfigure_frame(frame)
344 (o for o in [1])
345 self.events.append((frame.f_lineno, event))
346 return self.trace
347
348
349 class TraceTestCase(unittest.TestCase):
350
351 # Disable gc collection when tracing, otherwise the
352 # deallocators may be traced as well.
353 def setUp(self):
354 self.using_gc = gc.isenabled()
355 gc.disable()
356 self.addCleanup(sys.settrace, sys.gettrace())
357
358 def tearDown(self):
359 if self.using_gc:
360 gc.enable()
361
362 @staticmethod
363 def make_tracer():
364 """Helper to allow test subclasses to configure tracers differently"""
365 return Tracer()
366
367 def compare_events(self, line_offset, events, expected_events):
368 events = [(l - line_offset, e) for (l, e) in events]
369 if events != expected_events:
370 self.fail(
371 "events did not match expectation:\n" +
372 "\n".join(difflib.ndiff([str(x) for x in expected_events],
373 [str(x) for x in events])))
374
375 def run_and_compare(self, func, events):
376 tracer = self.make_tracer()
377 sys.settrace(tracer.trace)
378 func()
379 sys.settrace(None)
380 self.compare_events(func.__code__.co_firstlineno,
381 tracer.events, events)
382
383 def run_test(self, func):
384 self.run_and_compare(func, func.events)
385
386 def run_test2(self, func):
387 tracer = self.make_tracer()
388 func(tracer.trace)
389 sys.settrace(None)
390 self.compare_events(func.__code__.co_firstlineno,
391 tracer.events, func.events)
392
393 def test_set_and_retrieve_none(self):
394 sys.settrace(None)
395 assert sys.gettrace() is None
396
397 def test_set_and_retrieve_func(self):
398 def fn(*args):
399 pass
400
401 sys.settrace(fn)
402 try:
403 assert sys.gettrace() is fn
404 finally:
405 sys.settrace(None)
406
407 def test_01_basic(self):
408 self.run_test(basic)
409 def test_02_arigo0(self):
410 self.run_test(arigo_example0)
411 def test_02_arigo1(self):
412 self.run_test(arigo_example1)
413 def test_02_arigo2(self):
414 self.run_test(arigo_example2)
415 def test_03_one_instr(self):
416 self.run_test(one_instr_line)
417 def test_04_no_pop_blocks(self):
418 self.run_test(no_pop_blocks)
419 def test_05_no_pop_tops(self):
420 self.run_test(no_pop_tops)
421 def test_06_call(self):
422 self.run_test(call)
423 def test_07_raise(self):
424 self.run_test(test_raise)
425
426 def test_08_settrace_and_return(self):
427 self.run_test2(settrace_and_return)
428 def test_09_settrace_and_raise(self):
429 self.run_test2(settrace_and_raise)
430 def test_10_ireturn(self):
431 self.run_test(ireturn_example)
432 def test_11_tightloop(self):
433 self.run_test(tightloop_example)
434 def test_12_tighterloop(self):
435 self.run_test(tighterloop_example)
436
437 def test_13_genexp(self):
438 if self.using_gc:
439 gc.enable()
440 support.gc_collect()
441 try:
442 self.run_test(generator_example)
443 # issue1265: if the trace function contains a generator,
444 # and if the traced function contains another generator
445 # that is not completely exhausted, the trace stopped.
446 # Worse: the 'finally' clause was not invoked.
447 tracer = self.make_tracer()
448 sys.settrace(tracer.traceWithGenexp)
449 generator_example()
450 sys.settrace(None)
451 self.compare_events(generator_example.__code__.co_firstlineno,
452 tracer.events, generator_example.events)
453 finally:
454 if self.using_gc:
455 gc.disable()
456
457 def test_14_onliner_if(self):
458 def onliners():
459 if True: x=False
460 else: x=True
461 return 0
462 self.run_and_compare(
463 onliners,
464 [(0, 'call'),
465 (1, 'line'),
466 (3, 'line'),
467 (3, 'return')])
468
469 def test_15_loops(self):
470 # issue1750076: "while" expression is skipped by debugger
471 def for_example():
472 for x in range(2):
473 pass
474 self.run_and_compare(
475 for_example,
476 [(0, 'call'),
477 (1, 'line'),
478 (2, 'line'),
479 (1, 'line'),
480 (2, 'line'),
481 (1, 'line'),
482 (1, 'return')])
483
484 def while_example():
485 # While expression should be traced on every loop
486 x = 2
487 while x > 0:
488 x -= 1
489 self.run_and_compare(
490 while_example,
491 [(0, 'call'),
492 (2, 'line'),
493 (3, 'line'),
494 (4, 'line'),
495 (3, 'line'),
496 (4, 'line'),
497 (3, 'line'),
498 (3, 'return')])
499
500 def test_16_blank_lines(self):
501 namespace = {}
502 exec("def f():\n" + "\n" * 256 + " pass", namespace)
503 self.run_and_compare(
504 namespace["f"],
505 [(0, 'call'),
506 (257, 'line'),
507 (257, 'return')])
508
509 def test_17_none_f_trace(self):
510 # Issue 20041: fix TypeError when f_trace is set to None.
511 def func():
512 sys._getframe().f_trace = None
513 lineno = 2
514 self.run_and_compare(func,
515 [(0, 'call'),
516 (1, 'line')])
517
518 def test_18_except_with_name(self):
519 def func():
520 try:
521 try:
522 raise Exception
523 except Exception as e:
524 raise
525 x = "Something"
526 y = "Something"
527 except Exception:
528 pass
529
530 self.run_and_compare(func,
531 [(0, 'call'),
532 (1, 'line'),
533 (2, 'line'),
534 (3, 'line'),
535 (3, 'exception'),
536 (4, 'line'),
537 (5, 'line'),
538 (8, 'line'),
539 (9, 'line'),
540 (9, 'return')])
541
542 def test_19_except_with_finally(self):
543 def func():
544 try:
545 try:
546 raise Exception
547 finally:
548 y = "Something"
549 except Exception:
550 b = 23
551
552 self.run_and_compare(func,
553 [(0, 'call'),
554 (1, 'line'),
555 (2, 'line'),
556 (3, 'line'),
557 (3, 'exception'),
558 (5, 'line'),
559 (6, 'line'),
560 (7, 'line'),
561 (7, 'return')])
562
563 def test_20_async_for_loop(self):
564 class AsyncIteratorWrapper:
565 def __init__(self, obj):
566 self._it = iter(obj)
567
568 def __aiter__(self):
569 return self
570
571 async def __anext__(self):
572 try:
573 return next(self._it)
574 except StopIteration:
575 raise StopAsyncIteration
576
577 async def doit_async():
578 async for letter in AsyncIteratorWrapper("abc"):
579 x = letter
580 y = 42
581
582 def run(tracer):
583 x = doit_async()
584 try:
585 sys.settrace(tracer)
586 x.send(None)
587 finally:
588 sys.settrace(None)
589
590 tracer = self.make_tracer()
591 events = [
592 (0, 'call'),
593 (1, 'line'),
594 (-12, 'call'),
595 (-11, 'line'),
596 (-11, 'return'),
597 (-9, 'call'),
598 (-8, 'line'),
599 (-8, 'return'),
600 (-6, 'call'),
601 (-5, 'line'),
602 (-4, 'line'),
603 (-4, 'return'),
604 (1, 'exception'),
605 (2, 'line'),
606 (1, 'line'),
607 (-6, 'call'),
608 (-5, 'line'),
609 (-4, 'line'),
610 (-4, 'return'),
611 (1, 'exception'),
612 (2, 'line'),
613 (1, 'line'),
614 (-6, 'call'),
615 (-5, 'line'),
616 (-4, 'line'),
617 (-4, 'return'),
618 (1, 'exception'),
619 (2, 'line'),
620 (1, 'line'),
621 (-6, 'call'),
622 (-5, 'line'),
623 (-4, 'line'),
624 (-4, 'exception'),
625 (-3, 'line'),
626 (-2, 'line'),
627 (-2, 'exception'),
628 (-2, 'return'),
629 (1, 'exception'),
630 (3, 'line'),
631 (3, 'return')]
632 try:
633 run(tracer.trace)
634 except Exception:
635 pass
636 self.compare_events(doit_async.__code__.co_firstlineno,
637 tracer.events, events)
638
639 def test_async_for_backwards_jump_has_no_line(self):
640 async def arange(n):
641 for i in range(n):
642 yield i
643 async def f():
644 async for i in arange(3):
645 if i > 100:
646 break # should never be traced
647
648 tracer = self.make_tracer()
649 coro = f()
650 try:
651 sys.settrace(tracer.trace)
652 coro.send(None)
653 except Exception:
654 pass
655 finally:
656 sys.settrace(None)
657
658 events = [
659 (0, 'call'),
660 (1, 'line'),
661 (-3, 'call'),
662 (-2, 'line'),
663 (-1, 'line'),
664 (-1, 'return'),
665 (1, 'exception'),
666 (2, 'line'),
667 (1, 'line'),
668 (-1, 'call'),
669 (-2, 'line'),
670 (-1, 'line'),
671 (-1, 'return'),
672 (1, 'exception'),
673 (2, 'line'),
674 (1, 'line'),
675 (-1, 'call'),
676 (-2, 'line'),
677 (-1, 'line'),
678 (-1, 'return'),
679 (1, 'exception'),
680 (2, 'line'),
681 (1, 'line'),
682 (-1, 'call'),
683 (-2, 'line'),
684 (-2, 'return'),
685 (1, 'exception'),
686 (1, 'return'),
687 ]
688 self.compare_events(f.__code__.co_firstlineno,
689 tracer.events, events)
690
691 def test_21_repeated_pass(self):
692 def func():
693 pass
694 pass
695
696 self.run_and_compare(func,
697 [(0, 'call'),
698 (1, 'line'),
699 (2, 'line'),
700 (2, 'return')])
701
702 def test_loop_in_try_except(self):
703 # https://bugs.python.org/issue41670
704
705 def func():
706 try:
707 for i in []: pass
708 return 1
709 except:
710 return 2
711
712 self.run_and_compare(func,
713 [(0, 'call'),
714 (1, 'line'),
715 (2, 'line'),
716 (3, 'line'),
717 (3, 'return')])
718
719 def test_try_except_no_exception(self):
720
721 def func():
722 try:
723 2
724 except:
725 4
726 else:
727 6
728 if False:
729 8
730 else:
731 10
732 if func.__name__ == 'Fred':
733 12
734 finally:
735 14
736
737 self.run_and_compare(func,
738 [(0, 'call'),
739 (1, 'line'),
740 (2, 'line'),
741 (6, 'line'),
742 (7, 'line'),
743 (10, 'line'),
744 (11, 'line'),
745 (14, 'line'),
746 (14, 'return')])
747
748 def test_try_exception_in_else(self):
749
750 def func():
751 try:
752 try:
753 3
754 except:
755 5
756 else:
757 7
758 raise Exception
759 finally:
760 10
761 except:
762 12
763 finally:
764 14
765
766 self.run_and_compare(func,
767 [(0, 'call'),
768 (1, 'line'),
769 (2, 'line'),
770 (3, 'line'),
771 (7, 'line'),
772 (8, 'line'),
773 (8, 'exception'),
774 (10, 'line'),
775 (11, 'line'),
776 (12, 'line'),
777 (14, 'line'),
778 (14, 'return')])
779
780 def test_nested_loops(self):
781
782 def func():
783 for i in range(2):
784 for j in range(2):
785 a = i + j
786 return a == 1
787
788 self.run_and_compare(func,
789 [(0, 'call'),
790 (1, 'line'),
791 (2, 'line'),
792 (3, 'line'),
793 (2, 'line'),
794 (3, 'line'),
795 (2, 'line'),
796 (1, 'line'),
797 (2, 'line'),
798 (3, 'line'),
799 (2, 'line'),
800 (3, 'line'),
801 (2, 'line'),
802 (1, 'line'),
803 (4, 'line'),
804 (4, 'return')])
805
806 def test_if_break(self):
807
808 def func():
809 seq = [1, 0]
810 while seq:
811 n = seq.pop()
812 if n:
813 break # line 5
814 else:
815 n = 99
816 return n # line 8
817
818 self.run_and_compare(func,
819 [(0, 'call'),
820 (1, 'line'),
821 (2, 'line'),
822 (3, 'line'),
823 (4, 'line'),
824 (2, 'line'),
825 (3, 'line'),
826 (4, 'line'),
827 (5, 'line'),
828 (8, 'line'),
829 (8, 'return')])
830
831 def test_break_through_finally(self):
832
833 def func():
834 a, c, d, i = 1, 1, 1, 99
835 try:
836 for i in range(3):
837 try:
838 a = 5
839 if i > 0:
840 break # line 7
841 a = 8
842 finally:
843 c = 10
844 except:
845 d = 12 # line 12
846 assert a == 5 and c == 10 and d == 1 # line 13
847
848 self.run_and_compare(func,
849 [(0, 'call'),
850 (1, 'line'),
851 (2, 'line'),
852 (3, 'line'),
853 (4, 'line'),
854 (5, 'line'),
855 (6, 'line'),
856 (8, 'line'),
857 (10, 'line'),
858 (3, 'line'),
859 (4, 'line'),
860 (5, 'line'),
861 (6, 'line'),
862 (7, 'line'),
863 (10, 'line'),
864 (13, 'line'),
865 (13, 'return')])
866
867 def test_continue_through_finally(self):
868
869 def func():
870 a, b, c, d, i = 1, 1, 1, 1, 99
871 try:
872 for i in range(2):
873 try:
874 a = 5
875 if i > 0:
876 continue # line 7
877 b = 8
878 finally:
879 c = 10
880 except:
881 d = 12 # line 12
882 assert (a, b, c, d) == (5, 8, 10, 1) # line 13
883
884 self.run_and_compare(func,
885 [(0, 'call'),
886 (1, 'line'),
887 (2, 'line'),
888 (3, 'line'),
889 (4, 'line'),
890 (5, 'line'),
891 (6, 'line'),
892 (8, 'line'),
893 (10, 'line'),
894 (3, 'line'),
895 (4, 'line'),
896 (5, 'line'),
897 (6, 'line'),
898 (7, 'line'),
899 (10, 'line'),
900 (3, 'line'),
901 (13, 'line'),
902 (13, 'return')])
903
904 def test_return_through_finally(self):
905
906 def func():
907 try:
908 return 2
909 finally:
910 4
911
912 self.run_and_compare(func,
913 [(0, 'call'),
914 (1, 'line'),
915 (2, 'line'),
916 (4, 'line'),
917 (4, 'return')])
918
919 def test_try_except_with_wrong_type(self):
920
921 def func():
922 try:
923 2/0
924 except IndexError:
925 4
926 finally:
927 return 6
928
929 self.run_and_compare(func,
930 [(0, 'call'),
931 (1, 'line'),
932 (2, 'line'),
933 (2, 'exception'),
934 (3, 'line'),
935 (6, 'line'),
936 (6, 'return')])
937
938 def test_break_to_continue1(self):
939
940 def func():
941 TRUE = 1
942 x = [1]
943 while x:
944 x.pop()
945 while TRUE:
946 break
947 continue
948
949 self.run_and_compare(func,
950 [(0, 'call'),
951 (1, 'line'),
952 (2, 'line'),
953 (3, 'line'),
954 (4, 'line'),
955 (5, 'line'),
956 (6, 'line'),
957 (7, 'line'),
958 (3, 'line'),
959 (3, 'return')])
960
961 def test_break_to_continue2(self):
962
963 def func():
964 TRUE = 1
965 x = [1]
966 while x:
967 x.pop()
968 while TRUE:
969 break
970 else:
971 continue
972
973 self.run_and_compare(func,
974 [(0, 'call'),
975 (1, 'line'),
976 (2, 'line'),
977 (3, 'line'),
978 (4, 'line'),
979 (5, 'line'),
980 (6, 'line'),
981 (3, 'line'),
982 (3, 'return')])
983
984 def test_break_to_break(self):
985
986 def func():
987 TRUE = 1
988 while TRUE:
989 while TRUE:
990 break
991 break
992
993 self.run_and_compare(func,
994 [(0, 'call'),
995 (1, 'line'),
996 (2, 'line'),
997 (3, 'line'),
998 (4, 'line'),
999 (5, 'line'),
1000 (5, 'return')])
1001
1002 def test_nested_ifs(self):
1003
1004 def func():
1005 a = b = 1
1006 if a == 1:
1007 if b == 1:
1008 x = 4
1009 else:
1010 y = 6
1011 else:
1012 z = 8
1013
1014 self.run_and_compare(func,
1015 [(0, 'call'),
1016 (1, 'line'),
1017 (2, 'line'),
1018 (3, 'line'),
1019 (4, 'line'),
1020 (4, 'return')])
1021
1022 def test_nested_ifs_with_and(self):
1023
1024 def func():
1025 if A:
1026 if B:
1027 if C:
1028 if D:
1029 return False
1030 else:
1031 return False
1032 elif E and F:
1033 return True
1034
1035 A = B = True
1036 C = False
1037
1038 self.run_and_compare(func,
1039 [(0, 'call'),
1040 (1, 'line'),
1041 (2, 'line'),
1042 (3, 'line'),
1043 (3, 'return')])
1044
1045 def test_nested_try_if(self):
1046
1047 def func():
1048 x = "hello"
1049 try:
1050 3/0
1051 except ZeroDivisionError:
1052 if x == 'raise':
1053 raise ValueError() # line 6
1054 f = 7
1055
1056 self.run_and_compare(func,
1057 [(0, 'call'),
1058 (1, 'line'),
1059 (2, 'line'),
1060 (3, 'line'),
1061 (3, 'exception'),
1062 (4, 'line'),
1063 (5, 'line'),
1064 (7, 'line'),
1065 (7, 'return')])
1066
1067 def test_if_false_in_with(self):
1068
1069 class C:
1070 def __enter__(self):
1071 return self
1072 def __exit__(*args):
1073 pass
1074
1075 def func():
1076 with C():
1077 if False:
1078 pass
1079
1080 self.run_and_compare(func,
1081 [(0, 'call'),
1082 (1, 'line'),
1083 (-5, 'call'),
1084 (-4, 'line'),
1085 (-4, 'return'),
1086 (2, 'line'),
1087 (1, 'line'),
1088 (-3, 'call'),
1089 (-2, 'line'),
1090 (-2, 'return'),
1091 (1, 'return')])
1092
1093 def test_if_false_in_try_except(self):
1094
1095 def func():
1096 try:
1097 if False:
1098 pass
1099 except Exception:
1100 X
1101
1102 self.run_and_compare(func,
1103 [(0, 'call'),
1104 (1, 'line'),
1105 (2, 'line'),
1106 (2, 'return')])
1107
1108 def test_implicit_return_in_class(self):
1109
1110 def func():
1111 class A:
1112 if 3 < 9:
1113 a = 1
1114 else:
1115 a = 2
1116
1117 self.run_and_compare(func,
1118 [(0, 'call'),
1119 (1, 'line'),
1120 (1, 'call'),
1121 (1, 'line'),
1122 (2, 'line'),
1123 (3, 'line'),
1124 (3, 'return'),
1125 (1, 'return')])
1126
1127 def test_try_in_try(self):
1128 def func():
1129 try:
1130 try:
1131 pass
1132 except Exception as ex:
1133 pass
1134 except Exception:
1135 pass
1136
1137 self.run_and_compare(func,
1138 [(0, 'call'),
1139 (1, 'line'),
1140 (2, 'line'),
1141 (3, 'line'),
1142 (3, 'return')])
1143
1144 def test_try_in_try_with_exception(self):
1145
1146 def func():
1147 try:
1148 try:
1149 raise TypeError
1150 except ValueError as ex:
1151 5
1152 except TypeError:
1153 7
1154
1155 self.run_and_compare(func,
1156 [(0, 'call'),
1157 (1, 'line'),
1158 (2, 'line'),
1159 (3, 'line'),
1160 (3, 'exception'),
1161 (4, 'line'),
1162 (6, 'line'),
1163 (7, 'line'),
1164 (7, 'return')])
1165
1166 def func():
1167 try:
1168 try:
1169 raise ValueError
1170 except ValueError as ex:
1171 5
1172 except TypeError:
1173 7
1174
1175 self.run_and_compare(func,
1176 [(0, 'call'),
1177 (1, 'line'),
1178 (2, 'line'),
1179 (3, 'line'),
1180 (3, 'exception'),
1181 (4, 'line'),
1182 (5, 'line'),
1183 (5, 'return')])
1184
1185 def test_if_in_if_in_if(self):
1186 def func(a=0, p=1, z=1):
1187 if p:
1188 if a:
1189 if z:
1190 pass
1191 else:
1192 pass
1193 else:
1194 pass
1195
1196 self.run_and_compare(func,
1197 [(0, 'call'),
1198 (1, 'line'),
1199 (2, 'line'),
1200 (2, 'return')])
1201
1202 def test_early_exit_with(self):
1203
1204 class C:
1205 def __enter__(self):
1206 return self
1207 def __exit__(*args):
1208 pass
1209
1210 def func_break():
1211 for i in (1,2):
1212 with C():
1213 break
1214 pass
1215
1216 def func_return():
1217 with C():
1218 return
1219
1220 self.run_and_compare(func_break,
1221 [(0, 'call'),
1222 (1, 'line'),
1223 (2, 'line'),
1224 (-5, 'call'),
1225 (-4, 'line'),
1226 (-4, 'return'),
1227 (3, 'line'),
1228 (2, 'line'),
1229 (-3, 'call'),
1230 (-2, 'line'),
1231 (-2, 'return'),
1232 (4, 'line'),
1233 (4, 'return')])
1234
1235 self.run_and_compare(func_return,
1236 [(0, 'call'),
1237 (1, 'line'),
1238 (-11, 'call'),
1239 (-10, 'line'),
1240 (-10, 'return'),
1241 (2, 'line'),
1242 (1, 'line'),
1243 (-9, 'call'),
1244 (-8, 'line'),
1245 (-8, 'return'),
1246 (1, 'return')])
1247
1248 def test_flow_converges_on_same_line(self):
1249
1250 def foo(x):
1251 if x:
1252 try:
1253 1/(x - 1)
1254 except ZeroDivisionError:
1255 pass
1256 return x
1257
1258 def func():
1259 for i in range(2):
1260 foo(i)
1261
1262 self.run_and_compare(func,
1263 [(0, 'call'),
1264 (1, 'line'),
1265 (2, 'line'),
1266 (-8, 'call'),
1267 (-7, 'line'),
1268 (-2, 'line'),
1269 (-2, 'return'),
1270 (1, 'line'),
1271 (2, 'line'),
1272 (-8, 'call'),
1273 (-7, 'line'),
1274 (-6, 'line'),
1275 (-5, 'line'),
1276 (-5, 'exception'),
1277 (-4, 'line'),
1278 (-3, 'line'),
1279 (-2, 'line'),
1280 (-2, 'return'),
1281 (1, 'line'),
1282 (1, 'return')])
1283
1284 def test_no_tracing_of_named_except_cleanup(self):
1285
1286 def func():
1287 x = 0
1288 try:
1289 1/x
1290 except ZeroDivisionError as error:
1291 if x:
1292 raise
1293 return "done"
1294
1295 self.run_and_compare(func,
1296 [(0, 'call'),
1297 (1, 'line'),
1298 (2, 'line'),
1299 (3, 'line'),
1300 (3, 'exception'),
1301 (4, 'line'),
1302 (5, 'line'),
1303 (7, 'line'),
1304 (7, 'return')])
1305
1306 def test_tracing_exception_raised_in_with(self):
1307
1308 class NullCtx:
1309 def __enter__(self):
1310 return self
1311 def __exit__(self, *excinfo):
1312 pass
1313
1314 def func():
1315 try:
1316 with NullCtx():
1317 1/0
1318 except ZeroDivisionError:
1319 pass
1320
1321 self.run_and_compare(func,
1322 [(0, 'call'),
1323 (1, 'line'),
1324 (2, 'line'),
1325 (-5, 'call'),
1326 (-4, 'line'),
1327 (-4, 'return'),
1328 (3, 'line'),
1329 (3, 'exception'),
1330 (2, 'line'),
1331 (-3, 'call'),
1332 (-2, 'line'),
1333 (-2, 'return'),
1334 (4, 'line'),
1335 (5, 'line'),
1336 (5, 'return')])
1337
1338 def test_try_except_star_no_exception(self):
1339
1340 def func():
1341 try:
1342 2
1343 except* Exception:
1344 4
1345 else:
1346 6
1347 if False:
1348 8
1349 else:
1350 10
1351 if func.__name__ == 'Fred':
1352 12
1353 finally:
1354 14
1355
1356 self.run_and_compare(func,
1357 [(0, 'call'),
1358 (1, 'line'),
1359 (2, 'line'),
1360 (6, 'line'),
1361 (7, 'line'),
1362 (10, 'line'),
1363 (11, 'line'),
1364 (14, 'line'),
1365 (14, 'return')])
1366
1367 def test_try_except_star_named_no_exception(self):
1368
1369 def func():
1370 try:
1371 2
1372 except* Exception as e:
1373 4
1374 else:
1375 6
1376 finally:
1377 8
1378
1379 self.run_and_compare(func,
1380 [(0, 'call'),
1381 (1, 'line'),
1382 (2, 'line'),
1383 (6, 'line'),
1384 (8, 'line'),
1385 (8, 'return')])
1386
1387 def test_try_except_star_exception_caught(self):
1388
1389 def func():
1390 try:
1391 raise ValueError(2)
1392 except* ValueError:
1393 4
1394 else:
1395 6
1396 finally:
1397 8
1398
1399 self.run_and_compare(func,
1400 [(0, 'call'),
1401 (1, 'line'),
1402 (2, 'line'),
1403 (2, 'exception'),
1404 (3, 'line'),
1405 (4, 'line'),
1406 (8, 'line'),
1407 (8, 'return')])
1408
1409 def test_try_except_star_named_exception_caught(self):
1410
1411 def func():
1412 try:
1413 raise ValueError(2)
1414 except* ValueError as e:
1415 4
1416 else:
1417 6
1418 finally:
1419 8
1420
1421 self.run_and_compare(func,
1422 [(0, 'call'),
1423 (1, 'line'),
1424 (2, 'line'),
1425 (2, 'exception'),
1426 (3, 'line'),
1427 (4, 'line'),
1428 (8, 'line'),
1429 (8, 'return')])
1430
1431 def test_try_except_star_exception_not_caught(self):
1432
1433 def func():
1434 try:
1435 try:
1436 raise ValueError(3)
1437 except* TypeError:
1438 5
1439 except ValueError:
1440 7
1441
1442 self.run_and_compare(func,
1443 [(0, 'call'),
1444 (1, 'line'),
1445 (2, 'line'),
1446 (3, 'line'),
1447 (3, 'exception'),
1448 (4, 'line'),
1449 (6, 'line'),
1450 (7, 'line'),
1451 (7, 'return')])
1452
1453 def test_try_except_star_named_exception_not_caught(self):
1454
1455 def func():
1456 try:
1457 try:
1458 raise ValueError(3)
1459 except* TypeError as e:
1460 5
1461 except ValueError:
1462 7
1463
1464 self.run_and_compare(func,
1465 [(0, 'call'),
1466 (1, 'line'),
1467 (2, 'line'),
1468 (3, 'line'),
1469 (3, 'exception'),
1470 (4, 'line'),
1471 (6, 'line'),
1472 (7, 'line'),
1473 (7, 'return')])
1474
1475 def test_try_except_star_nested(self):
1476
1477 def func():
1478 try:
1479 try:
1480 raise ExceptionGroup(
1481 'eg',
1482 [ValueError(5), TypeError('bad type')])
1483 except* TypeError as e:
1484 7
1485 except* OSError:
1486 9
1487 except* ValueError:
1488 raise
1489 except* ValueError:
1490 try:
1491 raise TypeError(14)
1492 except* OSError:
1493 16
1494 except* TypeError as e:
1495 18
1496 return 0
1497
1498 self.run_and_compare(func,
1499 [(0, 'call'),
1500 (1, 'line'),
1501 (2, 'line'),
1502 (3, 'line'),
1503 (4, 'line'),
1504 (5, 'line'),
1505 (3, 'line'),
1506 (3, 'exception'),
1507 (6, 'line'),
1508 (7, 'line'),
1509 (8, 'line'),
1510 (10, 'line'),
1511 (11, 'line'),
1512 (12, 'line'),
1513 (13, 'line'),
1514 (14, 'line'),
1515 (14, 'exception'),
1516 (15, 'line'),
1517 (17, 'line'),
1518 (18, 'line'),
1519 (19, 'line'),
1520 (19, 'return')])
1521
1522 def test_notrace_lambda(self):
1523 #Regression test for issue 46314
1524
1525 def func():
1526 1
1527 lambda x: 2
1528 3
1529
1530 self.run_and_compare(func,
1531 [(0, 'call'),
1532 (1, 'line'),
1533 (2, 'line'),
1534 (3, 'line'),
1535 (3, 'return')])
1536
1537 def test_class_creation_with_docstrings(self):
1538
1539 def func():
1540 class Class_1:
1541 ''' the docstring. 2'''
1542 def __init__(self):
1543 ''' Another docstring. 4'''
1544 self.a = 5
1545
1546 self.run_and_compare(func,
1547 [(0, 'call'),
1548 (1, 'line'),
1549 (1, 'call'),
1550 (1, 'line'),
1551 (2, 'line'),
1552 (3, 'line'),
1553 (3, 'return'),
1554 (1, 'return')])
1555
1556 @support.cpython_only
1557 def test_no_line_event_after_creating_generator(self):
1558 # Spurious line events before call events only show up with C tracer
1559
1560 # Skip this test if the _testcapi module isn't available.
1561 _testcapi = import_helper.import_module('_testcapi')
1562
1563 def gen():
1564 yield 1
1565
1566 def func():
1567 for _ in (
1568 gen()
1569 ):
1570 pass
1571
1572 EXPECTED_EVENTS = [
1573 (0, 'call'),
1574 (2, 'line'),
1575 (1, 'line'),
1576 (-3, 'call'),
1577 (-2, 'line'),
1578 (-2, 'return'),
1579 (4, 'line'),
1580 (1, 'line'),
1581 (-2, 'call'),
1582 (-2, 'return'),
1583 (1, 'return'),
1584 ]
1585
1586 # C level events should be the same as expected and the same as Python level.
1587
1588 events = []
1589 # Turning on and off tracing must be on same line to avoid unwanted LINE events.
1590 _testcapi.settrace_to_record(events); func(); sys.settrace(None)
1591 start_line = func.__code__.co_firstlineno
1592 events = [
1593 (line-start_line, EVENT_NAMES[what])
1594 for (what, line, arg) in events
1595 ]
1596 self.assertEqual(events, EXPECTED_EVENTS)
1597
1598 self.run_and_compare(func, EXPECTED_EVENTS)
1599
1600 def test_settrace_error(self):
1601
1602 raised = False
1603 def error_once(frame, event, arg):
1604 nonlocal raised
1605 if not raised:
1606 raised = True
1607 raise Exception
1608 return error
1609
1610 try:
1611 sys._getframe().f_trace = error_once
1612 sys.settrace(error_once)
1613 len([])
1614 except Exception as ex:
1615 count = 0
1616 tb = ex.__traceback__
1617 while tb:
1618 if tb.tb_frame.f_code.co_name == "test_settrace_error":
1619 count += 1
1620 tb = tb.tb_next
1621 if count == 0:
1622 self.fail("Traceback is missing frame")
1623 elif count > 1:
1624 self.fail("Traceback has frame more than once")
1625 else:
1626 self.fail("No exception raised")
1627 finally:
1628 sys.settrace(None)
1629
1630 @support.cpython_only
1631 def test_testcapi_settrace_error(self):
1632
1633 # Skip this test if the _testcapi module isn't available.
1634 _testcapi = import_helper.import_module('_testcapi')
1635
1636 try:
1637 _testcapi.settrace_to_error([])
1638 len([])
1639 except Exception as ex:
1640 count = 0
1641 tb = ex.__traceback__
1642 while tb:
1643 if tb.tb_frame.f_code.co_name == "test_testcapi_settrace_error":
1644 count += 1
1645 tb = tb.tb_next
1646 if count == 0:
1647 self.fail("Traceback is missing frame")
1648 elif count > 1:
1649 self.fail("Traceback has frame more than once")
1650 else:
1651 self.fail("No exception raised")
1652 finally:
1653 sys.settrace(None)
1654
1655 def test_very_large_function(self):
1656 # There is a separate code path when the number of lines > (1 << 15).
1657 d = {}
1658 exec("""def f(): # line 0
1659 x = 0 # line 1
1660 y = 1 # line 2
1661 %s # lines 3 through (1 << 16)
1662 x += 1 #
1663 return""" % ('\n' * (1 << 16),), d)
1664 f = d['f']
1665
1666 EXPECTED_EVENTS = [
1667 (0, 'call'),
1668 (1, 'line'),
1669 (2, 'line'),
1670 (65540, 'line'),
1671 (65541, 'line'),
1672 (65541, 'return'),
1673 ]
1674
1675 self.run_and_compare(f, EXPECTED_EVENTS)
1676
1677
1678 EVENT_NAMES = [
1679 'call',
1680 'exception',
1681 'line',
1682 'return'
1683 ]
1684
1685
1686 class SkipLineEventsTraceTestCase(TraceTestCase):
1687 """Repeat the trace tests, but with per-line events skipped"""
1688
1689 def compare_events(self, line_offset, events, expected_events):
1690 skip_line_events = [e for e in expected_events if e[1] != 'line']
1691 super().compare_events(line_offset, events, skip_line_events)
1692
1693 @staticmethod
1694 def make_tracer():
1695 return Tracer(trace_line_events=False)
1696
1697
1698 @support.cpython_only
1699 class TraceOpcodesTestCase(TraceTestCase):
1700 """Repeat the trace tests, but with per-opcodes events enabled"""
1701
1702 def compare_events(self, line_offset, events, expected_events):
1703 skip_opcode_events = [e for e in events if e[1] != 'opcode']
1704 if len(events) > 1:
1705 self.assertLess(len(skip_opcode_events), len(events),
1706 msg="No 'opcode' events received by the tracer")
1707 super().compare_events(line_offset, skip_opcode_events, expected_events)
1708
1709 @staticmethod
1710 def make_tracer():
1711 return Tracer(trace_opcode_events=True)
1712
1713
1714 class RaisingTraceFuncTestCase(unittest.TestCase):
1715 def setUp(self):
1716 self.addCleanup(sys.settrace, sys.gettrace())
1717
1718 def trace(self, frame, event, arg):
1719 """A trace function that raises an exception in response to a
1720 specific trace event."""
1721 if event == self.raiseOnEvent:
1722 raise ValueError # just something that isn't RuntimeError
1723 else:
1724 return self.trace
1725
1726 def f(self):
1727 """The function to trace; raises an exception if that's the case
1728 we're testing, so that the 'exception' trace event fires."""
1729 if self.raiseOnEvent == 'exception':
1730 x = 0
1731 y = 1/x
1732 else:
1733 return 1
1734
1735 def run_test_for_event(self, event):
1736 """Tests that an exception raised in response to the given event is
1737 handled OK."""
1738 self.raiseOnEvent = event
1739 try:
1740 for i in range(sys.getrecursionlimit() + 1):
1741 sys.settrace(self.trace)
1742 try:
1743 self.f()
1744 except ValueError:
1745 pass
1746 else:
1747 self.fail("exception not raised!")
1748 except RuntimeError:
1749 self.fail("recursion counter not reset")
1750
1751 # Test the handling of exceptions raised by each kind of trace event.
1752 def test_call(self):
1753 self.run_test_for_event('call')
1754 def test_line(self):
1755 self.run_test_for_event('line')
1756 def test_return(self):
1757 self.run_test_for_event('return')
1758 def test_exception(self):
1759 self.run_test_for_event('exception')
1760
1761 def test_trash_stack(self):
1762 def f():
1763 for i in range(5):
1764 print(i) # line tracing will raise an exception at this line
1765
1766 def g(frame, why, extra):
1767 if (why == 'line' and
1768 frame.f_lineno == f.__code__.co_firstlineno + 2):
1769 raise RuntimeError("i am crashing")
1770 return g
1771
1772 sys.settrace(g)
1773 try:
1774 f()
1775 except RuntimeError:
1776 # the test is really that this doesn't segfault:
1777 import gc
1778 gc.collect()
1779 else:
1780 self.fail("exception not propagated")
1781
1782
1783 def test_exception_arguments(self):
1784 def f():
1785 x = 0
1786 # this should raise an error
1787 x.no_such_attr
1788 def g(frame, event, arg):
1789 if (event == 'exception'):
1790 type, exception, trace = arg
1791 self.assertIsInstance(exception, Exception)
1792 return g
1793
1794 existing = sys.gettrace()
1795 try:
1796 sys.settrace(g)
1797 try:
1798 f()
1799 except AttributeError:
1800 # this is expected
1801 pass
1802 finally:
1803 sys.settrace(existing)
1804
1805 def test_line_event_raises_before_opcode_event(self):
1806 exception = ValueError("BOOM!")
1807 def trace(frame, event, arg):
1808 if event == "line":
1809 raise exception
1810 frame.f_trace_opcodes = True
1811 return trace
1812 def f():
1813 pass
1814 with self.assertRaises(ValueError) as caught:
1815 sys.settrace(trace)
1816 f()
1817 self.assertIs(caught.exception, exception)
1818
1819
1820 # 'Jump' tests: assigning to frame.f_lineno within a trace function
1821 # moves the execution position - it's how debuggers implement a Jump
1822 # command (aka. "Set next statement").
1823
1824 class JumpTracer:
1825 """Defines a trace function that jumps from one place to another."""
1826
1827 def __init__(self, function, jumpFrom, jumpTo, event='line',
1828 decorated=False):
1829 self.code = function.__code__
1830 self.jumpFrom = jumpFrom
1831 self.jumpTo = jumpTo
1832 self.event = event
1833 self.firstLine = None if decorated else self.code.co_firstlineno
1834 self.done = False
1835
1836 def trace(self, frame, event, arg):
1837 if self.done:
1838 return
1839 # frame.f_code.co_firstlineno is the first line of the decorator when
1840 # 'function' is decorated and the decorator may be written using
1841 # multiple physical lines when it is too long. Use the first line
1842 # trace event in 'function' to find the first line of 'function'.
1843 if (self.firstLine is None and frame.f_code == self.code and
1844 event == 'line'):
1845 self.firstLine = frame.f_lineno - 1
1846 if (event == self.event and self.firstLine is not None and
1847 frame.f_lineno == self.firstLine + self.jumpFrom):
1848 f = frame
1849 while f is not None and f.f_code != self.code:
1850 f = f.f_back
1851 if f is not None:
1852 # Cope with non-integer self.jumpTo (because of
1853 # no_jump_to_non_integers below).
1854 try:
1855 frame.f_lineno = self.firstLine + self.jumpTo
1856 except TypeError:
1857 frame.f_lineno = self.jumpTo
1858 self.done = True
1859 return self.trace
1860
1861 # This verifies the line-numbers-must-be-integers rule.
1862 def no_jump_to_non_integers(output):
1863 try:
1864 output.append(2)
1865 except ValueError as e:
1866 output.append('integer' in str(e))
1867
1868 # This verifies that you can't set f_lineno via _getframe or similar
1869 # trickery.
1870 def no_jump_without_trace_function():
1871 try:
1872 previous_frame = sys._getframe().f_back
1873 previous_frame.f_lineno = previous_frame.f_lineno
1874 except ValueError as e:
1875 # This is the exception we wanted; make sure the error message
1876 # talks about trace functions.
1877 if 'trace' not in str(e):
1878 raise
1879 else:
1880 # Something's wrong - the expected exception wasn't raised.
1881 raise AssertionError("Trace-function-less jump failed to fail")
1882
1883
1884 class JumpTestCase(unittest.TestCase):
1885 if sys.implementation.name == "pypy":
1886 no_jump_into_with_error = (ValueError, "body of a with statement")
1887 else:
1888 no_jump_into_with_error = (ValueError, "stack")
1889
1890 def setUp(self):
1891 self.addCleanup(sys.settrace, sys.gettrace())
1892 sys.settrace(None)
1893
1894 def compare_jump_output(self, expected, received):
1895 if received != expected:
1896 self.fail( "Outputs don't match:\n" +
1897 "Expected: " + repr(expected) + "\n" +
1898 "Received: " + repr(received))
1899
1900 def run_test(self, func, jumpFrom, jumpTo, expected, error=None,
1901 event='line', decorated=False):
1902 wrapped = func
1903 while hasattr(wrapped, '__wrapped__'):
1904 wrapped = wrapped.__wrapped__
1905
1906 tracer = JumpTracer(wrapped, jumpFrom, jumpTo, event, decorated)
1907 sys.settrace(tracer.trace)
1908 output = []
1909 if error is None:
1910 func(output)
1911 else:
1912 with self.assertRaisesRegex(*error):
1913 func(output)
1914 sys.settrace(None)
1915 self.compare_jump_output(expected, output)
1916
1917 def run_async_test(self, func, jumpFrom, jumpTo, expected, error=None,
1918 event='line', decorated=False):
1919 wrapped = func
1920 while hasattr(wrapped, '__wrapped__'):
1921 wrapped = wrapped.__wrapped__
1922
1923 tracer = JumpTracer(wrapped, jumpFrom, jumpTo, event, decorated)
1924 sys.settrace(tracer.trace)
1925 output = []
1926 if error is None:
1927 asyncio.run(func(output))
1928 else:
1929 with self.assertRaisesRegex(*error):
1930 asyncio.run(func(output))
1931 sys.settrace(None)
1932 asyncio.set_event_loop_policy(None)
1933 self.compare_jump_output(expected, output)
1934
1935 def jump_test(jumpFrom, jumpTo, expected, error=None, event='line'):
1936 """Decorator that creates a test that makes a jump
1937 from one place to another in the following code.
1938 """
1939 def decorator(func):
1940 @wraps(func)
1941 def test(self):
1942 self.run_test(func, jumpFrom, jumpTo, expected,
1943 error=error, event=event, decorated=True)
1944 return test
1945 return decorator
1946
1947 def async_jump_test(jumpFrom, jumpTo, expected, error=None, event='line'):
1948 """Decorator that creates a test that makes a jump
1949 from one place to another in the following asynchronous code.
1950 """
1951 def decorator(func):
1952 @wraps(func)
1953 def test(self):
1954 self.run_async_test(func, jumpFrom, jumpTo, expected,
1955 error=error, event=event, decorated=True)
1956 return test
1957 return decorator
1958
1959 ## The first set of 'jump' tests are for things that are allowed:
1960
1961 @jump_test(1, 3, [3])
1962 def test_jump_simple_forwards(output):
1963 output.append(1)
1964 output.append(2)
1965 output.append(3)
1966
1967 @jump_test(2, 1, [1, 1, 2])
1968 def test_jump_simple_backwards(output):
1969 output.append(1)
1970 output.append(2)
1971
1972 @jump_test(1, 4, [5])
1973 def test_jump_is_none_forwards(output):
1974 x = None
1975 if x is None:
1976 output.append(3)
1977 else:
1978 output.append(5)
1979
1980 @jump_test(6, 5, [3, 5, 6])
1981 def test_jump_is_none_backwards(output):
1982 x = None
1983 if x is None:
1984 output.append(3)
1985 else:
1986 output.append(5)
1987 output.append(6)
1988
1989 @jump_test(1, 4, [5])
1990 def test_jump_is_not_none_forwards(output):
1991 x = None
1992 if x is not None:
1993 output.append(3)
1994 else:
1995 output.append(5)
1996
1997 @jump_test(6, 5, [5, 5, 6])
1998 def test_jump_is_not_none_backwards(output):
1999 x = None
2000 if x is not None:
2001 output.append(3)
2002 else:
2003 output.append(5)
2004 output.append(6)
2005
2006 @jump_test(3, 5, [2, 5])
2007 def test_jump_out_of_block_forwards(output):
2008 for i in 1, 2:
2009 output.append(2)
2010 for j in [3]: # Also tests jumping over a block
2011 output.append(4)
2012 output.append(5)
2013
2014 @jump_test(6, 1, [1, 3, 5, 1, 3, 5, 6, 7])
2015 def test_jump_out_of_block_backwards(output):
2016 output.append(1)
2017 for i in [1]:
2018 output.append(3)
2019 for j in [2]: # Also tests jumping over a block
2020 output.append(5)
2021 output.append(6)
2022 output.append(7)
2023
2024 @async_jump_test(4, 5, [3, 5])
2025 @clean_asynciter
2026 async def test_jump_out_of_async_for_block_forwards(output, asynciter):
2027 for i in [1]:
2028 async for i in asynciter([1, 2]):
2029 output.append(3)
2030 output.append(4)
2031 output.append(5)
2032
2033 @async_jump_test(5, 2, [2, 4, 2, 4, 5, 6])
2034 @clean_asynciter
2035 async def test_jump_out_of_async_for_block_backwards(output, asynciter):
2036 for i in [1]:
2037 output.append(2)
2038 async for i in asynciter([1]):
2039 output.append(4)
2040 output.append(5)
2041 output.append(6)
2042
2043 @jump_test(1, 2, [3])
2044 def test_jump_to_codeless_line(output):
2045 output.append(1)
2046 # Jumping to this line should skip to the next one.
2047 output.append(3)
2048
2049 @jump_test(2, 2, [1, 2, 3])
2050 def test_jump_to_same_line(output):
2051 output.append(1)
2052 output.append(2)
2053 output.append(3)
2054
2055 # Tests jumping within a finally block, and over one.
2056 @jump_test(4, 9, [2, 9])
2057 def test_jump_in_nested_finally(output):
2058 try:
2059 output.append(2)
2060 finally:
2061 output.append(4)
2062 try:
2063 output.append(6)
2064 finally:
2065 output.append(8)
2066 output.append(9)
2067
2068 @jump_test(6, 7, [2, 7], (ZeroDivisionError, ''))
2069 def test_jump_in_nested_finally_2(output):
2070 try:
2071 output.append(2)
2072 1/0
2073 return
2074 finally:
2075 output.append(6)
2076 output.append(7)
2077 output.append(8)
2078
2079 @jump_test(6, 11, [2, 11], (ZeroDivisionError, ''))
2080 def test_jump_in_nested_finally_3(output):
2081 try:
2082 output.append(2)
2083 1/0
2084 return
2085 finally:
2086 output.append(6)
2087 try:
2088 output.append(8)
2089 finally:
2090 output.append(10)
2091 output.append(11)
2092 output.append(12)
2093
2094 @jump_test(5, 11, [2, 4], (ValueError, 'exception'))
2095 def test_no_jump_over_return_try_finally_in_finally_block(output):
2096 try:
2097 output.append(2)
2098 finally:
2099 output.append(4)
2100 output.append(5)
2101 return
2102 try:
2103 output.append(8)
2104 finally:
2105 output.append(10)
2106 pass
2107 output.append(12)
2108
2109 @jump_test(3, 4, [1], (ValueError, 'after'))
2110 def test_no_jump_infinite_while_loop(output):
2111 output.append(1)
2112 while True:
2113 output.append(3)
2114 output.append(4)
2115
2116 @jump_test(2, 4, [4, 4])
2117 def test_jump_forwards_into_while_block(output):
2118 i = 1
2119 output.append(2)
2120 while i <= 2:
2121 output.append(4)
2122 i += 1
2123
2124 @jump_test(5, 3, [3, 3, 3, 5])
2125 def test_jump_backwards_into_while_block(output):
2126 i = 1
2127 while i <= 2:
2128 output.append(3)
2129 i += 1
2130 output.append(5)
2131
2132 @jump_test(2, 3, [1, 3])
2133 def test_jump_forwards_out_of_with_block(output):
2134 with tracecontext(output, 1):
2135 output.append(2)
2136 output.append(3)
2137
2138 @async_jump_test(2, 3, [1, 3])
2139 async def test_jump_forwards_out_of_async_with_block(output):
2140 async with asynctracecontext(output, 1):
2141 output.append(2)
2142 output.append(3)
2143
2144 @jump_test(3, 1, [1, 2, 1, 2, 3, -2])
2145 def test_jump_backwards_out_of_with_block(output):
2146 output.append(1)
2147 with tracecontext(output, 2):
2148 output.append(3)
2149
2150 @async_jump_test(3, 1, [1, 2, 1, 2, 3, -2])
2151 async def test_jump_backwards_out_of_async_with_block(output):
2152 output.append(1)
2153 async with asynctracecontext(output, 2):
2154 output.append(3)
2155
2156 @jump_test(2, 5, [5])
2157 def test_jump_forwards_out_of_try_finally_block(output):
2158 try:
2159 output.append(2)
2160 finally:
2161 output.append(4)
2162 output.append(5)
2163
2164 @jump_test(3, 1, [1, 1, 3, 5])
2165 def test_jump_backwards_out_of_try_finally_block(output):
2166 output.append(1)
2167 try:
2168 output.append(3)
2169 finally:
2170 output.append(5)
2171
2172 @jump_test(2, 6, [6])
2173 def test_jump_forwards_out_of_try_except_block(output):
2174 try:
2175 output.append(2)
2176 except:
2177 output.append(4)
2178 raise
2179 output.append(6)
2180
2181 @jump_test(3, 1, [1, 1, 3])
2182 def test_jump_backwards_out_of_try_except_block(output):
2183 output.append(1)
2184 try:
2185 output.append(3)
2186 except:
2187 output.append(5)
2188 raise
2189
2190 @jump_test(5, 7, [4, 7, 8])
2191 def test_jump_between_except_blocks(output):
2192 try:
2193 1/0
2194 except ZeroDivisionError:
2195 output.append(4)
2196 output.append(5)
2197 except FloatingPointError:
2198 output.append(7)
2199 output.append(8)
2200
2201 @jump_test(5, 7, [4, 7, 8])
2202 def test_jump_from_except_to_finally(output):
2203 try:
2204 1/0
2205 except ZeroDivisionError:
2206 output.append(4)
2207 output.append(5)
2208 finally:
2209 output.append(7)
2210 output.append(8)
2211
2212 @jump_test(5, 6, [4, 6, 7])
2213 def test_jump_within_except_block(output):
2214 try:
2215 1/0
2216 except:
2217 output.append(4)
2218 output.append(5)
2219 output.append(6)
2220 output.append(7)
2221
2222 @jump_test(6, 1, [1, 5, 1, 5])
2223 def test_jump_over_try_except(output):
2224 output.append(1)
2225 try:
2226 1 / 0
2227 except ZeroDivisionError as e:
2228 output.append(5)
2229 x = 42 # has to be a two-instruction block
2230
2231 @jump_test(2, 4, [1, 4, 5, -4])
2232 def test_jump_across_with(output):
2233 output.append(1)
2234 with tracecontext(output, 2):
2235 output.append(3)
2236 with tracecontext(output, 4):
2237 output.append(5)
2238
2239 @async_jump_test(2, 4, [1, 4, 5, -4])
2240 async def test_jump_across_async_with(output):
2241 output.append(1)
2242 async with asynctracecontext(output, 2):
2243 output.append(3)
2244 async with asynctracecontext(output, 4):
2245 output.append(5)
2246
2247 @jump_test(4, 5, [1, 3, 5, 6])
2248 def test_jump_out_of_with_block_within_for_block(output):
2249 output.append(1)
2250 for i in [1]:
2251 with tracecontext(output, 3):
2252 output.append(4)
2253 output.append(5)
2254 output.append(6)
2255
2256 @async_jump_test(4, 5, [1, 3, 5, 6])
2257 async def test_jump_out_of_async_with_block_within_for_block(output):
2258 output.append(1)
2259 for i in [1]:
2260 async with asynctracecontext(output, 3):
2261 output.append(4)
2262 output.append(5)
2263 output.append(6)
2264
2265 @jump_test(4, 5, [1, 2, 3, 5, -2, 6])
2266 def test_jump_out_of_with_block_within_with_block(output):
2267 output.append(1)
2268 with tracecontext(output, 2):
2269 with tracecontext(output, 3):
2270 output.append(4)
2271 output.append(5)
2272 output.append(6)
2273
2274 @async_jump_test(4, 5, [1, 2, 3, 5, -2, 6])
2275 async def test_jump_out_of_async_with_block_within_with_block(output):
2276 output.append(1)
2277 with tracecontext(output, 2):
2278 async with asynctracecontext(output, 3):
2279 output.append(4)
2280 output.append(5)
2281 output.append(6)
2282
2283 @jump_test(5, 6, [2, 4, 6, 7])
2284 def test_jump_out_of_with_block_within_finally_block(output):
2285 try:
2286 output.append(2)
2287 finally:
2288 with tracecontext(output, 4):
2289 output.append(5)
2290 output.append(6)
2291 output.append(7)
2292
2293 @async_jump_test(5, 6, [2, 4, 6, 7])
2294 async def test_jump_out_of_async_with_block_within_finally_block(output):
2295 try:
2296 output.append(2)
2297 finally:
2298 async with asynctracecontext(output, 4):
2299 output.append(5)
2300 output.append(6)
2301 output.append(7)
2302
2303 @jump_test(8, 11, [1, 3, 5, 11, 12])
2304 def test_jump_out_of_complex_nested_blocks(output):
2305 output.append(1)
2306 for i in [1]:
2307 output.append(3)
2308 for j in [1, 2]:
2309 output.append(5)
2310 try:
2311 for k in [1, 2]:
2312 output.append(8)
2313 finally:
2314 output.append(10)
2315 output.append(11)
2316 output.append(12)
2317
2318 @jump_test(3, 5, [1, 2, 5])
2319 def test_jump_out_of_with_assignment(output):
2320 output.append(1)
2321 with tracecontext(output, 2) \
2322 as x:
2323 output.append(4)
2324 output.append(5)
2325
2326 @async_jump_test(3, 5, [1, 2, 5])
2327 async def test_jump_out_of_async_with_assignment(output):
2328 output.append(1)
2329 async with asynctracecontext(output, 2) \
2330 as x:
2331 output.append(4)
2332 output.append(5)
2333
2334 @jump_test(3, 6, [1, 6, 8, 9])
2335 def test_jump_over_return_in_try_finally_block(output):
2336 output.append(1)
2337 try:
2338 output.append(3)
2339 if not output: # always false
2340 return
2341 output.append(6)
2342 finally:
2343 output.append(8)
2344 output.append(9)
2345
2346 @jump_test(5, 8, [1, 3, 8, 10, 11, 13])
2347 def test_jump_over_break_in_try_finally_block(output):
2348 output.append(1)
2349 while True:
2350 output.append(3)
2351 try:
2352 output.append(5)
2353 if not output: # always false
2354 break
2355 output.append(8)
2356 finally:
2357 output.append(10)
2358 output.append(11)
2359 break
2360 output.append(13)
2361
2362 @jump_test(1, 7, [7, 8])
2363 def test_jump_over_for_block_before_else(output):
2364 output.append(1)
2365 if not output: # always false
2366 for i in [3]:
2367 output.append(4)
2368 else:
2369 output.append(6)
2370 output.append(7)
2371 output.append(8)
2372
2373 @async_jump_test(1, 7, [7, 8])
2374 async def test_jump_over_async_for_block_before_else(output):
2375 output.append(1)
2376 if not output: # always false
2377 async for i in asynciter([3]):
2378 output.append(4)
2379 else:
2380 output.append(6)
2381 output.append(7)
2382 output.append(8)
2383
2384 # The second set of 'jump' tests are for things that are not allowed:
2385
2386 @jump_test(2, 3, [1], (ValueError, 'after'))
2387 def test_no_jump_too_far_forwards(output):
2388 output.append(1)
2389 output.append(2)
2390
2391 @jump_test(2, -2, [1], (ValueError, 'before'))
2392 def test_no_jump_too_far_backwards(output):
2393 output.append(1)
2394 output.append(2)
2395
2396 # Test each kind of 'except' line.
2397 @jump_test(2, 3, [4], (ValueError, 'except'))
2398 def test_no_jump_to_except_1(output):
2399 try:
2400 output.append(2)
2401 except:
2402 output.append(4)
2403 raise
2404
2405 @jump_test(2, 3, [4], (ValueError, 'except'))
2406 def test_no_jump_to_except_2(output):
2407 try:
2408 output.append(2)
2409 except ValueError:
2410 output.append(4)
2411 raise
2412
2413 @jump_test(2, 3, [4], (ValueError, 'except'))
2414 def test_no_jump_to_except_3(output):
2415 try:
2416 output.append(2)
2417 except ValueError as e:
2418 output.append(4)
2419 raise e
2420
2421 @jump_test(2, 3, [4], (ValueError, 'except'))
2422 def test_no_jump_to_except_4(output):
2423 try:
2424 output.append(2)
2425 except (ValueError, RuntimeError) as e:
2426 output.append(4)
2427 raise e
2428
2429 @jump_test(1, 3, [], (ValueError, 'into'))
2430 def test_no_jump_forwards_into_for_block(output):
2431 output.append(1)
2432 for i in 1, 2:
2433 output.append(3)
2434
2435 @async_jump_test(1, 3, [], (ValueError, 'into'))
2436 async def test_no_jump_forwards_into_async_for_block(output):
2437 output.append(1)
2438 async for i in asynciter([1, 2]):
2439 output.append(3)
2440 pass
2441
2442 @jump_test(3, 2, [2, 2], (ValueError, 'into'))
2443 def test_no_jump_backwards_into_for_block(output):
2444 for i in 1, 2:
2445 output.append(2)
2446 output.append(3)
2447
2448 @async_jump_test(3, 2, [2, 2], (ValueError, "can't jump into the body of a for loop"))
2449 async def test_no_jump_backwards_into_async_for_block(output):
2450 async for i in asynciter([1, 2]):
2451 output.append(2)
2452 output.append(3)
2453
2454 @jump_test(1, 3, [], no_jump_into_with_error)
2455 def test_no_jump_forwards_into_with_block(output):
2456 output.append(1)
2457 with tracecontext(output, 2):
2458 output.append(3)
2459
2460 @async_jump_test(1, 3, [], no_jump_into_with_error)
2461 async def test_no_jump_forwards_into_async_with_block(output):
2462 output.append(1)
2463 async with asynctracecontext(output, 2):
2464 output.append(3)
2465
2466 @jump_test(3, 2, [1, 2, -1], no_jump_into_with_error)
2467 def test_no_jump_backwards_into_with_block(output):
2468 with tracecontext(output, 1):
2469 output.append(2)
2470 output.append(3)
2471
2472 @async_jump_test(3, 2, [1, 2, -1], no_jump_into_with_error)
2473 async def test_no_jump_backwards_into_async_with_block(output):
2474 async with asynctracecontext(output, 1):
2475 output.append(2)
2476 output.append(3)
2477
2478 @jump_test(1, 3, [3, 5])
2479 def test_jump_forwards_into_try_finally_block(output):
2480 output.append(1)
2481 try:
2482 output.append(3)
2483 finally:
2484 output.append(5)
2485
2486 @jump_test(5, 2, [2, 4, 2, 4, 5])
2487 def test_jump_backwards_into_try_finally_block(output):
2488 try:
2489 output.append(2)
2490 finally:
2491 output.append(4)
2492 output.append(5)
2493
2494 @jump_test(1, 3, [3])
2495 def test_jump_forwards_into_try_except_block(output):
2496 output.append(1)
2497 try:
2498 output.append(3)
2499 except:
2500 output.append(5)
2501 raise
2502
2503 @jump_test(6, 2, [2, 2, 6])
2504 def test_jump_backwards_into_try_except_block(output):
2505 try:
2506 output.append(2)
2507 except:
2508 output.append(4)
2509 raise
2510 output.append(6)
2511
2512 # 'except' with a variable creates an implicit finally block
2513 @jump_test(5, 7, [4, 7, 8])
2514 def test_jump_between_except_blocks_2(output):
2515 try:
2516 1/0
2517 except ZeroDivisionError:
2518 output.append(4)
2519 output.append(5)
2520 except FloatingPointError as e:
2521 output.append(7)
2522 output.append(8)
2523
2524 @jump_test(1, 5, [5])
2525 def test_jump_into_finally_block(output):
2526 output.append(1)
2527 try:
2528 output.append(3)
2529 finally:
2530 output.append(5)
2531
2532 @jump_test(3, 6, [2, 6, 7])
2533 def test_jump_into_finally_block_from_try_block(output):
2534 try:
2535 output.append(2)
2536 output.append(3)
2537 finally: # still executed if the jump is failed
2538 output.append(5)
2539 output.append(6)
2540 output.append(7)
2541
2542 @jump_test(5, 1, [1, 3, 1, 3, 5])
2543 def test_jump_out_of_finally_block(output):
2544 output.append(1)
2545 try:
2546 output.append(3)
2547 finally:
2548 output.append(5)
2549
2550 @jump_test(1, 5, [], (ValueError, "can't jump into an 'except' block as there's no exception"))
2551 def test_no_jump_into_bare_except_block(output):
2552 output.append(1)
2553 try:
2554 output.append(3)
2555 except:
2556 output.append(5)
2557
2558 @jump_test(1, 5, [], (ValueError, "can't jump into an 'except' block as there's no exception"))
2559 def test_no_jump_into_qualified_except_block(output):
2560 output.append(1)
2561 try:
2562 output.append(3)
2563 except Exception:
2564 output.append(5)
2565
2566 @jump_test(3, 6, [2, 5, 6], (ValueError, "can't jump into an 'except' block as there's no exception"))
2567 def test_no_jump_into_bare_except_block_from_try_block(output):
2568 try:
2569 output.append(2)
2570 output.append(3)
2571 except: # executed if the jump is failed
2572 output.append(5)
2573 output.append(6)
2574 raise
2575 output.append(8)
2576
2577 @jump_test(3, 6, [2], (ValueError, "can't jump into an 'except' block as there's no exception"))
2578 def test_no_jump_into_qualified_except_block_from_try_block(output):
2579 try:
2580 output.append(2)
2581 output.append(3)
2582 except ZeroDivisionError:
2583 output.append(5)
2584 output.append(6)
2585 raise
2586 output.append(8)
2587
2588 @jump_test(7, 1, [1, 3, 6, 1, 3, 6, 7])
2589 def test_jump_out_of_bare_except_block(output):
2590 output.append(1)
2591 try:
2592 output.append(3)
2593 1/0
2594 except:
2595 output.append(6)
2596 output.append(7)
2597
2598 @jump_test(7, 1, [1, 3, 6, 1, 3, 6, 7])
2599 def test_jump_out_of_qualified_except_block(output):
2600 output.append(1)
2601 try:
2602 output.append(3)
2603 1/0
2604 except Exception:
2605 output.append(6)
2606 output.append(7)
2607
2608 @jump_test(3, 5, [1, 2, 5, -2])
2609 def test_jump_between_with_blocks(output):
2610 output.append(1)
2611 with tracecontext(output, 2):
2612 output.append(3)
2613 with tracecontext(output, 4):
2614 output.append(5)
2615
2616 @async_jump_test(3, 5, [1, 2, 5, -2])
2617 async def test_jump_between_async_with_blocks(output):
2618 output.append(1)
2619 async with asynctracecontext(output, 2):
2620 output.append(3)
2621 async with asynctracecontext(output, 4):
2622 output.append(5)
2623
2624 @jump_test(5, 7, [2, 4], (ValueError, "after"))
2625 def test_no_jump_over_return_out_of_finally_block(output):
2626 try:
2627 output.append(2)
2628 finally:
2629 output.append(4)
2630 output.append(5)
2631 return
2632 output.append(7)
2633
2634 @jump_test(7, 4, [1, 6], (ValueError, 'into'))
2635 def test_no_jump_into_for_block_before_else(output):
2636 output.append(1)
2637 if not output: # always false
2638 for i in [3]:
2639 output.append(4)
2640 else:
2641 output.append(6)
2642 output.append(7)
2643 output.append(8)
2644
2645 @async_jump_test(7, 4, [1, 6], (ValueError, 'into'))
2646 async def test_no_jump_into_async_for_block_before_else(output):
2647 output.append(1)
2648 if not output: # always false
2649 async for i in asynciter([3]):
2650 output.append(4)
2651 else:
2652 output.append(6)
2653 output.append(7)
2654 output.append(8)
2655
2656 def test_no_jump_to_non_integers(self):
2657 self.run_test(no_jump_to_non_integers, 2, "Spam", [True])
2658
2659 def test_no_jump_without_trace_function(self):
2660 # Must set sys.settrace(None) in setUp(), else condition is not
2661 # triggered.
2662 no_jump_without_trace_function()
2663
2664 def test_large_function(self):
2665 d = {}
2666 exec("""def f(output): # line 0
2667 x = 0 # line 1
2668 y = 1 # line 2
2669 ''' # line 3
2670 %s # lines 4-1004
2671 ''' # line 1005
2672 x += 1 # line 1006
2673 output.append(x) # line 1007
2674 return""" % ('\n' * 1000,), d)
2675 f = d['f']
2676 self.run_test(f, 2, 1007, [0])
2677
2678 def test_jump_to_firstlineno(self):
2679 # This tests that PDB can jump back to the first line in a
2680 # file. See issue #1689458. It can only be triggered in a
2681 # function call if the function is defined on a single line.
2682 code = compile("""
2683 # Comments don't count.
2684 output.append(2) # firstlineno is here.
2685 output.append(3)
2686 output.append(4)
2687 """, "<fake module>", "exec")
2688 class fake_function:
2689 __code__ = code
2690 tracer = JumpTracer(fake_function, 4, 1)
2691 sys.settrace(tracer.trace)
2692 namespace = {"output": []}
2693 exec(code, namespace)
2694 sys.settrace(None)
2695 self.compare_jump_output([2, 3, 2, 3, 4], namespace["output"])
2696
2697 @jump_test(2, 3, [1], event='call', error=(ValueError, "can't jump from"
2698 " the 'call' trace event of a new frame"))
2699 def test_no_jump_from_call(output):
2700 output.append(1)
2701 def nested():
2702 output.append(3)
2703 nested()
2704 output.append(5)
2705
2706 @jump_test(2, 1, [1], event='return', error=(ValueError,
2707 "can only jump from a 'line' trace event"))
2708 def test_no_jump_from_return_event(output):
2709 output.append(1)
2710 return
2711
2712 @jump_test(2, 1, [1], event='exception', error=(ValueError,
2713 "can only jump from a 'line' trace event"))
2714 def test_no_jump_from_exception_event(output):
2715 output.append(1)
2716 1 / 0
2717
2718 @jump_test(3, 2, [2, 5], event='return')
2719 def test_jump_from_yield(output):
2720 def gen():
2721 output.append(2)
2722 yield 3
2723 next(gen())
2724 output.append(5)
2725
2726 @jump_test(2, 3, [1, 3])
2727 def test_jump_forward_over_listcomp(output):
2728 output.append(1)
2729 x = [i for i in range(10)]
2730 output.append(3)
2731
2732 # checking for segfaults.
2733 # See https://github.com/python/cpython/issues/92311
2734 @jump_test(3, 1, [])
2735 def test_jump_backward_over_listcomp(output):
2736 a = 1
2737 x = [i for i in range(10)]
2738 c = 3
2739
2740 @jump_test(8, 2, [2, 7, 2])
2741 def test_jump_backward_over_listcomp_v2(output):
2742 flag = False
2743 output.append(2)
2744 if flag:
2745 return
2746 x = [i for i in range(5)]
2747 flag = 6
2748 output.append(7)
2749 output.append(8)
2750
2751 @async_jump_test(2, 3, [1, 3])
2752 async def test_jump_forward_over_async_listcomp(output):
2753 output.append(1)
2754 x = [i async for i in asynciter(range(10))]
2755 output.append(3)
2756
2757 @async_jump_test(3, 1, [])
2758 async def test_jump_backward_over_async_listcomp(output):
2759 a = 1
2760 x = [i async for i in asynciter(range(10))]
2761 c = 3
2762
2763 @async_jump_test(8, 2, [2, 7, 2])
2764 async def test_jump_backward_over_async_listcomp_v2(output):
2765 flag = False
2766 output.append(2)
2767 if flag:
2768 return
2769 x = [i async for i in asynciter(range(5))]
2770 flag = 6
2771 output.append(7)
2772 output.append(8)
2773
2774 # checking for segfaults.
2775 @jump_test(3, 7, [], error=(ValueError, "stack"))
2776 @support.cpython_only
2777 def test_jump_with_null_on_stack_load_global(output):
2778 a = 1
2779 print(
2780 output.append(3)
2781 )
2782 output.append(5)
2783 (
2784 ( # 7
2785 a
2786 +
2787 10
2788 )
2789 +
2790 13
2791 )
2792 output.append(15)
2793
2794 # checking for segfaults.
2795 @jump_test(4, 8, [], error=(ValueError, "stack"))
2796 @support.cpython_only
2797 def test_jump_with_null_on_stack_push_null(output):
2798 a = 1
2799 f = print
2800 f(
2801 output.append(4)
2802 )
2803 output.append(6)
2804 (
2805 ( # 8
2806 a
2807 +
2808 11
2809 )
2810 +
2811 14
2812 )
2813 output.append(16)
2814
2815 # checking for segfaults.
2816 @jump_test(3, 7, [], error=(ValueError, "stack"))
2817 @support.cpython_only
2818 def test_jump_with_null_on_stack_load_attr(output):
2819 a = 1
2820 list.append(
2821 output, 3
2822 )
2823 output.append(5)
2824 (
2825 ( # 7
2826 a
2827 +
2828 10
2829 )
2830 +
2831 13
2832 )
2833 output.append(15)
2834
2835 @jump_test(2, 3, [1, 3])
2836 def test_jump_extended_args_unpack_ex_simple(output):
2837 output.append(1)
2838 _, *_, _ = output.append(2) or "Spam"
2839 output.append(3)
2840
2841 @jump_test(3, 4, [1, 4, 4, 5])
2842 def test_jump_extended_args_unpack_ex_tricky(output):
2843 output.append(1)
2844 (
2845 _, *_, _
2846 ) = output.append(4) or "Spam"
2847 output.append(5)
2848
2849 @support.requires_resource('cpu')
2850 def test_jump_extended_args_for_iter(self):
2851 # In addition to failing when extended arg handling is broken, this can
2852 # also hang for a *very* long time:
2853 source = [
2854 "def f(output):",
2855 " output.append(1)",
2856 " for _ in spam:",
2857 *(f" output.append({i})" for i in range(3, 100_000)),
2858 f" output.append(100_000)",
2859 ]
2860 namespace = {}
2861 exec("\n".join(source), namespace)
2862 f = namespace["f"]
2863 self.run_test(f, 2, 100_000, [1, 100_000])
2864
2865 @jump_test(2, 3, [1, 3])
2866 def test_jump_or_pop(output):
2867 output.append(1)
2868 _ = output.append(2) and "Spam"
2869 output.append(3)
2870
2871
2872 class TestExtendedArgs(unittest.TestCase):
2873
2874 def setUp(self):
2875 self.addCleanup(sys.settrace, sys.gettrace())
2876 sys.settrace(None)
2877
2878 def count_traces(self, func):
2879 # warmup
2880 for _ in range(20):
2881 func()
2882
2883 counts = {"call": 0, "line": 0, "return": 0}
2884 def trace(frame, event, arg):
2885 counts[event] += 1
2886 return trace
2887
2888 sys.settrace(trace)
2889 func()
2890 sys.settrace(None)
2891
2892 return counts
2893
2894 def test_trace_unpack_long_sequence(self):
2895 ns = {}
2896 code = "def f():\n (" + "y,\n "*300 + ") = range(300)"
2897 exec(code, ns)
2898 counts = self.count_traces(ns["f"])
2899 self.assertEqual(counts, {'call': 1, 'line': 301, 'return': 1})
2900
2901 def test_trace_lots_of_globals(self):
2902 code = """if 1:
2903 def f():
2904 return (
2905 {}
2906 )
2907 """.format("\n+\n".join(f"var{i}\n" for i in range(1000)))
2908 ns = {f"var{i}": i for i in range(1000)}
2909 exec(code, ns)
2910 counts = self.count_traces(ns["f"])
2911 self.assertEqual(counts, {'call': 1, 'line': 2000, 'return': 1})
2912
2913
2914 class TestEdgeCases(unittest.TestCase):
2915
2916 def setUp(self):
2917 self.addCleanup(sys.settrace, sys.gettrace())
2918 sys.settrace(None)
2919
2920 @support.cpython_only
2921 def test_reentrancy(self):
2922 def foo(*args):
2923 ...
2924
2925 def bar(*args):
2926 ...
2927
2928 class A:
2929 def __call__(self, *args):
2930 pass
2931
2932 def __del__(self):
2933 sys.settrace(bar)
2934
2935 sys.settrace(A())
2936 with support.catch_unraisable_exception() as cm:
2937 sys.settrace(foo)
2938 self.assertEqual(cm.unraisable.object, A.__del__)
2939 self.assertIsInstance(cm.unraisable.exc_value, RuntimeError)
2940
2941 self.assertEqual(sys.gettrace(), foo)
2942
2943
2944 def test_same_object(self):
2945 def foo(*args):
2946 ...
2947
2948 sys.settrace(foo)
2949 del foo
2950 sys.settrace(sys.gettrace())
2951
2952
2953 if __name__ == "__main__":
2954 unittest.main()