Debian Codegraph @

pypy/interpreter/test/apptest_sys_settrace.py

raw symbols SCIP
1 # Ported from lib-python/3/test/test_sys_settrace.py
2 # Converted to pytest apptest style for untranslated testing.
3 # Skips: @cpython_only tests, async jump tests (non-core), test_very_large_function.
4
5 import sys
6 import gc
7 import pytest
8
9
10 # ---------------------------------------------------------------------------
11 # Infrastructure
12 # ---------------------------------------------------------------------------
13
14 class tracecontext:
15 """Context manager that traces its enter and exit."""
16 def __init__(self, output, value):
17 self.output = output
18 self.value = value
19
20 def __enter__(self):
21 self.output.append(self.value)
22
23 def __exit__(self, *exc_info):
24 self.output.append(-self.value)
25
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
40 async def asynciter(iterable):
41 """Convert an iterable to an asynchronous iterator."""
42 for x in iterable:
43 yield x
44
45
46 class Tracer:
47 def __init__(self, trace_line_events=None, trace_opcode_events=None):
48 self.trace_line_events = trace_line_events
49 self.trace_opcode_events = trace_opcode_events
50 self.events = []
51
52 def _reconfigure_frame(self, frame):
53 if self.trace_line_events is not None:
54 frame.f_trace_lines = self.trace_line_events
55 if self.trace_opcode_events is not None:
56 frame.f_trace_opcodes = self.trace_opcode_events
57
58 def trace(self, frame, event, arg):
59 self._reconfigure_frame(frame)
60 self.events.append((frame.f_lineno, event))
61 return self.trace
62
63 def traceWithGenexp(self, frame, event, arg):
64 self._reconfigure_frame(frame)
65 (o for o in [1])
66 self.events.append((frame.f_lineno, event))
67 return self.trace
68
69
70 def compare_events(line_offset, events, expected_events):
71 import difflib
72 events = [(l - line_offset, e) for (l, e) in events]
73 if events != expected_events:
74 raise AssertionError(
75 "events did not match expectation:\n" +
76 "\n".join(difflib.ndiff([str(x) for x in expected_events],
77 [str(x) for x in events])))
78
79
80 def run_and_compare(func, expected_events):
81 using_gc = gc.isenabled()
82 gc.collect() # collect importlib generators before disabling GC (PyPy has no refcounting)
83 gc.disable()
84 try:
85 tracer = Tracer()
86 sys.settrace(tracer.trace)
87 try:
88 func()
89 finally:
90 sys.settrace(None)
91 compare_events(func.__code__.co_firstlineno, tracer.events, expected_events)
92 finally:
93 if using_gc:
94 gc.enable()
95
96
97 def run_test(func):
98 run_and_compare(func, func.events)
99
100
101 def run_test2(func):
102 """For functions that take a trace function as argument."""
103 using_gc = gc.isenabled()
104 gc.disable()
105 try:
106 tracer = Tracer()
107 func(tracer.trace)
108 sys.settrace(None)
109 compare_events(func.__code__.co_firstlineno, tracer.events, func.events)
110 finally:
111 if using_gc:
112 gc.enable()
113
114
115 # ---------------------------------------------------------------------------
116 # Functions with associated .events used by trace tests
117 # ---------------------------------------------------------------------------
118
119 def basic():
120 return 1
121
122 basic.events = [(0, 'call'),
123 (1, 'line'),
124 (1, 'return')]
125
126
127 def arigo_example0():
128 x = 1
129 del x
130 while 0:
131 pass
132 x = 1
133
134 arigo_example0.events = [(0, 'call'),
135 (1, 'line'),
136 (2, 'line'),
137 (3, 'line'),
138 (5, 'line'),
139 (5, 'return')]
140
141
142 def arigo_example1():
143 x = 1
144 del x
145 if 0:
146 pass
147 x = 1
148
149 arigo_example1.events = [(0, 'call'),
150 (1, 'line'),
151 (2, 'line'),
152 (3, 'line'),
153 (5, 'line'),
154 (5, 'return')]
155
156
157 def arigo_example2():
158 x = 1
159 del x
160 if 1:
161 x = 1
162 else:
163 pass
164 return None
165
166 arigo_example2.events = [(0, 'call'),
167 (1, 'line'),
168 (2, 'line'),
169 (3, 'line'),
170 (4, 'line'),
171 (7, 'line'),
172 (7, 'return')]
173
174
175 def one_instr_line():
176 x = 1
177 del x
178 x = 1
179
180 one_instr_line.events = [(0, 'call'),
181 (1, 'line'),
182 (2, 'line'),
183 (3, 'line'),
184 (3, 'return')]
185
186
187 def no_pop_tops(): # 0
188 x = 1 # 1
189 for a in range(2): # 2
190 if a: # 3
191 x = 1 # 4
192 else: # 5
193 x = 1 # 6
194
195 no_pop_tops.events = [(0, 'call'),
196 (1, 'line'),
197 (2, 'line'),
198 (3, 'line'),
199 (6, 'line'),
200 (2, 'line'),
201 (3, 'line'),
202 (4, 'line'),
203 (2, 'line'),
204 (2, 'return')]
205
206
207 def no_pop_blocks():
208 y = 1
209 while not y:
210 bla
211 x = 1
212
213 no_pop_blocks.events = [(0, 'call'),
214 (1, 'line'),
215 (2, 'line'),
216 (4, 'line'),
217 (4, 'return')]
218
219
220 def _called(): # line -3
221 x = 1
222
223 def _call(): # line 0
224 _called()
225
226 _call.events = [(0, 'call'),
227 (1, 'line'),
228 (-3, 'call'),
229 (-2, 'line'),
230 (-2, 'return'),
231 (1, 'return')]
232
233
234 def _raises():
235 raise Exception
236
237 def _test_raise():
238 try:
239 _raises()
240 except Exception:
241 pass
242
243 _test_raise.events = [(0, 'call'),
244 (1, 'line'),
245 (2, 'line'),
246 (-3, 'call'),
247 (-2, 'line'),
248 (-2, 'exception'),
249 (-2, 'return'),
250 (2, 'exception'),
251 (3, 'line'),
252 (4, 'line'),
253 (4, 'return')]
254
255
256 def _settrace_and_return(tracefunc):
257 sys.settrace(tracefunc)
258 sys._getframe().f_back.f_trace = tracefunc
259
260 def settrace_and_return(tracefunc):
261 _settrace_and_return(tracefunc)
262
263 settrace_and_return.events = [(1, 'return')]
264
265
266 def _settrace_and_raise(tracefunc):
267 sys.settrace(tracefunc)
268 sys._getframe().f_back.f_trace = tracefunc
269 raise RuntimeError
270
271 def settrace_and_raise(tracefunc):
272 try:
273 _settrace_and_raise(tracefunc)
274 except RuntimeError:
275 pass
276
277 settrace_and_raise.events = [(2, 'exception'),
278 (3, 'line'),
279 (4, 'line'),
280 (4, 'return')]
281
282
283 def ireturn_example():
284 a = 5
285 b = 5
286 if a == b:
287 b = a+1
288 else:
289 pass
290
291 ireturn_example.events = [(0, 'call'),
292 (1, 'line'),
293 (2, 'line'),
294 (3, 'line'),
295 (4, 'line'),
296 (4, 'return')]
297
298
299 def tightloop_example():
300 items = range(0, 3)
301 try:
302 i = 0
303 while 1:
304 b = items[i]; i+=1
305 except IndexError:
306 pass
307
308 tightloop_example.events = [(0, 'call'),
309 (1, 'line'),
310 (2, 'line'),
311 (3, 'line'),
312 (4, 'line'),
313 (5, 'line'),
314 (4, 'line'),
315 (5, 'line'),
316 (4, 'line'),
317 (5, 'line'),
318 (4, 'line'),
319 (5, 'line'),
320 (5, 'exception'),
321 (6, 'line'),
322 (7, 'line'),
323 (7, 'return')]
324
325
326 def tighterloop_example():
327 items = range(1, 4)
328 try:
329 i = 0
330 while 1: i = items[i]
331 except IndexError:
332 pass
333
334 tighterloop_example.events = [(0, 'call'),
335 (1, 'line'),
336 (2, 'line'),
337 (3, 'line'),
338 (4, 'line'),
339 (4, 'line'),
340 (4, 'line'),
341 (4, 'line'),
342 (4, 'exception'),
343 (5, 'line'),
344 (6, 'line'),
345 (6, 'return')]
346
347
348 def generator_function():
349 try:
350 yield True
351 "continued"
352 finally:
353 "finally"
354
355 def generator_example():
356 # any() will leave the generator before its end
357 x = any(generator_function()); gc.collect()
358 for x in range(10):
359 y = x
360
361 generator_example.events = ([(0, 'call'),
362 (2, 'line'),
363 (-7, 'call'),
364 (-6, 'line'),
365 (-5, 'line'),
366 (-5, 'return'),
367 (-5, 'call'),
368 (-5, 'exception'),
369 (-2, 'line'),
370 (-2, 'return')] +
371 [(3, 'line'), (4, 'line')] * 10 +
372 [(3, 'line'), (3, 'return')])
373
374
375 # ---------------------------------------------------------------------------
376 # TraceTestCase tests
377 # ---------------------------------------------------------------------------
378
379 def test_set_and_retrieve_none():
380 sys.settrace(None)
381 assert sys.gettrace() is None
382
383
384 def test_set_and_retrieve_func():
385 def fn(*args):
386 pass
387 sys.settrace(fn)
388 try:
389 assert sys.gettrace() is fn
390 finally:
391 sys.settrace(None)
392
393
394 def test_01_basic():
395 run_test(basic)
396
397 def test_02_arigo0():
398 run_test(arigo_example0)
399
400 def test_02_arigo1():
401 run_test(arigo_example1)
402
403 def test_02_arigo2():
404 run_test(arigo_example2)
405
406 def test_03_one_instr():
407 run_test(one_instr_line)
408
409 def test_04_no_pop_blocks():
410 run_test(no_pop_blocks)
411
412 def test_05_no_pop_tops():
413 run_test(no_pop_tops)
414
415 def test_06_call():
416 run_test(_call)
417
418 def test_07_raise():
419 run_test(_test_raise)
420
421 def test_08_settrace_and_return():
422 run_test2(settrace_and_return)
423
424 def test_09_settrace_and_raise():
425 run_test2(settrace_and_raise)
426
427 def test_10_ireturn():
428 run_test(ireturn_example)
429
430 def test_11_tightloop():
431 run_test(tightloop_example)
432
433 def test_12_tighterloop():
434 run_test(tighterloop_example)
435
436
437 def test_13_genexp():
438 using_gc = gc.isenabled()
439 if not using_gc:
440 gc.enable()
441 gc.collect()
442 try:
443 run_test(generator_example)
444 tracer = Tracer()
445 sys.settrace(tracer.traceWithGenexp)
446 generator_example()
447 sys.settrace(None)
448 compare_events(generator_example.__code__.co_firstlineno,
449 tracer.events, generator_example.events)
450 finally:
451 if not using_gc:
452 gc.disable()
453
454
455 def test_14_onliner_if():
456 def onliners():
457 if True: x=False
458 else: x=True
459 return 0
460 run_and_compare(onliners,
461 [(0, 'call'),
462 (1, 'line'),
463 (3, 'line'),
464 (3, 'return')])
465
466
467 def test_15_loops():
468 def for_example():
469 for x in range(2):
470 pass
471 run_and_compare(for_example,
472 [(0, 'call'),
473 (1, 'line'),
474 (2, 'line'),
475 (1, 'line'),
476 (2, 'line'),
477 (1, 'line'),
478 (1, 'return')])
479
480 def while_example():
481 # While expression should be traced on every loop
482 x = 2
483 while x > 0:
484 x -= 1
485 run_and_compare(while_example,
486 [(0, 'call'),
487 (2, 'line'),
488 (3, 'line'),
489 (4, 'line'),
490 (3, 'line'),
491 (4, 'line'),
492 (3, 'line'),
493 (3, 'return')])
494
495
496 def test_16_blank_lines():
497 namespace = {}
498 exec("def f():\n" + "\n" * 256 + " pass", namespace)
499 run_and_compare(namespace["f"],
500 [(0, 'call'),
501 (257, 'line'),
502 (257, 'return')])
503
504
505 def test_17_none_f_trace():
506 def func():
507 sys._getframe().f_trace = None
508 lineno = 2
509 run_and_compare(func,
510 [(0, 'call'),
511 (1, 'line')])
512
513
514 def test_18_except_with_name():
515 def func():
516 try:
517 try:
518 raise Exception
519 except Exception as e:
520 raise
521 x = "Something"
522 y = "Something"
523 except Exception:
524 pass
525 run_and_compare(func,
526 [(0, 'call'),
527 (1, 'line'),
528 (2, 'line'),
529 (3, 'line'),
530 (3, 'exception'),
531 (4, 'line'),
532 (5, 'line'),
533 (8, 'line'),
534 (9, 'line'),
535 (9, 'return')])
536
537
538 def test_19_except_with_finally():
539 def func():
540 try:
541 try:
542 raise Exception
543 finally:
544 y = "Something"
545 except Exception:
546 b = 23
547 run_and_compare(func,
548 [(0, 'call'),
549 (1, 'line'),
550 (2, 'line'),
551 (3, 'line'),
552 (3, 'exception'),
553 (5, 'line'),
554 (6, 'line'),
555 (7, 'line'),
556 (7, 'return')])
557
558
559 def test_21_repeated_pass():
560 def func():
561 pass
562 pass
563 run_and_compare(func,
564 [(0, 'call'),
565 (1, 'line'),
566 (2, 'line'),
567 (2, 'return')])
568
569
570 def test_loop_in_try_except():
571 def func():
572 try:
573 for i in []: pass
574 return 1
575 except:
576 return 2
577 run_and_compare(func,
578 [(0, 'call'),
579 (1, 'line'),
580 (2, 'line'),
581 (3, 'line'),
582 (3, 'return')])
583
584
585 def test_try_except_no_exception():
586 def func():
587 try:
588 2
589 except:
590 4
591 else:
592 6
593 if False:
594 8
595 else:
596 10
597 if func.__name__ == 'Fred':
598 12
599 finally:
600 14
601 run_and_compare(func,
602 [(0, 'call'),
603 (1, 'line'),
604 (2, 'line'),
605 (6, 'line'),
606 (7, 'line'),
607 (10, 'line'),
608 (11, 'line'),
609 (14, 'line'),
610 (14, 'return')])
611
612
613 def test_try_exception_in_else():
614 def func():
615 try:
616 try:
617 3
618 except:
619 5
620 else:
621 7
622 raise Exception
623 finally:
624 10
625 except:
626 12
627 finally:
628 14
629 run_and_compare(func,
630 [(0, 'call'),
631 (1, 'line'),
632 (2, 'line'),
633 (3, 'line'),
634 (7, 'line'),
635 (8, 'line'),
636 (8, 'exception'),
637 (10, 'line'),
638 (11, 'line'),
639 (12, 'line'),
640 (14, 'line'),
641 (14, 'return')])
642
643
644 def test_nested_loops():
645 def func():
646 for i in range(2):
647 for j in range(2):
648 a = i + j
649 return a == 1
650 run_and_compare(func,
651 [(0, 'call'),
652 (1, 'line'),
653 (2, 'line'),
654 (3, 'line'),
655 (2, 'line'),
656 (3, 'line'),
657 (2, 'line'),
658 (1, 'line'),
659 (2, 'line'),
660 (3, 'line'),
661 (2, 'line'),
662 (3, 'line'),
663 (2, 'line'),
664 (1, 'line'),
665 (4, 'line'),
666 (4, 'return')])
667
668
669 def test_if_break():
670 def func():
671 seq = [1, 0]
672 while seq:
673 n = seq.pop()
674 if n:
675 break
676 else:
677 n = 99
678 return n
679 run_and_compare(func,
680 [(0, 'call'),
681 (1, 'line'),
682 (2, 'line'),
683 (3, 'line'),
684 (4, 'line'),
685 (2, 'line'),
686 (3, 'line'),
687 (4, 'line'),
688 (5, 'line'),
689 (8, 'line'),
690 (8, 'return')])
691
692
693 def test_break_through_finally():
694 def func():
695 a, c, d, i = 1, 1, 1, 99
696 try:
697 for i in range(3):
698 try:
699 a = 5
700 if i > 0:
701 break
702 a = 8
703 finally:
704 c = 10
705 except:
706 d = 12
707 assert a == 5 and c == 10 and d == 1
708 run_and_compare(func,
709 [(0, 'call'),
710 (1, 'line'),
711 (2, 'line'),
712 (3, 'line'),
713 (4, 'line'),
714 (5, 'line'),
715 (6, 'line'),
716 (8, 'line'),
717 (10, 'line'),
718 (3, 'line'),
719 (4, 'line'),
720 (5, 'line'),
721 (6, 'line'),
722 (7, 'line'),
723 (10, 'line'),
724 (13, 'line'),
725 (13, 'return')])
726
727
728 def test_continue_through_finally():
729 def func():
730 a, b, c, d, i = 1, 1, 1, 1, 99
731 try:
732 for i in range(2):
733 try:
734 a = 5
735 if i > 0:
736 continue
737 b = 8
738 finally:
739 c = 10
740 except:
741 d = 12
742 assert (a, b, c, d) == (5, 8, 10, 1)
743 run_and_compare(func,
744 [(0, 'call'),
745 (1, 'line'),
746 (2, 'line'),
747 (3, 'line'),
748 (4, 'line'),
749 (5, 'line'),
750 (6, 'line'),
751 (8, 'line'),
752 (10, 'line'),
753 (3, 'line'),
754 (4, 'line'),
755 (5, 'line'),
756 (6, 'line'),
757 (7, 'line'),
758 (10, 'line'),
759 (3, 'line'),
760 (13, 'line'),
761 (13, 'return')])
762
763
764 def test_return_through_finally():
765 def func():
766 try:
767 return 2
768 finally:
769 4
770 run_and_compare(func,
771 [(0, 'call'),
772 (1, 'line'),
773 (2, 'line'),
774 (4, 'line'),
775 (4, 'return')])
776
777
778 def test_try_except_with_wrong_type():
779 def func():
780 try:
781 2/0
782 except IndexError:
783 4
784 finally:
785 return 6
786 run_and_compare(func,
787 [(0, 'call'),
788 (1, 'line'),
789 (2, 'line'),
790 (2, 'exception'),
791 (3, 'line'),
792 (6, 'line'),
793 (6, 'return')])
794
795
796 def test_break_to_continue1():
797 def func():
798 TRUE = 1
799 x = [1]
800 while x:
801 x.pop()
802 while TRUE:
803 break
804 continue
805 run_and_compare(func,
806 [(0, 'call'),
807 (1, 'line'),
808 (2, 'line'),
809 (3, 'line'),
810 (4, 'line'),
811 (5, 'line'),
812 (6, 'line'),
813 (7, 'line'),
814 (3, 'line'),
815 (3, 'return')])
816
817
818 def test_break_to_continue2():
819 def func():
820 TRUE = 1
821 x = [1]
822 while x:
823 x.pop()
824 while TRUE:
825 break
826 else:
827 continue
828 run_and_compare(func,
829 [(0, 'call'),
830 (1, 'line'),
831 (2, 'line'),
832 (3, 'line'),
833 (4, 'line'),
834 (5, 'line'),
835 (6, 'line'),
836 (3, 'line'),
837 (3, 'return')])
838
839
840 def test_break_to_break():
841 def func():
842 TRUE = 1
843 while TRUE:
844 while TRUE:
845 break
846 break
847 run_and_compare(func,
848 [(0, 'call'),
849 (1, 'line'),
850 (2, 'line'),
851 (3, 'line'),
852 (4, 'line'),
853 (5, 'line'),
854 (5, 'return')])
855
856
857 def test_nested_ifs():
858 def func():
859 a = b = 1
860 if a == 1:
861 if b == 1:
862 x = 4
863 else:
864 y = 6
865 else:
866 z = 8
867 run_and_compare(func,
868 [(0, 'call'),
869 (1, 'line'),
870 (2, 'line'),
871 (3, 'line'),
872 (4, 'line'),
873 (4, 'return')])
874
875
876 def test_nested_ifs_with_and():
877 A = B = True
878 C = False
879
880 def func():
881 if A:
882 if B:
883 if C:
884 if D:
885 return False
886 else:
887 return False
888 elif E and F:
889 return True
890 run_and_compare(func,
891 [(0, 'call'),
892 (1, 'line'),
893 (2, 'line'),
894 (3, 'line'),
895 (3, 'return')])
896
897
898 def test_nested_try_if():
899 def func():
900 x = "hello"
901 try:
902 3/0
903 except ZeroDivisionError:
904 if x == 'raise':
905 raise ValueError()
906 f = 7
907 run_and_compare(func,
908 [(0, 'call'),
909 (1, 'line'),
910 (2, 'line'),
911 (3, 'line'),
912 (3, 'exception'),
913 (4, 'line'),
914 (5, 'line'),
915 (7, 'line'),
916 (7, 'return')])
917
918
919 def test_if_false_in_with():
920 class C:
921 def __enter__(self):
922 return self
923 def __exit__(*args):
924 pass
925
926 def func():
927 with C():
928 if False:
929 pass
930 run_and_compare(func,
931 [(0, 'call'),
932 (1, 'line'),
933 (-5, 'call'),
934 (-4, 'line'),
935 (-4, 'return'),
936 (2, 'line'),
937 (1, 'line'),
938 (-3, 'call'),
939 (-2, 'line'),
940 (-2, 'return'),
941 (1, 'return')])
942
943
944 def test_if_false_in_try_except():
945 def func():
946 try:
947 if False:
948 pass
949 except Exception:
950 X
951 run_and_compare(func,
952 [(0, 'call'),
953 (1, 'line'),
954 (2, 'line'),
955 (2, 'return')])
956
957
958 def test_implicit_return_in_class():
959 def func():
960 class A:
961 if 3 < 9:
962 a = 1
963 else:
964 a = 2
965 run_and_compare(func,
966 [(0, 'call'),
967 (1, 'line'),
968 (1, 'call'),
969 (1, 'line'),
970 (2, 'line'),
971 (3, 'line'),
972 (3, 'return'),
973 (1, 'return')])
974
975
976 def test_try_in_try():
977 def func():
978 try:
979 try:
980 pass
981 except Exception as ex:
982 pass
983 except Exception:
984 pass
985 run_and_compare(func,
986 [(0, 'call'),
987 (1, 'line'),
988 (2, 'line'),
989 (3, 'line'),
990 (3, 'return')])
991
992
993 def test_try_in_try_with_exception():
994 def func():
995 try:
996 try:
997 raise TypeError
998 except ValueError as ex:
999 5
1000 except TypeError:
1001 7
1002 run_and_compare(func,
1003 [(0, 'call'),
1004 (1, 'line'),
1005 (2, 'line'),
1006 (3, 'line'),
1007 (3, 'exception'),
1008 (4, 'line'),
1009 (6, 'line'),
1010 (7, 'line'),
1011 (7, 'return')])
1012
1013 def func2():
1014 try:
1015 try:
1016 raise ValueError
1017 except ValueError as ex:
1018 5
1019 except TypeError:
1020 7
1021 run_and_compare(func2,
1022 [(0, 'call'),
1023 (1, 'line'),
1024 (2, 'line'),
1025 (3, 'line'),
1026 (3, 'exception'),
1027 (4, 'line'),
1028 (5, 'line'),
1029 (5, 'return')])
1030
1031
1032 def test_if_in_if_in_if():
1033 def func(a=0, p=1, z=1):
1034 if p:
1035 if a:
1036 if z:
1037 pass
1038 else:
1039 pass
1040 else:
1041 pass
1042 run_and_compare(func,
1043 [(0, 'call'),
1044 (1, 'line'),
1045 (2, 'line'),
1046 (2, 'return')])
1047
1048
1049 def test_early_exit_with():
1050 class C:
1051 def __enter__(self):
1052 return self
1053 def __exit__(*args):
1054 pass
1055
1056 def func_break():
1057 for i in (1,2):
1058 with C():
1059 break
1060 pass
1061
1062 def func_return():
1063 with C():
1064 return
1065
1066 run_and_compare(func_break,
1067 [(0, 'call'),
1068 (1, 'line'),
1069 (2, 'line'),
1070 (-5, 'call'),
1071 (-4, 'line'),
1072 (-4, 'return'),
1073 (3, 'line'),
1074 (2, 'line'),
1075 (-3, 'call'),
1076 (-2, 'line'),
1077 (-2, 'return'),
1078 (4, 'line'),
1079 (4, 'return')])
1080
1081 run_and_compare(func_return,
1082 [(0, 'call'),
1083 (1, 'line'),
1084 (-11, 'call'),
1085 (-10, 'line'),
1086 (-10, 'return'),
1087 (2, 'line'),
1088 (1, 'line'),
1089 (-9, 'call'),
1090 (-8, 'line'),
1091 (-8, 'return'),
1092 (1, 'return')])
1093
1094
1095 def test_flow_converges_on_same_line():
1096 def foo(x):
1097 if x:
1098 try:
1099 1/(x - 1)
1100 except ZeroDivisionError:
1101 pass
1102 return x
1103
1104 def func():
1105 for i in range(2):
1106 foo(i)
1107 run_and_compare(func,
1108 [(0, 'call'),
1109 (1, 'line'),
1110 (2, 'line'),
1111 (-8, 'call'),
1112 (-7, 'line'),
1113 (-2, 'line'),
1114 (-2, 'return'),
1115 (1, 'line'),
1116 (2, 'line'),
1117 (-8, 'call'),
1118 (-7, 'line'),
1119 (-6, 'line'),
1120 (-5, 'line'),
1121 (-5, 'exception'),
1122 (-4, 'line'),
1123 (-3, 'line'),
1124 (-2, 'line'),
1125 (-2, 'return'),
1126 (1, 'line'),
1127 (1, 'return')])
1128
1129
1130 def test_no_tracing_of_named_except_cleanup():
1131 def func():
1132 x = 0
1133 try:
1134 1/x
1135 except ZeroDivisionError as error:
1136 if x:
1137 raise
1138 return "done"
1139 run_and_compare(func,
1140 [(0, 'call'),
1141 (1, 'line'),
1142 (2, 'line'),
1143 (3, 'line'),
1144 (3, 'exception'),
1145 (4, 'line'),
1146 (5, 'line'),
1147 (7, 'line'),
1148 (7, 'return')])
1149
1150
1151 def test_tracing_exception_raised_in_with():
1152 class NullCtx:
1153 def __enter__(self):
1154 return self
1155 def __exit__(self, *excinfo):
1156 pass
1157
1158 def func():
1159 try:
1160 with NullCtx():
1161 1/0
1162 except ZeroDivisionError:
1163 pass
1164 run_and_compare(func,
1165 [(0, 'call'),
1166 (1, 'line'),
1167 (2, 'line'),
1168 (-5, 'call'),
1169 (-4, 'line'),
1170 (-4, 'return'),
1171 (3, 'line'),
1172 (3, 'exception'),
1173 (2, 'line'),
1174 (-3, 'call'),
1175 (-2, 'line'),
1176 (-2, 'return'),
1177 (4, 'line'),
1178 (5, 'line'),
1179 (5, 'return')])
1180
1181
1182 def test_try_except_star_no_exception():
1183 def func():
1184 try:
1185 2
1186 except* Exception:
1187 4
1188 else:
1189 6
1190 if False:
1191 8
1192 else:
1193 10
1194 if func.__name__ == 'Fred':
1195 12
1196 finally:
1197 14
1198 run_and_compare(func,
1199 [(0, 'call'),
1200 (1, 'line'),
1201 (2, 'line'),
1202 (6, 'line'),
1203 (7, 'line'),
1204 (10, 'line'),
1205 (11, 'line'),
1206 (14, 'line'),
1207 (14, 'return')])
1208
1209
1210 def test_try_except_star_named_no_exception():
1211 def func():
1212 try:
1213 2
1214 except* Exception as e:
1215 4
1216 else:
1217 6
1218 finally:
1219 8
1220 run_and_compare(func,
1221 [(0, 'call'),
1222 (1, 'line'),
1223 (2, 'line'),
1224 (6, 'line'),
1225 (8, 'line'),
1226 (8, 'return')])
1227
1228
1229 def test_try_except_star_exception_caught():
1230 def func():
1231 try:
1232 raise ValueError(2)
1233 except* ValueError:
1234 4
1235 else:
1236 6
1237 finally:
1238 8
1239 run_and_compare(func,
1240 [(0, 'call'),
1241 (1, 'line'),
1242 (2, 'line'),
1243 (2, 'exception'),
1244 (3, 'line'),
1245 (4, 'line'),
1246 (8, 'line'),
1247 (8, 'return')])
1248
1249
1250 def test_try_except_star_named_exception_caught():
1251 def func():
1252 try:
1253 raise ValueError(2)
1254 except* ValueError as e:
1255 4
1256 else:
1257 6
1258 finally:
1259 8
1260 run_and_compare(func,
1261 [(0, 'call'),
1262 (1, 'line'),
1263 (2, 'line'),
1264 (2, 'exception'),
1265 (3, 'line'),
1266 (4, 'line'),
1267 (8, 'line'),
1268 (8, 'return')])
1269
1270
1271 def test_try_except_star_exception_not_caught():
1272 def func():
1273 try:
1274 try:
1275 raise ValueError(3)
1276 except* TypeError:
1277 5
1278 except ValueError:
1279 7
1280 run_and_compare(func,
1281 [(0, 'call'),
1282 (1, 'line'),
1283 (2, 'line'),
1284 (3, 'line'),
1285 (3, 'exception'),
1286 (4, 'line'),
1287 (6, 'line'),
1288 (7, 'line'),
1289 (7, 'return')])
1290
1291
1292 def test_try_except_star_named_exception_not_caught():
1293 def func():
1294 try:
1295 try:
1296 raise ValueError(3)
1297 except* TypeError as e:
1298 5
1299 except ValueError:
1300 7
1301 run_and_compare(func,
1302 [(0, 'call'),
1303 (1, 'line'),
1304 (2, 'line'),
1305 (3, 'line'),
1306 (3, 'exception'),
1307 (4, 'line'),
1308 (6, 'line'),
1309 (7, 'line'),
1310 (7, 'return')])
1311
1312
1313 def test_notrace_lambda():
1314 def func():
1315 1
1316 lambda x: 2
1317 3
1318 run_and_compare(func,
1319 [(0, 'call'),
1320 (1, 'line'),
1321 (2, 'line'),
1322 (3, 'line'),
1323 (3, 'return')])
1324
1325
1326 def test_class_creation_with_docstrings():
1327 def func():
1328 class Class_1:
1329 ''' the docstring. 2'''
1330 def __init__(self):
1331 ''' Another docstring. 4'''
1332 self.a = 5
1333 run_and_compare(func,
1334 [(0, 'call'),
1335 (1, 'line'),
1336 (1, 'call'),
1337 (1, 'line'),
1338 (2, 'line'),
1339 (3, 'line'),
1340 (3, 'return'),
1341 (1, 'return')])
1342
1343
1344 def test_settrace_error():
1345 raised = False
1346 def error_once(frame, event, arg):
1347 nonlocal raised
1348 if not raised:
1349 raised = True
1350 raise Exception
1351 return error_once
1352
1353 try:
1354 sys._getframe().f_trace = error_once
1355 sys.settrace(error_once)
1356 len([])
1357 except Exception as ex:
1358 count = 0
1359 tb = ex.__traceback__
1360 while tb:
1361 if tb.tb_frame.f_code.co_name == "test_settrace_error":
1362 count += 1
1363 tb = tb.tb_next
1364 if count == 0:
1365 raise AssertionError("Traceback is missing frame")
1366 elif count > 1:
1367 raise AssertionError("Traceback has frame more than once")
1368 else:
1369 raise AssertionError("No exception raised")
1370 finally:
1371 sys.settrace(None)
1372
1373
1374 # ---------------------------------------------------------------------------
1375 # RaisingTraceFuncTestCase tests
1376 # ---------------------------------------------------------------------------
1377
1378 def _raiser(raiseOnEvent):
1379 def trace(frame, event, arg):
1380 if event == raiseOnEvent:
1381 raise ValueError
1382 return trace
1383 return trace
1384
1385 def _f_for_raising(raiseOnEvent):
1386 if raiseOnEvent == 'exception':
1387 x = 0
1388 y = 1/x
1389 else:
1390 return 1
1391
1392 def _run_test_for_event(event):
1393 trace = _raiser(event)
1394 try:
1395 for i in range(sys.getrecursionlimit() + 1):
1396 sys.settrace(trace)
1397 try:
1398 _f_for_raising(event)
1399 except ValueError:
1400 pass
1401 else:
1402 raise AssertionError("exception not raised!")
1403 except RuntimeError:
1404 raise AssertionError("recursion counter not reset")
1405 finally:
1406 sys.settrace(None)
1407
1408 def test_raising_on_call():
1409 _run_test_for_event('call')
1410
1411 def test_raising_on_line():
1412 _run_test_for_event('line')
1413
1414 def test_raising_on_return():
1415 _run_test_for_event('return')
1416
1417 def test_raising_on_exception():
1418 _run_test_for_event('exception')
1419
1420
1421 def test_raising_trash_stack():
1422 def f():
1423 for i in range(5):
1424 print(i)
1425
1426 def g(frame, why, extra):
1427 if (why == 'line' and
1428 frame.f_lineno == f.__code__.co_firstlineno + 2):
1429 raise RuntimeError("i am crashing")
1430 return g
1431
1432 sys.settrace(g)
1433 try:
1434 f()
1435 except RuntimeError:
1436 gc.collect()
1437 else:
1438 raise AssertionError("exception not propagated")
1439 finally:
1440 sys.settrace(None)
1441
1442
1443 def test_raising_exception_arguments():
1444 def f():
1445 x = 0
1446 x.no_such_attr
1447
1448 results = []
1449 def g(frame, event, arg):
1450 if event == 'exception':
1451 type_, exception, trace = arg
1452 results.append(isinstance(exception, Exception))
1453 return g
1454
1455 existing = sys.gettrace()
1456 try:
1457 sys.settrace(g)
1458 try:
1459 f()
1460 except AttributeError:
1461 pass
1462 finally:
1463 sys.settrace(existing)
1464 assert results and all(results)
1465
1466
1467 def test_raising_line_event_raises_before_opcode_event():
1468 exception = ValueError("BOOM!")
1469 def trace(frame, event, arg):
1470 if event == "line":
1471 raise exception
1472 frame.f_trace_opcodes = True
1473 return trace
1474 def f():
1475 pass
1476 with pytest.raises(ValueError) as caught:
1477 sys.settrace(trace)
1478 f()
1479 assert caught.value is exception
1480 sys.settrace(None)
1481
1482
1483 # ---------------------------------------------------------------------------
1484 # JumpTestCase infrastructure
1485 # ---------------------------------------------------------------------------
1486
1487 class JumpTracer:
1488 """Defines a trace function that jumps from one place to another."""
1489
1490 def __init__(self, function, jumpFrom, jumpTo, event='line', decorated=False):
1491 self.code = function.__code__
1492 self.jumpFrom = jumpFrom
1493 self.jumpTo = jumpTo
1494 self.event = event
1495 self.firstLine = None if decorated else self.code.co_firstlineno
1496 self.done = False
1497
1498 def trace(self, frame, event, arg):
1499 if self.done:
1500 return
1501 if (self.firstLine is None and frame.f_code == self.code and
1502 event == 'line'):
1503 self.firstLine = frame.f_lineno - 1
1504 if (event == self.event and self.firstLine is not None and
1505 frame.f_lineno == self.firstLine + self.jumpFrom):
1506 f = frame
1507 while f is not None and f.f_code != self.code:
1508 f = f.f_back
1509 if f is not None:
1510 try:
1511 frame.f_lineno = self.firstLine + self.jumpTo
1512 except TypeError:
1513 frame.f_lineno = self.jumpTo
1514 self.done = True
1515 return self.trace
1516
1517
1518 # PyPy uses "body of a with statement" in the error message
1519 _no_jump_into_with_error = (ValueError, "body of a with statement")
1520
1521
1522 def run_jump_test(func, jumpFrom, jumpTo, expected, error=None, event='line'):
1523 tracer = JumpTracer(func, jumpFrom, jumpTo, event)
1524 sys.settrace(tracer.trace)
1525 output = []
1526 try:
1527 if error is None:
1528 func(output)
1529 else:
1530 exc_type, exc_msg = error
1531 with pytest.raises(exc_type, match=exc_msg):
1532 func(output)
1533 finally:
1534 sys.settrace(None)
1535 assert output == expected, "Expected %r, got %r" % (expected, output)
1536
1537
1538 def run_jump_async_test(func, jumpFrom, jumpTo, expected, error=None, event='line'):
1539 import asyncio
1540 tracer = JumpTracer(func, jumpFrom, jumpTo, event)
1541 sys.settrace(tracer.trace)
1542 output = []
1543 try:
1544 if error is None:
1545 asyncio.run(func(output))
1546 else:
1547 exc_type, exc_msg = error
1548 with pytest.raises(exc_type, match=exc_msg):
1549 asyncio.run(func(output))
1550 finally:
1551 sys.settrace(None)
1552 assert output == expected, "Expected %r, got %r" % (expected, output)
1553
1554
1555 def no_jump_to_non_integers(output):
1556 try:
1557 output.append(2)
1558 except ValueError as e:
1559 output.append('integer' in str(e))
1560
1561
1562 def no_jump_without_trace_function():
1563 try:
1564 previous_frame = sys._getframe().f_back
1565 previous_frame.f_lineno = previous_frame.f_lineno
1566 except ValueError as e:
1567 if 'trace' not in str(e):
1568 raise
1569 else:
1570 raise AssertionError("Trace-function-less jump failed to fail")
1571
1572
1573 # ---------------------------------------------------------------------------
1574 # JumpTestCase tests (allowed jumps)
1575 # ---------------------------------------------------------------------------
1576
1577 def test_jump_simple_forwards():
1578 def func(output):
1579 output.append(1)
1580 output.append(2)
1581 output.append(3)
1582 run_jump_test(func, 1, 3, [3])
1583
1584 def test_jump_simple_backwards():
1585 def func(output):
1586 output.append(1)
1587 output.append(2)
1588 run_jump_test(func, 2, 1, [1, 1, 2])
1589
1590 def test_jump_is_none_forwards():
1591 def func(output):
1592 x = None
1593 if x is None:
1594 output.append(3)
1595 else:
1596 output.append(5)
1597 run_jump_test(func, 1, 4, [5])
1598
1599 def test_jump_is_none_backwards():
1600 def func(output):
1601 x = None
1602 if x is None:
1603 output.append(3)
1604 else:
1605 output.append(5)
1606 output.append(6)
1607 run_jump_test(func, 6, 5, [3, 5, 6])
1608
1609 def test_jump_is_not_none_forwards():
1610 def func(output):
1611 x = None
1612 if x is not None:
1613 output.append(3)
1614 else:
1615 output.append(5)
1616 run_jump_test(func, 1, 4, [5])
1617
1618 def test_jump_is_not_none_backwards():
1619 def func(output):
1620 x = None
1621 if x is not None:
1622 output.append(3)
1623 else:
1624 output.append(5)
1625 output.append(6)
1626 run_jump_test(func, 6, 5, [5, 5, 6])
1627
1628 def test_jump_out_of_block_forwards():
1629 def func(output):
1630 for i in 1, 2:
1631 output.append(2)
1632 for j in [3]:
1633 output.append(4)
1634 output.append(5)
1635 run_jump_test(func, 3, 5, [2, 5])
1636
1637 def test_jump_out_of_block_backwards():
1638 def func(output):
1639 output.append(1)
1640 for i in [1]:
1641 output.append(3)
1642 for j in [2]:
1643 output.append(5)
1644 output.append(6)
1645 output.append(7)
1646 run_jump_test(func, 6, 1, [1, 3, 5, 1, 3, 5, 6, 7])
1647
1648 def test_jump_to_codeless_line():
1649 def func(output):
1650 output.append(1)
1651 # Jumping to this line should skip to the next one.
1652 output.append(3)
1653 run_jump_test(func, 1, 2, [3])
1654
1655 def test_jump_to_same_line():
1656 def func(output):
1657 output.append(1)
1658 output.append(2)
1659 output.append(3)
1660 run_jump_test(func, 2, 2, [1, 2, 3])
1661
1662 def test_jump_in_nested_finally():
1663 def func(output):
1664 try:
1665 output.append(2)
1666 finally:
1667 output.append(4)
1668 try:
1669 output.append(6)
1670 finally:
1671 output.append(8)
1672 output.append(9)
1673 run_jump_test(func, 4, 9, [2, 9])
1674
1675 def test_jump_in_nested_finally_2():
1676 def func(output):
1677 try:
1678 output.append(2)
1679 1/0
1680 return
1681 finally:
1682 output.append(6)
1683 output.append(7)
1684 output.append(8)
1685 run_jump_test(func, 6, 7, [2, 7], (ZeroDivisionError, ''))
1686
1687 def test_jump_in_nested_finally_3():
1688 def func(output):
1689 try:
1690 output.append(2)
1691 1/0
1692 return
1693 finally:
1694 output.append(6)
1695 try:
1696 output.append(8)
1697 finally:
1698 output.append(10)
1699 output.append(11)
1700 output.append(12)
1701 run_jump_test(func, 6, 11, [2, 11], (ZeroDivisionError, ''))
1702
1703 def test_no_jump_infinite_while_loop():
1704 def func(output):
1705 output.append(1)
1706 while True:
1707 output.append(3)
1708 output.append(4)
1709 run_jump_test(func, 3, 4, [1], (ValueError, 'after'))
1710
1711 def test_jump_forwards_into_while_block():
1712 def func(output):
1713 i = 1
1714 output.append(2)
1715 while i <= 2:
1716 output.append(4)
1717 i += 1
1718 run_jump_test(func, 2, 4, [4, 4])
1719
1720 def test_jump_backwards_into_while_block():
1721 def func(output):
1722 i = 1
1723 while i <= 2:
1724 output.append(3)
1725 i += 1
1726 output.append(5)
1727 run_jump_test(func, 5, 3, [3, 3, 3, 5])
1728
1729 def test_jump_forwards_out_of_with_block():
1730 def func(output):
1731 with tracecontext(output, 1):
1732 output.append(2)
1733 output.append(3)
1734 run_jump_test(func, 2, 3, [1, 3])
1735
1736 def test_jump_backwards_out_of_with_block():
1737 def func(output):
1738 output.append(1)
1739 with tracecontext(output, 2):
1740 output.append(3)
1741 run_jump_test(func, 3, 1, [1, 2, 1, 2, 3, -2])
1742
1743 def test_jump_forwards_out_of_try_finally_block():
1744 def func(output):
1745 try:
1746 output.append(2)
1747 finally:
1748 output.append(4)
1749 output.append(5)
1750 run_jump_test(func, 2, 5, [5])
1751
1752 def test_jump_backwards_out_of_try_finally_block():
1753 def func(output):
1754 output.append(1)
1755 try:
1756 output.append(3)
1757 finally:
1758 output.append(5)
1759 run_jump_test(func, 3, 1, [1, 1, 3, 5])
1760
1761 def test_jump_forwards_out_of_try_except_block():
1762 def func(output):
1763 try:
1764 output.append(2)
1765 except:
1766 output.append(4)
1767 raise
1768 output.append(6)
1769 run_jump_test(func, 2, 6, [6])
1770
1771 def test_jump_backwards_out_of_try_except_block():
1772 def func(output):
1773 output.append(1)
1774 try:
1775 output.append(3)
1776 except:
1777 output.append(5)
1778 raise
1779 run_jump_test(func, 3, 1, [1, 1, 3])
1780
1781 def test_jump_between_except_blocks():
1782 def func(output):
1783 try:
1784 1/0
1785 except ZeroDivisionError:
1786 output.append(4)
1787 output.append(5)
1788 except FloatingPointError:
1789 output.append(7)
1790 output.append(8)
1791 run_jump_test(func, 5, 7, [4, 7, 8])
1792
1793 def test_jump_from_except_to_finally():
1794 def func(output):
1795 try:
1796 1/0
1797 except ZeroDivisionError:
1798 output.append(4)
1799 output.append(5)
1800 finally:
1801 output.append(7)
1802 output.append(8)
1803 run_jump_test(func, 5, 7, [4, 7, 8])
1804
1805 def test_jump_within_except_block():
1806 def func(output):
1807 try:
1808 1/0
1809 except:
1810 output.append(4)
1811 output.append(5)
1812 output.append(6)
1813 output.append(7)
1814 run_jump_test(func, 5, 6, [4, 6, 7])
1815
1816 def test_jump_over_try_except():
1817 def func(output):
1818 output.append(1)
1819 try:
1820 1 / 0
1821 except ZeroDivisionError as e:
1822 output.append(5)
1823 x = 42
1824 run_jump_test(func, 6, 1, [1, 5, 1, 5])
1825
1826 def test_jump_across_with():
1827 def func(output):
1828 output.append(1)
1829 with tracecontext(output, 2):
1830 output.append(3)
1831 with tracecontext(output, 4):
1832 output.append(5)
1833 run_jump_test(func, 2, 4, [1, 4, 5, -4])
1834
1835 def test_jump_out_of_with_block_within_for_block():
1836 def func(output):
1837 output.append(1)
1838 for i in [1]:
1839 with tracecontext(output, 3):
1840 output.append(4)
1841 output.append(5)
1842 output.append(6)
1843 run_jump_test(func, 4, 5, [1, 3, 5, 6])
1844
1845 def test_jump_out_of_with_block_within_with_block():
1846 def func(output):
1847 output.append(1)
1848 with tracecontext(output, 2):
1849 with tracecontext(output, 3):
1850 output.append(4)
1851 output.append(5)
1852 output.append(6)
1853 run_jump_test(func, 4, 5, [1, 2, 3, 5, -2, 6])
1854
1855 def test_jump_out_of_with_block_within_finally_block():
1856 def func(output):
1857 try:
1858 output.append(2)
1859 finally:
1860 with tracecontext(output, 4):
1861 output.append(5)
1862 output.append(6)
1863 output.append(7)
1864 run_jump_test(func, 5, 6, [2, 4, 6, 7])
1865
1866 def test_jump_out_of_complex_nested_blocks():
1867 def func(output):
1868 output.append(1)
1869 for i in [1]:
1870 output.append(3)
1871 for j in [1, 2]:
1872 output.append(5)
1873 try:
1874 for k in [1, 2]:
1875 output.append(8)
1876 finally:
1877 output.append(10)
1878 output.append(11)
1879 output.append(12)
1880 run_jump_test(func, 8, 11, [1, 3, 5, 11, 12])
1881
1882 def test_jump_out_of_with_assignment():
1883 def func(output):
1884 output.append(1)
1885 with tracecontext(output, 2) \
1886 as x:
1887 output.append(4)
1888 output.append(5)
1889 run_jump_test(func, 3, 5, [1, 2, 5])
1890
1891 def test_jump_over_return_in_try_finally_block():
1892 def func(output):
1893 output.append(1)
1894 try:
1895 output.append(3)
1896 if not output:
1897 return
1898 output.append(6)
1899 finally:
1900 output.append(8)
1901 output.append(9)
1902 run_jump_test(func, 3, 6, [1, 6, 8, 9])
1903
1904 def test_jump_over_break_in_try_finally_block():
1905 def func(output):
1906 output.append(1)
1907 while True:
1908 output.append(3)
1909 try:
1910 output.append(5)
1911 if not output:
1912 break
1913 output.append(8)
1914 finally:
1915 output.append(10)
1916 output.append(11)
1917 break
1918 output.append(13)
1919 run_jump_test(func, 5, 8, [1, 3, 8, 10, 11, 13])
1920
1921 def test_jump_over_for_block_before_else():
1922 def func(output):
1923 output.append(1)
1924 if not output:
1925 for i in [3]:
1926 output.append(4)
1927 else:
1928 output.append(6)
1929 output.append(7)
1930 output.append(8)
1931 run_jump_test(func, 1, 7, [7, 8])
1932
1933 def test_jump_forwards_into_try_finally_block():
1934 def func(output):
1935 output.append(1)
1936 try:
1937 output.append(3)
1938 finally:
1939 output.append(5)
1940 run_jump_test(func, 1, 3, [3, 5])
1941
1942 def test_jump_backwards_into_try_finally_block():
1943 def func(output):
1944 try:
1945 output.append(2)
1946 finally:
1947 output.append(4)
1948 output.append(5)
1949 run_jump_test(func, 5, 2, [2, 4, 2, 4, 5])
1950
1951 def test_jump_forwards_into_try_except_block():
1952 def func(output):
1953 output.append(1)
1954 try:
1955 output.append(3)
1956 except:
1957 output.append(5)
1958 raise
1959 run_jump_test(func, 1, 3, [3])
1960
1961 def test_jump_backwards_into_try_except_block():
1962 def func(output):
1963 try:
1964 output.append(2)
1965 except:
1966 output.append(4)
1967 raise
1968 output.append(6)
1969 run_jump_test(func, 6, 2, [2, 2, 6])
1970
1971 def test_jump_between_except_blocks_2():
1972 def func(output):
1973 try:
1974 1/0
1975 except ZeroDivisionError:
1976 output.append(4)
1977 output.append(5)
1978 except FloatingPointError as e:
1979 output.append(7)
1980 output.append(8)
1981 run_jump_test(func, 5, 7, [4, 7, 8])
1982
1983 def test_jump_into_finally_block():
1984 def func(output):
1985 output.append(1)
1986 try:
1987 output.append(3)
1988 finally:
1989 output.append(5)
1990 run_jump_test(func, 1, 5, [5])
1991
1992 def test_jump_into_finally_block_from_try_block():
1993 def func(output):
1994 try:
1995 output.append(2)
1996 output.append(3)
1997 finally:
1998 output.append(5)
1999 output.append(6)
2000 output.append(7)
2001 run_jump_test(func, 3, 6, [2, 6, 7])
2002
2003 def test_jump_out_of_finally_block():
2004 def func(output):
2005 output.append(1)
2006 try:
2007 output.append(3)
2008 finally:
2009 output.append(5)
2010 run_jump_test(func, 5, 1, [1, 3, 1, 3, 5])
2011
2012 def test_jump_between_with_blocks():
2013 def func(output):
2014 output.append(1)
2015 with tracecontext(output, 2):
2016 output.append(3)
2017 with tracecontext(output, 4):
2018 output.append(5)
2019 run_jump_test(func, 3, 5, [1, 2, 5, -2])
2020
2021
2022 # ---------------------------------------------------------------------------
2023 # JumpTestCase tests (not allowed)
2024 # ---------------------------------------------------------------------------
2025
2026 def test_no_jump_too_far_forwards():
2027 def func(output):
2028 output.append(1)
2029 output.append(2)
2030 run_jump_test(func, 2, 3, [1], (ValueError, 'after'))
2031
2032 def test_no_jump_too_far_backwards():
2033 def func(output):
2034 output.append(1)
2035 output.append(2)
2036 run_jump_test(func, 2, -2, [1], (ValueError, 'before'))
2037
2038 def test_no_jump_to_except_1():
2039 def func(output):
2040 try:
2041 output.append(2)
2042 except:
2043 output.append(4)
2044 raise
2045 run_jump_test(func, 2, 3, [4], (ValueError, 'except'))
2046
2047 def test_no_jump_to_except_2():
2048 def func(output):
2049 try:
2050 output.append(2)
2051 except ValueError:
2052 output.append(4)
2053 raise
2054 run_jump_test(func, 2, 3, [4], (ValueError, 'except'))
2055
2056 def test_no_jump_to_except_3():
2057 def func(output):
2058 try:
2059 output.append(2)
2060 except ValueError as e:
2061 output.append(4)
2062 raise e
2063 run_jump_test(func, 2, 3, [4], (ValueError, 'except'))
2064
2065 def test_no_jump_to_except_4():
2066 def func(output):
2067 try:
2068 output.append(2)
2069 except (ValueError, RuntimeError) as e:
2070 output.append(4)
2071 raise e
2072 run_jump_test(func, 2, 3, [4], (ValueError, 'except'))
2073
2074 def test_no_jump_forwards_into_for_block():
2075 def func(output):
2076 output.append(1)
2077 for i in 1, 2:
2078 output.append(3)
2079 run_jump_test(func, 1, 3, [], (ValueError, 'into'))
2080
2081 def test_no_jump_backwards_into_for_block():
2082 def func(output):
2083 for i in 1, 2:
2084 output.append(2)
2085 output.append(3)
2086 run_jump_test(func, 3, 2, [2, 2], (ValueError, 'into'))
2087
2088 def test_no_jump_forwards_into_with_block():
2089 def func(output):
2090 output.append(1)
2091 with tracecontext(output, 2):
2092 output.append(3)
2093 run_jump_test(func, 1, 3, [], _no_jump_into_with_error)
2094
2095 def test_no_jump_backwards_into_with_block():
2096 def func(output):
2097 with tracecontext(output, 1):
2098 output.append(2)
2099 output.append(3)
2100 run_jump_test(func, 3, 2, [1, 2, -1], _no_jump_into_with_error)
2101
2102 def test_no_jump_into_bare_except_block():
2103 def func(output):
2104 output.append(1)
2105 try:
2106 output.append(3)
2107 except:
2108 output.append(5)
2109 run_jump_test(func, 1, 5, [], (ValueError, "can't jump into an 'except' block as there's no exception"))
2110
2111 def test_no_jump_into_qualified_except_block():
2112 def func(output):
2113 output.append(1)
2114 try:
2115 output.append(3)
2116 except Exception:
2117 output.append(5)
2118 run_jump_test(func, 1, 5, [], (ValueError, "can't jump into an 'except' block as there's no exception"))
2119
2120 def test_no_jump_into_bare_except_block_from_try_block():
2121 def func(output):
2122 try:
2123 output.append(2)
2124 output.append(3)
2125 except:
2126 output.append(5)
2127 output.append(6)
2128 raise
2129 output.append(8)
2130 run_jump_test(func, 3, 6, [2, 5, 6], (ValueError, "can't jump into an 'except' block as there's no exception"))
2131
2132 def test_no_jump_into_qualified_except_block_from_try_block():
2133 def func(output):
2134 try:
2135 output.append(2)
2136 output.append(3)
2137 except ZeroDivisionError:
2138 output.append(5)
2139 output.append(6)
2140 raise
2141 output.append(8)
2142 run_jump_test(func, 3, 6, [2], (ValueError, "can't jump into an 'except' block as there's no exception"))
2143
2144 def test_jump_out_of_bare_except_block():
2145 def func(output):
2146 output.append(1)
2147 try:
2148 output.append(3)
2149 1/0
2150 except:
2151 output.append(6)
2152 output.append(7)
2153 run_jump_test(func, 7, 1, [1, 3, 6, 1, 3, 6, 7])
2154
2155 def test_jump_out_of_qualified_except_block():
2156 def func(output):
2157 output.append(1)
2158 try:
2159 output.append(3)
2160 1/0
2161 except Exception:
2162 output.append(6)
2163 output.append(7)
2164 run_jump_test(func, 7, 1, [1, 3, 6, 1, 3, 6, 7])
2165
2166 def test_no_jump_over_return_out_of_finally_block():
2167 def func(output):
2168 try:
2169 output.append(2)
2170 finally:
2171 output.append(4)
2172 output.append(5)
2173 return
2174 output.append(7)
2175 run_jump_test(func, 5, 7, [2, 4], (ValueError, 'after'))
2176
2177 def test_no_jump_into_for_block_before_else():
2178 def func(output):
2179 output.append(1)
2180 if not output:
2181 for i in [3]:
2182 output.append(4)
2183 else:
2184 output.append(6)
2185 output.append(7)
2186 output.append(8)
2187 run_jump_test(func, 7, 4, [1, 6], (ValueError, 'into'))
2188
2189 def test_no_jump_to_non_integers():
2190 run_jump_test(no_jump_to_non_integers, 2, "Spam", [True])
2191
2192 def test_no_jump_without_trace_function():
2193 no_jump_without_trace_function()
2194
2195 def test_large_function():
2196 d = {}
2197 exec("""def f(output): # line 0
2198 x = 0 # line 1
2199 y = 1 # line 2
2200 ''' # line 3
2201 %s # lines 4-1004
2202 ''' # line 1005
2203 x += 1 # line 1006
2204 output.append(x) # line 1007
2205 return""" % ('\n' * 1000,), d)
2206 f = d['f']
2207 run_jump_test(f, 2, 1007, [0])
2208
2209 def test_jump_to_firstlineno():
2210 code = compile("""
2211 # Comments don't count.
2212 output.append(2) # firstlineno is here.
2213 output.append(3)
2214 output.append(4)
2215 """, "<fake module>", "exec")
2216 class fake_function:
2217 __code__ = code
2218 tracer = JumpTracer(fake_function, 4, 1)
2219 sys.settrace(tracer.trace)
2220 namespace = {"output": []}
2221 exec(code, namespace)
2222 sys.settrace(None)
2223 assert namespace["output"] == [2, 3, 2, 3, 4]
2224
2225 def test_no_jump_from_call():
2226 def func(output):
2227 output.append(1)
2228 def nested():
2229 output.append(3)
2230 nested()
2231 output.append(5)
2232 run_jump_test(func, 2, 3, [1], event='call',
2233 error=(ValueError, "can't jump from the 'call' trace event of a new frame"))
2234
2235 def test_no_jump_from_return_event():
2236 def func(output):
2237 output.append(1)
2238 return
2239 run_jump_test(func, 2, 1, [1], event='return',
2240 error=(ValueError, "can only jump from a 'line' trace event"))
2241
2242 def test_no_jump_from_exception_event():
2243 def func(output):
2244 output.append(1)
2245 1 / 0
2246 run_jump_test(func, 2, 1, [1], event='exception',
2247 error=(ValueError, "can only jump from a 'line' trace event"))
2248
2249 def test_jump_from_yield():
2250 def func(output):
2251 def gen():
2252 output.append(2)
2253 yield 3
2254 next(gen())
2255 output.append(5)
2256 run_jump_test(func, 3, 2, [2, 5], event='return')
2257
2258 def test_jump_forward_over_listcomp():
2259 def func(output):
2260 output.append(1)
2261 x = [i for i in range(10)]
2262 output.append(3)
2263 run_jump_test(func, 2, 3, [1, 3])
2264
2265 def test_jump_backward_over_listcomp():
2266 def func(output):
2267 a = 1
2268 x = [i for i in range(10)]
2269 c = 3
2270 run_jump_test(func, 3, 1, [])
2271
2272 def test_jump_backward_over_listcomp_v2():
2273 def func(output):
2274 flag = False
2275 output.append(2)
2276 if flag:
2277 return
2278 x = [i for i in range(5)]
2279 flag = 6
2280 output.append(7)
2281 output.append(8)
2282 run_jump_test(func, 8, 2, [2, 7, 2])
2283
2284 def test_jump_extended_args_unpack_ex_simple():
2285 def func(output):
2286 output.append(1)
2287 _, *_, _ = output.append(2) or "Spam"
2288 output.append(3)
2289 run_jump_test(func, 2, 3, [1, 3])
2290
2291 def test_jump_or_pop():
2292 def func(output):
2293 output.append(1)
2294 _ = output.append(2) and "Spam"
2295 output.append(3)
2296 run_jump_test(func, 2, 3, [1, 3])
2297
2298
2299 # ---------------------------------------------------------------------------
2300 # TestExtendedArgs tests
2301 # ---------------------------------------------------------------------------
2302
2303 def test_extended_args_trace_unpack_long_sequence():
2304 ns = {}
2305 code = "def f():\n (" + "y,\n "*300 + ") = range(300)"
2306 exec(code, ns)
2307 f = ns["f"]
2308 for _ in range(20):
2309 f()
2310 counts = {"call": 0, "line": 0, "return": 0}
2311 def trace(frame, event, arg):
2312 counts[event] = counts.get(event, 0) + 1
2313 return trace
2314 sys.settrace(trace)
2315 f()
2316 sys.settrace(None)
2317 assert counts == {'call': 1, 'line': 301, 'return': 1}
2318
2319
2320 # ---------------------------------------------------------------------------
2321 # TestEdgeCases tests
2322 # ---------------------------------------------------------------------------
2323
2324 def test_edge_same_object():
2325 def foo(*args):
2326 pass
2327 sys.settrace(foo)
2328 del foo
2329 sys.settrace(sys.gettrace())
2330 sys.settrace(None)