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