File: test_debugger_json.py

package info (click to toggle)
pydevd 3.3.0%2Bds-4
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 13,892 kB
  • sloc: python: 77,508; cpp: 1,869; sh: 368; makefile: 50; ansic: 4
file content (6968 lines) | stat: -rw-r--r-- 278,023 bytes parent folder | download
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
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
# coding: utf-8
from collections import namedtuple
import json
from os.path import normcase
import os.path
import sys
import time

import pytest

from _pydev_bundle.pydev_localhost import get_socket_name
from _pydevd_bundle._debug_adapter import pydevd_schema, pydevd_base_schema
from _pydevd_bundle._debug_adapter.pydevd_base_schema import from_json
from _pydevd_bundle._debug_adapter.pydevd_schema import (
    ThreadEvent,
    ModuleEvent,
    OutputEvent,
    ExceptionOptions,
    Response,
    StoppedEvent,
    ContinuedEvent,
    ProcessEvent,
    InitializeRequest,
    InitializeRequestArguments,
    TerminateArguments,
    TerminateRequest,
    TerminatedEvent,
    FunctionBreakpoint,
    SetFunctionBreakpointsRequest,
    SetFunctionBreakpointsArguments,
    BreakpointEvent,
    InitializedEvent,
    ContinueResponse,
)
from _pydevd_bundle.pydevd_comm_constants import file_system_encoding
from _pydevd_bundle.pydevd_constants import (
    int_types,
    IS_64BIT_PROCESS,
    PY_VERSION_STR,
    PY_IMPL_VERSION_STR,
    PY_IMPL_NAME,
    IS_PY36_OR_GREATER,
    IS_PYPY,
    GENERATED_LEN_ATTR_NAME,
    IS_WINDOWS,
    IS_LINUX,
    IS_MAC,
    IS_PY38_OR_GREATER,
    IS_PY311_OR_GREATER,
    PYDEVD_USE_SYS_MONITORING,
    IS_PY312_OR_GREATER,
    SUPPORT_ATTACH_TO_PID,
    IS_PY313_OR_GREATER,
)
from tests_python import debugger_unittest
from tests_python.debug_constants import TEST_CHERRYPY, TEST_DJANGO, TEST_FLASK, IS_CPYTHON, TEST_GEVENT, TEST_CYTHON, IS_PY311
from tests_python.debugger_unittest import IS_JYTHON, IS_APPVEYOR, overrides, get_free_port, wait_for_condition
from _pydevd_bundle.pydevd_utils import DAPGrouper
import pydevd_file_utils
from _pydevd_bundle import pydevd_constants

pytest_plugins = [
    str("tests_python.debugger_fixtures"),
]

_JsonHit = namedtuple("_JsonHit", "thread_id, frame_id, stack_trace_response")

pytestmark = pytest.mark.skipif(IS_JYTHON, reason="Single notification is not OK in Jython (investigate).")

# Note: in reality must be < int32, but as it's created sequentially this should be
# a reasonable number for tests.
MAX_EXPECTED_ID = 10000


class _MessageWithMark(object):
    def __init__(self, msg):
        self.msg = msg
        self.marked = False


class JsonFacade(object):
    def __init__(self, writer):
        self.writer = writer
        if hasattr(writer, "reader_thread"):
            writer.reader_thread.accept_xml_messages = False
        self._all_json_messages_found = []
        self._sent_launch_or_attach = False

    def mark_messages(self, expected_class, accept_message=lambda obj: True):
        ret = []
        for message_with_mark in self._all_json_messages_found:
            if not message_with_mark.marked:
                if isinstance(message_with_mark.msg, expected_class):
                    if accept_message(message_with_mark.msg):
                        message_with_mark.marked = True
                        ret.append(message_with_mark.msg)
        return ret

    def wait_for_json_message(self, expected_class, accept_message=lambda obj: True):
        def accept_json_message(msg):
            if msg.startswith("{"):
                decoded_msg = from_json(msg)

                self._all_json_messages_found.append(_MessageWithMark(decoded_msg))

                if isinstance(decoded_msg, expected_class):
                    if accept_message(decoded_msg):
                        return True
            return False

        msg = self.writer.wait_for_message(accept_json_message, unquote_msg=False, expect_xml=False)
        return from_json(msg)

    def build_accept_response(self, request, response_class=None):
        if response_class is None:
            response_class = pydevd_base_schema.get_response_class(request)

        def accept_message(response):
            if isinstance(request, dict):
                if response.request_seq == request["seq"]:
                    return True
            else:
                if response.request_seq == request.seq:
                    return True
            return False

        return (response_class, Response), accept_message

    def wait_for_response(self, request, response_class=None):
        expected_classes, accept_message = self.build_accept_response(request, response_class)
        return self.wait_for_json_message(expected_classes, accept_message)

    def write_request(self, request):
        seq = self.writer.next_seq()
        if isinstance(request, dict):
            request["seq"] = seq
            self.writer.write_with_content_len(json.dumps(request))
        else:
            request.seq = seq
            self.writer.write_with_content_len(request.to_json())
        return request

    def write_make_initial_run(self):
        if not self._sent_launch_or_attach:
            self._auto_write_launch()

        configuration_done_request = self.write_request(pydevd_schema.ConfigurationDoneRequest())
        return self.wait_for_response(configuration_done_request)

    def write_list_threads(self):
        return self.wait_for_response(self.write_request(pydevd_schema.ThreadsRequest()))

    def wait_for_terminated(self):
        return self.wait_for_json_message(TerminatedEvent)

    def wait_for_thread_stopped(self, reason="breakpoint", line=None, file=None, name=None, preserve_focus_hint=None):
        """
        :param file:
            utf-8 bytes encoded file or unicode
        """
        stopped_event = self.wait_for_json_message(StoppedEvent)
        assert stopped_event.body.reason == reason
        if preserve_focus_hint is not None:
            assert stopped_event.body.preserveFocusHint == preserve_focus_hint
        json_hit = self.get_stack_as_json_hit(stopped_event.body.threadId)
        if file is not None:
            path = json_hit.stack_trace_response.body.stackFrames[0]["source"]["path"]

            if not path.endswith(file):
                # pytest may give a lowercase tempdir, so, also check with
                # the real case if possible
                file = pydevd_file_utils.get_path_with_real_case(file)
                if not path.endswith(file):
                    raise AssertionError("Expected path: %s to end with: %s" % (path, file))
        if name is not None:
            assert json_hit.stack_trace_response.body.stackFrames[0]["name"] == name
        if line is not None:
            found_line = json_hit.stack_trace_response.body.stackFrames[0]["line"]
            path = json_hit.stack_trace_response.body.stackFrames[0]["source"]["path"]
            if not isinstance(line, (tuple, list)):
                line = [line]
            assert found_line in line, "Expect to break at line: %s. Found: %s (file: %s)" % (line, found_line, path)
        return json_hit

    def write_set_function_breakpoints(self, function_names):
        function_breakpoints = [
            FunctionBreakpoint(
                name,
            )
            for name in function_names
        ]
        arguments = SetFunctionBreakpointsArguments(function_breakpoints)
        request = SetFunctionBreakpointsRequest(arguments)
        response = self.wait_for_response(self.write_request(request))
        assert response.success

    def write_set_breakpoints(
        self,
        lines,
        filename=None,
        line_to_info=None,
        success=True,
        verified=True,
        send_launch_if_needed=True,
        expected_lines_in_response=None,
    ):
        """
        Adds a breakpoint.
        """
        if send_launch_if_needed and not self._sent_launch_or_attach:
            self._auto_write_launch()

        if isinstance(lines, int):
            lines = [lines]

        if line_to_info is None:
            line_to_info = {}

        if filename is None:
            filename = self.writer.get_main_filename()

        if isinstance(filename, bytes):
            filename = filename.decode(file_system_encoding)  # file is in the filesystem encoding but protocol needs it in utf-8
            filename = filename.encode("utf-8")

        source = pydevd_schema.Source(path=filename)
        breakpoints = []
        for line in lines:
            condition = None
            hit_condition = None
            log_message = None

            if line in line_to_info:
                line_info = line_to_info.get(line)
                condition = line_info.get("condition")
                hit_condition = line_info.get("hit_condition")
                log_message = line_info.get("log_message")

            breakpoints.append(
                pydevd_schema.SourceBreakpoint(line, condition=condition, hitCondition=hit_condition, logMessage=log_message).to_dict()
            )

        arguments = pydevd_schema.SetBreakpointsArguments(source, breakpoints)
        request = pydevd_schema.SetBreakpointsRequest(arguments)

        # : :type response: SetBreakpointsResponse
        response = self.wait_for_response(self.write_request(request))
        body = response.body

        assert response.success == success

        if success:
            # : :type body: SetBreakpointsResponseBody
            assert len(body.breakpoints) == len(lines)
            lines_in_response = [b["line"] for b in body.breakpoints]

            if expected_lines_in_response is None:
                expected_lines_in_response = lines
            assert set(lines_in_response) == set(expected_lines_in_response)

            for b in body.breakpoints:
                if isinstance(verified, dict):
                    if b["verified"] != verified[b["id"]]:
                        raise AssertionError(
                            "Expected verified breakpoint to be: %s. Found: %s.\nBreakpoint: %s" % (verified, verified[b["id"]], b)
                        )

                elif b["verified"] != verified:
                    raise AssertionError(
                        "Expected verified breakpoint to be: %s. Found: %s.\nBreakpoint: %s" % (verified, b["verified"], b)
                    )
        return response

    def write_set_exception_breakpoints(self, filters=None, exception_options=None):
        """
        :param list(str) filters:
            A list with 'raised' or 'uncaught' entries.

        :param list(ExceptionOptions) exception_options:

        """
        filters = filters or []
        assert set(filters).issubset(set(("raised", "uncaught", "userUnhandled")))

        exception_options = exception_options or []
        exception_options = [exception_option.to_dict() for exception_option in exception_options]

        arguments = pydevd_schema.SetExceptionBreakpointsArguments(filters=filters, exceptionOptions=exception_options)
        request = pydevd_schema.SetExceptionBreakpointsRequest(arguments)
        # : :type response: SetExceptionBreakpointsResponse
        response = self.wait_for_response(self.write_request(request))
        assert response.success

    def reset_sent_launch_or_attach(self):
        self._sent_launch_or_attach = False

    def _write_launch_or_attach(self, command, **arguments):
        assert not self._sent_launch_or_attach
        self._sent_launch_or_attach = True
        arguments["noDebug"] = False
        request = {"type": "request", "command": command, "arguments": arguments, "seq": -1}
        self.wait_for_response(self.write_request(request))

    def _auto_write_launch(self):
        self.write_launch(
            variablePresentation={
                "all": "hide",
                "protected": "inline",
            }
        )

    def write_launch(self, **arguments):
        return self._write_launch_or_attach("launch", **arguments)

    def write_attach(self, **arguments):
        return self._write_launch_or_attach("attach", **arguments)

    def write_disconnect(self, wait_for_response=True, terminate_debugee=False):
        assert self._sent_launch_or_attach
        self._sent_launch_or_attach = False
        arguments = pydevd_schema.DisconnectArguments(terminateDebuggee=terminate_debugee)
        request = pydevd_schema.DisconnectRequest(arguments=arguments)
        self.write_request(request)
        if wait_for_response:
            self.wait_for_response(request)

    def get_stack_as_json_hit(self, thread_id, no_stack_frame=False):
        stack_trace_request = self.write_request(pydevd_schema.StackTraceRequest(pydevd_schema.StackTraceArguments(threadId=thread_id)))

        # : :type stack_trace_response: StackTraceResponse
        # : :type stack_trace_response_body: StackTraceResponseBody
        # : :type stack_frame: StackFrame
        stack_trace_response = self.wait_for_response(stack_trace_request)
        stack_trace_response_body = stack_trace_response.body
        if no_stack_frame:
            assert len(stack_trace_response_body.stackFrames) == 0
            frame_id = None
        else:
            assert len(stack_trace_response_body.stackFrames) > 0
            for stack_frame in stack_trace_response_body.stackFrames:
                assert stack_frame["id"] < MAX_EXPECTED_ID

            stack_frame = next(iter(stack_trace_response_body.stackFrames))
            frame_id = stack_frame["id"]

        return _JsonHit(thread_id=thread_id, frame_id=frame_id, stack_trace_response=stack_trace_response)

    def get_variables_response(self, variables_reference, fmt=None, success=True):
        assert variables_reference < MAX_EXPECTED_ID
        variables_request = self.write_request(
            pydevd_schema.VariablesRequest(pydevd_schema.VariablesArguments(variables_reference, format=fmt))
        )
        variables_response = self.wait_for_response(variables_request)
        assert variables_response.success == success
        return variables_response

    def filter_return_variables(self, variables):
        ret = []
        for variable in variables:
            if variable["name"].startswith("(return)"):
                ret.append(variable)
        return ret

    def pop_variables_reference(self, lst):
        """
        Modifies dicts in-place to remove the variablesReference and returns those (in the same order
        in which they were received).
        """
        references = []
        for dct in lst:
            reference = dct.pop("variablesReference", None)
            if reference is not None:
                assert isinstance(reference, int_types)
                assert reference < MAX_EXPECTED_ID
            references.append(reference)
        return references

    def wait_for_continued_event(self, all_threads_continued=True):
        ev = self.wait_for_json_message(ContinuedEvent)
        assert ev.body.allThreadsContinued == all_threads_continued

    def _by_type(self, *msgs):
        ret = {}
        for msg in msgs:
            assert msg.__class__ not in ret
            ret[msg.__class__] = msg
        return ret

    def write_continue(self, wait_for_response=True, thread_id="*"):
        continue_request = self.write_request(pydevd_schema.ContinueRequest(pydevd_schema.ContinueArguments(threadId=thread_id)))

        if wait_for_response:
            if thread_id != "*":
                # event, response may be sent in any order
                msg1 = self.wait_for_json_message((ContinuedEvent, ContinueResponse))
                msg2 = self.wait_for_json_message((ContinuedEvent, ContinueResponse))
                by_type = self._by_type(msg1, msg2)
                continued_ev = by_type[ContinuedEvent]
                continue_response = by_type[ContinueResponse]
                assert continue_response.request_seq == continue_request.seq

                assert continued_ev.body.allThreadsContinued == False
                assert continue_response.body.allThreadsContinued == False
            else:
                # The continued event is received before the response.
                self.wait_for_continued_event(all_threads_continued=True)
                continue_response = self.wait_for_response(continue_request)
                assert continue_response.body.allThreadsContinued

    def write_pause(self):
        pause_request = self.write_request(pydevd_schema.PauseRequest(pydevd_schema.PauseArguments("*")))
        pause_response = self.wait_for_response(pause_request)
        assert pause_response.success

    def write_step_in(self, thread_id, target_id=None):
        arguments = pydevd_schema.StepInArguments(threadId=thread_id, targetId=target_id)
        self.wait_for_response(self.write_request(pydevd_schema.StepInRequest(arguments)))

    def write_step_next(self, thread_id, wait_for_response=True):
        next_request = self.write_request(pydevd_schema.NextRequest(pydevd_schema.NextArguments(thread_id)))
        if wait_for_response:
            self.wait_for_response(next_request)

    def write_step_out(self, thread_id, wait_for_response=True):
        stepout_request = self.write_request(pydevd_schema.StepOutRequest(pydevd_schema.StepOutArguments(thread_id)))
        if wait_for_response:
            self.wait_for_response(stepout_request)

    def write_set_variable(self, frame_variables_reference, name, value, success=True):
        set_variable_request = self.write_request(
            pydevd_schema.SetVariableRequest(
                pydevd_schema.SetVariableArguments(
                    frame_variables_reference,
                    name,
                    value,
                )
            )
        )
        set_variable_response = self.wait_for_response(set_variable_request)
        if set_variable_response.success != success:
            raise AssertionError(
                "Expected %s. Found: %s\nResponse: %s\n" % (success, set_variable_response.success, set_variable_response.to_json())
            )
        return set_variable_response

    def get_name_to_scope(self, frame_id):
        scopes_request = self.write_request(pydevd_schema.ScopesRequest(pydevd_schema.ScopesArguments(frame_id)))

        scopes_response = self.wait_for_response(scopes_request)

        scopes = scopes_response.body.scopes
        name_to_scopes = dict((scope["name"], pydevd_schema.Scope(**scope)) for scope in scopes)

        assert len(scopes) == 2
        assert sorted(name_to_scopes.keys()) == ["Globals", "Locals"]
        assert not name_to_scopes["Locals"].expensive
        assert name_to_scopes["Locals"].presentationHint == "locals"

        return name_to_scopes

    def get_step_in_targets(self, frame_id):
        request = self.write_request(pydevd_schema.StepInTargetsRequest(pydevd_schema.StepInTargetsArguments(frame_id)))

        # : :type response: StepInTargetsResponse
        response = self.wait_for_response(request)

        # : :type body: StepInTargetsResponseBody
        body = response.body
        targets = body.targets
        # : :type targets: List[StepInTarget]
        return targets

    def get_name_to_var(self, variables_reference):
        variables_response = self.get_variables_response(variables_reference)
        return dict((variable["name"], pydevd_schema.Variable(**variable)) for variable in variables_response.body.variables)

    def get_locals_name_to_var(self, frame_id):
        name_to_scope = self.get_name_to_scope(frame_id)

        return self.get_name_to_var(name_to_scope["Locals"].variablesReference)

    def get_globals_name_to_var(self, frame_id):
        name_to_scope = self.get_name_to_scope(frame_id)

        return self.get_name_to_var(name_to_scope["Globals"].variablesReference)

    def get_local_var(self, frame_id, var_name):
        ret = self.get_locals_name_to_var(frame_id)[var_name]
        assert ret.name == var_name
        return ret

    def get_global_var(self, frame_id, var_name):
        ret = self.get_globals_name_to_var(frame_id)[var_name]
        assert ret.name == var_name
        return ret

    def get_var(self, variables_reference, var_name=None, index=None):
        if var_name is not None:
            return self.get_name_to_var(variables_reference)[var_name]
        else:
            assert index is not None, "Either var_name or index must be passed."
            variables_response = self.get_variables_response(variables_reference)
            return pydevd_schema.Variable(**variables_response.body.variables[index])

    def write_set_debugger_property(
        self, dont_trace_start_patterns=None, dont_trace_end_patterns=None, multi_threads_single_notification=None, success=True
    ):
        dbg_request = self.write_request(
            pydevd_schema.SetDebuggerPropertyRequest(
                pydevd_schema.SetDebuggerPropertyArguments(
                    dontTraceStartPatterns=dont_trace_start_patterns,
                    dontTraceEndPatterns=dont_trace_end_patterns,
                    multiThreadsSingleNotification=multi_threads_single_notification,
                )
            )
        )
        response = self.wait_for_response(dbg_request)
        assert response.success == success
        return response

    def write_set_pydevd_source_map(self, source, pydevd_source_maps, success=True):
        dbg_request = self.write_request(
            pydevd_schema.SetPydevdSourceMapRequest(
                pydevd_schema.SetPydevdSourceMapArguments(
                    source=source,
                    pydevdSourceMaps=pydevd_source_maps,
                )
            )
        )
        response = self.wait_for_response(dbg_request)
        assert response.success == success
        return response

    def write_initialize(self, success=True):
        arguments = InitializeRequestArguments(
            adapterID="pydevd_test_case",
        )
        response = self.wait_for_response(self.write_request(InitializeRequest(arguments)))
        assert response.success == success
        if success:
            process_id = response.body.kwargs["pydevd"]["processId"]
            assert isinstance(process_id, int)
        return response

    def write_authorize(self, access_token, success=True):
        from _pydevd_bundle._debug_adapter.pydevd_schema import PydevdAuthorizeArguments
        from _pydevd_bundle._debug_adapter.pydevd_schema import PydevdAuthorizeRequest

        arguments = PydevdAuthorizeArguments(
            debugServerAccessToken=access_token,
        )
        response = self.wait_for_response(self.write_request(PydevdAuthorizeRequest(arguments)))
        assert response.success == success
        return response

    def evaluate(self, expression, frameId=None, context=None, fmt=None, success=True, wait_for_response=True):
        """
        :param wait_for_response:
            If True returns the response, otherwise returns the request.

        :returns EvaluateResponse
        """
        eval_request = self.write_request(
            pydevd_schema.EvaluateRequest(pydevd_schema.EvaluateArguments(expression, frameId=frameId, context=context, format=fmt))
        )
        if wait_for_response:
            eval_response = self.wait_for_response(eval_request)
            assert eval_response.success == success
            return eval_response
        else:
            return eval_request

    def write_terminate(self):
        # Note: this currently terminates promptly, so, no answer is given.
        self.write_request(TerminateRequest(arguments=TerminateArguments()))

    def write_get_source(self, source_reference, success=True):
        response = self.wait_for_response(self.write_request(pydevd_schema.SourceRequest(pydevd_schema.SourceArguments(source_reference))))
        assert response.success == success
        return response


@pytest.mark.parametrize("scenario", ["basic", "condition", "hitCondition"])
def test_case_json_logpoints(case_setup_dap, scenario):
    with case_setup_dap.test_file("_debugger_case_change_breaks.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        break_2 = writer.get_line_index_with_content("break 2")
        break_3 = writer.get_line_index_with_content("break 3")
        if scenario == "basic":
            json_facade.write_set_breakpoints([break_2, break_3], line_to_info={break_2: {"log_message": 'var {repr("_a")} is {_a}'}})
        elif scenario == "condition":
            json_facade.write_set_breakpoints(
                [break_2, break_3], line_to_info={break_2: {"log_message": 'var {repr("_a")} is {_a}', "condition": "True"}}
            )
        elif scenario == "hitCondition":
            json_facade.write_set_breakpoints(
                [break_2, break_3], line_to_info={break_2: {"log_message": 'var {repr("_a")} is {_a}', "hit_condition": "1"}}
            )
        json_facade.write_make_initial_run()

        # Should only print, not stop on logpoints.

        # Just one hit at the end (break 3).
        json_facade.wait_for_thread_stopped(line=break_3)
        json_facade.write_continue()

        def accept_message(output_event):
            msg = output_event.body.output
            ctx = output_event.body.category

            if ctx == "stdout":
                msg = msg.strip()
                return msg == "var '_a' is 2"

        messages = json_facade.mark_messages(OutputEvent, accept_message)
        if scenario == "hitCondition":
            assert len(messages) == 1
        else:
            assert len(messages) == 2

        writer.finished_ok = True


def test_case_json_logpoint_and_step_failure_ok(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_hit_count.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        before_loop_line = writer.get_line_index_with_content("before loop line")
        for_line = writer.get_line_index_with_content("for line")
        print_line = writer.get_line_index_with_content("print line")
        json_facade.write_set_breakpoints(
            [before_loop_line, print_line], line_to_info={print_line: {"log_message": 'var {repr("_a")} is {_a}'}}
        )
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(line=before_loop_line)

        json_facade.write_step_in(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", line=for_line)

        json_facade.write_step_in(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", line=print_line)

        json_facade.write_continue()

        writer.finished_ok = True


def test_case_json_logpoint_and_step_still_prints(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_hit_count.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        before_loop_line = writer.get_line_index_with_content("before loop line")
        print_line = writer.get_line_index_with_content("print line")
        json_facade.write_set_breakpoints(
            [before_loop_line, print_line], line_to_info={print_line: {"log_message": 'var {repr("i")} is {i}'}}
        )
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(line=before_loop_line)

        for _i in range(4):
            # I.e.: even when stepping we should have the messages.
            json_facade.write_step_next(json_hit.thread_id)
            json_hit = json_facade.wait_for_thread_stopped("step")

        json_facade.write_continue()

        def accept_last_output_message(output_event):
            return output_event.body.output.startswith("var 'i' is 9")

        json_facade.wait_for_json_message(OutputEvent, accept_last_output_message)

        def accept_message(output_event):
            return output_event.body.output.startswith("var 'i' is ")

        assert len(json_facade.mark_messages(OutputEvent, accept_message)) == 10

        writer.finished_ok = True


def test_case_json_hit_count_and_step(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_hit_count.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        for_line = writer.get_line_index_with_content("for line")
        print_line = writer.get_line_index_with_content("print line")
        json_facade.write_set_breakpoints([print_line], line_to_info={print_line: {"hit_condition": "5"}})
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(line=print_line)
        i_local_var = json_facade.get_local_var(json_hit.frame_id, "i")  # : :type i_local_var: pydevd_schema.Variable
        assert i_local_var.value == "4"

        json_facade.write_step_in(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", line=for_line)

        json_facade.write_step_in(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", line=print_line)

        json_facade.write_continue()

        writer.finished_ok = True


def test_case_json_hit_condition_error(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_hit_count.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        bp = writer.get_line_index_with_content("before loop line")
        json_facade.write_set_breakpoints([bp], line_to_info={bp: {"condition": "range.range.range"}})
        json_facade.write_make_initial_run()

        def accept_message(msg):
            if msg.body.category == "important":
                if "Error while evaluating expression in conditional breakpoint" in msg.body.output:
                    return True
            return False

        json_facade.wait_for_json_message(OutputEvent, accept_message=accept_message)

        # In the dap mode we skip suspending when an error happens in conditional exceptions.
        # json_facade.wait_for_thread_stopped(line=bp)
        # json_facade.write_continue()

        writer.finished_ok = True


def test_case_json_hit_condition_error_count(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_hit_count_conditional.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        bp = writer.get_line_index_with_content("for line")
        bp2 = writer.get_line_index_with_content("after loop line")
        json_facade.write_set_breakpoints([bp, bp2], line_to_info={bp: {"condition": "1 / 0"}, bp2: {}})
        json_facade.write_make_initial_run()

        def accept_message(msg):
            if msg.body.category == "important":
                if "Error while evaluating expression in conditional breakpoint" in msg.body.output:
                    return True
            return False

        json_facade.wait_for_thread_stopped()
        messages = json_facade.mark_messages(OutputEvent, accept_message=accept_message)
        assert len(messages) == 11

        json_facade.write_continue()

        writer.finished_ok = True


def test_case_process_event(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_change_breaks.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        assert len(json_facade.mark_messages(ProcessEvent)) == 1
        json_facade.write_make_initial_run()
        writer.finished_ok = True


def test_case_json_change_breaks(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_change_breaks.py") as writer:
        json_facade = JsonFacade(writer)

        break1_line = writer.get_line_index_with_content("break 1")
        # Note: we can only write breakpoints after the launch is received.
        json_facade.write_set_breakpoints(break1_line, success=False, send_launch_if_needed=False)

        json_facade.write_launch()
        json_facade.write_set_breakpoints(break1_line)
        json_facade.write_make_initial_run()

        json_facade.wait_for_thread_stopped(line=break1_line)
        json_facade.write_set_breakpoints([])
        json_facade.write_continue()

        writer.finished_ok = True


def test_case_json_suspend_notification(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_change_breaks.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.writer.write_multi_threads_single_notification(False)
        break1_line = writer.get_line_index_with_content("break 1")
        json_facade.write_launch()
        json_facade.write_set_breakpoints(break1_line)
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(line=break1_line)
        json_facade.write_continue(thread_id=json_hit.thread_id)

        json_hit = json_facade.wait_for_thread_stopped(line=break1_line)
        json_facade.write_continue(thread_id=json_hit.thread_id, wait_for_response=False)

        writer.finished_ok = True


def test_case_handled_exception_no_break_on_generator(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_ignore_exceptions.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        json_facade.write_set_exception_breakpoints(["raised"])
        json_facade.write_make_initial_run()

        writer.finished_ok = True


def test_case_throw_exc_reason(case_setup_dap):
    def check_test_suceeded_msg(self, stdout, stderr):
        return "TEST SUCEEDED" in "".join(stderr)

    def additional_output_checks(writer, stdout, stderr):
        assert "raise RuntimeError('TEST SUCEEDED')" in stderr
        assert "raise RuntimeError from e" in stderr
        assert "raise Exception('another while handling')" in stderr

    with case_setup_dap.test_file(
        "_debugger_case_raise_with_cause.py",
        EXPECTED_RETURNCODE=1,
        check_test_suceeded_msg=check_test_suceeded_msg,
        additional_output_checks=additional_output_checks,
    ) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(justMyCode=False)
        json_facade.write_set_exception_breakpoints(["uncaught"])
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(
            reason="exception", line=writer.get_line_index_with_content("raise RuntimeError from e")
        )

        exc_info_request = json_facade.write_request(
            pydevd_schema.ExceptionInfoRequest(pydevd_schema.ExceptionInfoArguments(json_hit.thread_id))
        )
        exc_info_response = json_facade.wait_for_response(exc_info_request)

        stack_frames = json_hit.stack_trace_response.body.stackFrames
        # Note that the additional context doesn't really appear in the stack
        # frames, only in the details.
        assert [x["name"] for x in stack_frames] == [
            "foobar",
            "<module>",
            "[Chained Exc: another while handling] foobar",
            "[Chained Exc: another while handling] handle",
            "[Chained Exc: TEST SUCEEDED] foobar",
            "[Chained Exc: TEST SUCEEDED] method",
            "[Chained Exc: TEST SUCEEDED] method2",
        ]

        body = exc_info_response.body
        assert body.exceptionId.endswith("RuntimeError")
        assert body.description == "another while handling"
        assert normcase(body.details.kwargs["source"]) == normcase(writer.TEST_FILE)

        # Check that we have all the lines (including the cause/context) in the stack trace.
        import re

        lines_and_names = re.findall(r",\sline\s(\d+),\sin\s(\[Chained Exception\]\s)?([\w|<|>]+)", body.details.stackTrace)
        assert lines_and_names == [
            ("16", "", "foobar"),
            ("6", "", "method"),
            ("2", "", "method2"),
            ("18", "", "foobar"),
            ("10", "", "handle"),
            ("20", "", "foobar"),
            ("23", "", "<module>"),
        ], "Did not find the expected names in:\n%s" % (body.details.stackTrace,)

        json_facade.write_continue()

        writer.finished_ok = True


def test_case_throw_exc_reason_shown(case_setup_dap):
    def check_test_suceeded_msg(self, stdout, stderr):
        return "TEST SUCEEDED" in "".join(stderr)

    def additional_output_checks(writer, stdout, stderr):
        assert "raise Exception('TEST SUCEEDED') from e" in stderr
        assert "{}['foo']" in stderr
        assert "KeyError: 'foo'" in stderr

    with case_setup_dap.test_file(
        "_debugger_case_raise_with_cause_msg.py",
        EXPECTED_RETURNCODE=1,
        check_test_suceeded_msg=check_test_suceeded_msg,
        additional_output_checks=additional_output_checks,
    ) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(justMyCode=False)
        json_facade.write_set_exception_breakpoints(["uncaught"])
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(
            reason="exception", line=writer.get_line_index_with_content("raise Exception('TEST SUCEEDED') from e")
        )

        exc_info_request = json_facade.write_request(
            pydevd_schema.ExceptionInfoRequest(pydevd_schema.ExceptionInfoArguments(json_hit.thread_id))
        )
        exc_info_response = json_facade.wait_for_response(exc_info_request)

        stack_frames = json_hit.stack_trace_response.body.stackFrames
        # Note that the additional context doesn't really appear in the stack
        # frames, only in the details.
        assert [x["name"] for x in stack_frames] == [
            "method",
            "<module>",
            "[Chained Exc: 'foo'] method",
            "[Chained Exc: 'foo'] method2",
        ]

        body = exc_info_response.body
        assert body.exceptionId == "Exception"
        assert body.description == "TEST SUCEEDED"
        if IS_PY311_OR_GREATER:
            assert "^^^^" in body.details.stackTrace
        assert normcase(body.details.kwargs["source"]) == normcase(writer.TEST_FILE)

        # Check that we have the exception cause in the stack trace.
        assert "KeyError: 'foo'" in body.details.stackTrace

        json_facade.write_continue()

        writer.finished_ok = True


def test_case_handled_exception_breaks(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_exceptions.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        json_facade.write_set_exception_breakpoints(["raised"])
        json_facade.write_make_initial_run()

        json_facade.wait_for_thread_stopped(reason="exception", line=writer.get_line_index_with_content("raise indexerror line"))
        json_facade.write_continue()

        json_facade.wait_for_thread_stopped(reason="exception", line=writer.get_line_index_with_content("reraise on method2"))

        # Clear so that the last one is not hit.
        json_facade.write_set_exception_breakpoints([])
        json_facade.write_continue()

        writer.finished_ok = True


def _check_current_line(json_hit, current_line):
    if not isinstance(current_line, (list, tuple)):
        current_line = (current_line,)
    for frame in json_hit.stack_trace_response.body.stackFrames:
        if "(Current frame)" in frame["name"]:
            if frame["line"] not in current_line:
                rep = json.dumps(json_hit.stack_trace_response.body.stackFrames, indent=4)
                raise AssertionError("Expected: %s to be one of: %s\nFrames:\n%s." % (frame["line"], current_line, rep))

            break
    else:
        rep = json.dumps(json_hit.stack_trace_response.body.stackFrames, indent=4)
        raise AssertionError("Could not find (Current frame) in any frame name in: %s." % (rep))


@pytest.mark.parametrize("stop", [False, True])
def test_case_user_unhandled_exception(case_setup_dap, stop):
    def get_environ(self):
        env = os.environ.copy()

        # Note that we put the working directory in the project roots to check that when expanded
        # the relative file that doesn't exist is still considered a library file.
        env["IDE_PROJECT_ROOTS"] = os.path.dirname(self.TEST_FILE) + os.pathsep + os.path.abspath(".")
        return env

    if stop:
        target = "_debugger_case_user_unhandled.py"
    else:
        target = "_debugger_case_user_unhandled2.py"
    with case_setup_dap.test_file(target, get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        json_facade.write_set_exception_breakpoints(["userUnhandled"])
        json_facade.write_make_initial_run()

        if stop:
            json_hit = json_facade.wait_for_thread_stopped(
                reason="exception", line=writer.get_line_index_with_content("raise here"), file=target
            )
            _check_current_line(json_hit, writer.get_line_index_with_content("stop here"))

            json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.skipif(not IS_PY36_OR_GREATER, reason="Only CPython 3.6 onwards")
@pytest.mark.parametrize("stop", [False, True])
def test_case_user_unhandled_exception_coroutine(case_setup_dap, stop):
    if stop:
        target = "my_code/my_code_coroutine_user_unhandled.py"
    else:
        target = "my_code/my_code_coroutine_user_unhandled_no_stop.py"
    basename = os.path.basename(target)

    def additional_output_checks(writer, stdout, stderr):
        if stop:
            assert "raise RuntimeError" in stderr
        else:
            assert "raise RuntimeError" not in stderr

    with case_setup_dap.test_file(
        target, EXPECTED_RETURNCODE=1 if stop else 0, additional_output_checks=additional_output_checks
    ) as writer:
        json_facade = JsonFacade(writer)

        not_my_code_dir = debugger_unittest._get_debugger_test_file("not_my_code")
        json_facade.write_launch(
            rules=[
                {"path": not_my_code_dir, "include": False},
            ]
        )
        json_facade.write_set_exception_breakpoints(["userUnhandled"])
        json_facade.write_make_initial_run()

        if stop:
            stop_line = writer.get_line_index_with_content("stop here 1")
            current_line = stop_line

            json_hit = json_facade.wait_for_thread_stopped(reason="exception", line=stop_line, file=basename)
            _check_current_line(json_hit, current_line)

            json_facade.write_continue()

            current_line = writer.get_line_index_with_content("stop here 2")
            json_hit = json_facade.wait_for_thread_stopped(reason="exception", line=stop_line, file=basename)
            _check_current_line(json_hit, current_line)

            json_facade.write_continue()

            current_line = (
                writer.get_line_index_with_content("stop here 3a"),
                writer.get_line_index_with_content("stop here 3b"),
            )

            json_hit = json_facade.wait_for_thread_stopped(reason="exception", line=stop_line, file=basename)
            _check_current_line(json_hit, current_line)

            json_facade.write_continue()

        writer.finished_ok = True


def test_case_user_unhandled_exception_dont_stop(case_setup_dap):
    with case_setup_dap.test_file(
        "my_code/my_code_exception_user_unhandled.py",
    ) as writer:
        json_facade = JsonFacade(writer)

        not_my_code_dir = debugger_unittest._get_debugger_test_file("not_my_code")
        json_facade.write_launch(
            debugStdLib=True,
            rules=[
                {"path": not_my_code_dir, "include": False},
            ],
        )

        json_facade.write_set_exception_breakpoints(["userUnhandled"])
        json_facade.write_make_initial_run()

        writer.finished_ok = True


def test_case_user_unhandled_exception_stop_on_yield(case_setup_dap, pyfile):
    @pyfile
    def case_error_on_yield():
        def on_yield():
            yield
            raise AssertionError()  # raise here

        try:
            for _ in on_yield():  # stop here
                pass
        except:
            print("TEST SUCEEDED!")
            raise

    def get_environ(self):
        env = os.environ.copy()

        # Note that we put the working directory in the project roots to check that when expanded
        # the relative file that doesn't exist is still considered a library file.
        env["IDE_PROJECT_ROOTS"] = os.path.dirname(self.TEST_FILE) + os.pathsep + os.path.abspath(".")
        return env

    def additional_output_checks(writer, stdout, stderr):
        assert "raise AssertionError" in stderr

    with case_setup_dap.test_file(
        case_error_on_yield, get_environ=get_environ, EXPECTED_RETURNCODE=1, additional_output_checks=additional_output_checks
    ) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        json_facade.write_set_exception_breakpoints(["userUnhandled"])
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(
            reason="exception", line=writer.get_line_index_with_content("raise here"), file=case_error_on_yield
        )
        _check_current_line(json_hit, writer.get_line_index_with_content("stop here"))

        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.parametrize(
    "target",
    [
        "absolute",
        "relative",
    ],
)
@pytest.mark.parametrize(
    "just_my_code",
    [
        True,
        False,
    ],
)
def test_case_unhandled_exception_just_my_code(case_setup_dap, target, just_my_code):
    def check_test_suceeded_msg(writer, stdout, stderr):
        # Don't call super (we have an unhandled exception in the stack trace).
        return "TEST SUCEEDED" in "".join(stderr)

    def additional_output_checks(writer, stdout, stderr):
        if "call_exception_in_exec()" not in stderr:
            raise AssertionError("Expected test to have an unhandled exception.\nstdout:\n%s\n\nstderr:\n%s" % (stdout, stderr))

    def get_environ(self):
        env = os.environ.copy()

        # Note that we put the working directory in the project roots to check that when expanded
        # the relative file that doesn't exist is still considered a library file.
        env["IDE_PROJECT_ROOTS"] = os.path.dirname(self.TEST_FILE) + os.pathsep + os.path.abspath(".")
        return env

    def update_command_line_args(writer, args):
        ret = debugger_unittest.AbstractWriterThread.update_command_line_args(writer, args)
        if target == "absolute":
            if sys.platform == "win32":
                ret.append("c:/temp/folder/my_filename.pyx")
            else:
                ret.append("/temp/folder/my_filename.pyx")

        elif target == "relative":
            ret.append("folder/my_filename.pyx")

        else:
            raise AssertionError("Unhandled case: %s" % (target,))
        return args

    target_filename = "_debugger_case_unhandled_just_my_code.py"
    with case_setup_dap.test_file(
        target_filename,
        check_test_suceeded_msg=check_test_suceeded_msg,
        additional_output_checks=additional_output_checks,
        update_command_line_args=update_command_line_args,
        get_environ=get_environ,
        EXPECTED_RETURNCODE=1,
    ) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(justMyCode=just_my_code)
        json_facade.write_set_exception_breakpoints(["uncaught"])
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(reason="exception")
        frames = json_hit.stack_trace_response.body.stackFrames
        if just_my_code:
            assert len(frames) == 1
            assert frames[0]["source"]["path"].endswith(target_filename)
        else:
            assert len(frames) > 1
            assert frames[0]["source"]["path"].endswith("my_filename.pyx")

        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.skipif(not IS_PY36_OR_GREATER, reason="Python 3.6 onwards required for test.")
def test_case_stop_async_iteration_exception(case_setup_dap):
    def get_environ(self):
        env = os.environ.copy()
        env["IDE_PROJECT_ROOTS"] = os.path.dirname(self.TEST_FILE) + os.pathsep + os.path.abspath(".")
        return env

    with case_setup_dap.test_file(
        "_debugger_case_stop_async_iteration.py",
        get_environ=get_environ,
    ) as writer:
        json_facade = JsonFacade(writer)

        # We don't want to hit common library exceptions here.
        json_facade.write_launch(justMyCode=True)

        json_facade.write_set_exception_breakpoints(["raised"])
        json_facade.write_make_initial_run()

        # Just making sure that no exception breakpoints are hit.

        writer.finished_ok = True


@pytest.mark.parametrize(
    "target_file",
    [
        "_debugger_case_unhandled_exceptions.py",
        "_debugger_case_unhandled_exceptions_custom.py",
    ],
)
def test_case_unhandled_exception(case_setup_dap, target_file):
    def check_test_suceeded_msg(writer, stdout, stderr):
        # Don't call super (we have an unhandled exception in the stack trace).
        return "TEST SUCEEDED" in "".join(stdout) and "TEST SUCEEDED" in "".join(stderr)

    def additional_output_checks(writer, stdout, stderr):
        if "raise MyError" not in stderr and "raise Exception" not in stderr:
            raise AssertionError("Expected test to have an unhandled exception.\nstdout:\n%s\n\nstderr:\n%s" % (stdout, stderr))

    with case_setup_dap.test_file(
        target_file,
        check_test_suceeded_msg=check_test_suceeded_msg,
        additional_output_checks=additional_output_checks,
        EXPECTED_RETURNCODE=1,
    ) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        json_facade.write_set_exception_breakpoints(["uncaught"])
        json_facade.write_make_initial_run()

        line_in_thread1 = writer.get_line_index_with_content("in thread 1")
        line_in_thread2 = writer.get_line_index_with_content("in thread 2")
        line_in_main = writer.get_line_index_with_content("in main")
        json_facade.wait_for_thread_stopped(reason="exception", line=(line_in_thread1, line_in_thread2), file=target_file)
        json_facade.write_continue()

        json_facade.wait_for_thread_stopped(reason="exception", line=(line_in_thread1, line_in_thread2), file=target_file)
        json_facade.write_continue()

        json_facade.wait_for_thread_stopped(reason="exception", line=line_in_main, file=target_file)
        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.parametrize(
    "target_file",
    [
        "_debugger_case_unhandled_exceptions_generator.py",
        "_debugger_case_unhandled_exceptions_listcomp.py",
    ],
)
def test_case_unhandled_exception_generator(case_setup_dap, target_file):
    def check_test_suceeded_msg(writer, stdout, stderr):
        # Don't call super (we have an unhandled exception in the stack trace).
        return "TEST SUCEEDED" in "".join(stdout) and "TEST SUCEEDED" in "".join(stderr)

    def additional_output_checks(writer, stdout, stderr):
        if "ZeroDivisionError" not in stderr:
            raise AssertionError("Expected test to have an unhandled exception.\nstdout:\n%s\n\nstderr:\n%s" % (stdout, stderr))

    with case_setup_dap.test_file(
        target_file,
        check_test_suceeded_msg=check_test_suceeded_msg,
        additional_output_checks=additional_output_checks,
        EXPECTED_RETURNCODE=1,
    ) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        json_facade.write_set_exception_breakpoints(["uncaught"])
        json_facade.write_make_initial_run()

        line_in_main = writer.get_line_index_with_content("exc line")

        json_hit = json_facade.wait_for_thread_stopped(reason="exception", line=line_in_main, file=target_file)
        frames = json_hit.stack_trace_response.body.stackFrames
        json_facade.write_continue()

        if "generator" in target_file:
            expected_frame_names = ["<genexpr>", "f", "<module>"]
        else:
            if IS_PY312_OR_GREATER:
                expected_frame_names = ["f", "<module>"]
            else:
                expected_frame_names = ["<listcomp>", "f", "<module>"]

        frame_names = [f["name"] for f in frames]
        assert frame_names == expected_frame_names

        writer.finished_ok = True


def test_case_sys_exit_unhandled_exception(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_sysexit.py", EXPECTED_RETURNCODE=1) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_set_exception_breakpoints(["uncaught"])
        json_facade.write_make_initial_run()

        break_line = writer.get_line_index_with_content("sys.exit(1)")
        json_facade.wait_for_thread_stopped(reason="exception", line=break_line)
        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.parametrize("break_on_system_exit_zero", [True, False])
@pytest.mark.parametrize("target", ["_debugger_case_sysexit_0.py", "_debugger_case_sysexit_none.py"])
def test_case_sys_exit_0_unhandled_exception(case_setup_dap, break_on_system_exit_zero, target):
    with case_setup_dap.test_file(target, EXPECTED_RETURNCODE=0) as writer:
        json_facade = JsonFacade(writer)
        kwargs = {}
        if break_on_system_exit_zero:
            kwargs = {"breakOnSystemExitZero": True}
        json_facade.write_launch(**kwargs)
        json_facade.write_set_exception_breakpoints(["uncaught"])
        json_facade.write_make_initial_run()

        break_line = writer.get_line_index_with_content("sys.exit(")
        if break_on_system_exit_zero:
            json_facade.wait_for_thread_stopped(reason="exception", line=break_line)
            json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.parametrize("break_on_system_exit_zero", [True, False])
def test_case_sys_exit_0_handled_exception(case_setup_dap, break_on_system_exit_zero):
    with case_setup_dap.test_file("_debugger_case_sysexit_0.py", EXPECTED_RETURNCODE=0) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(
            debugOptions=["BreakOnSystemExitZero"] if break_on_system_exit_zero else [],
        )
        json_facade.write_set_exception_breakpoints(["raised"])
        json_facade.write_make_initial_run()

        break_line = writer.get_line_index_with_content("sys.exit(0)")
        break_main_line = writer.get_line_index_with_content("call_main_line")
        if break_on_system_exit_zero:
            json_facade.wait_for_thread_stopped(reason="exception", line=break_line)
            json_facade.write_continue()

            json_facade.wait_for_thread_stopped(reason="exception", line=break_main_line)
            json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.skipif(
    sys.platform == "darwin" or not SUPPORT_ATTACH_TO_PID or IS_PYPY,
    reason="https://github.com/microsoft/ptvsd/issues/1988",
)
@pytest.mark.flaky(retries=2, delay=1)
@pytest.mark.parametrize("raised", ["raised", ""])
@pytest.mark.parametrize("uncaught", ["uncaught", ""])
@pytest.mark.parametrize("zero", ["zero", ""])
@pytest.mark.parametrize("exit_code", [0, 1, "nan"])
def test_case_sys_exit_multiple_exception_attach(case_setup_remote, raised, uncaught, zero, exit_code):
    filters = []
    if raised:
        filters += ["raised"]
    if uncaught:
        filters += ["uncaught"]

    def update_command_line_args(writer, args):
        # Add exit code to command line args
        ret = debugger_unittest.AbstractWriterThread.update_command_line_args(writer, args)
        ret.append(repr(exit_code))
        return ret

    evaled_exit_code = exit_code if exit_code != "nan" else 1

    with case_setup_remote.test_file(
        "_debugger_case_sysexit_unhandled_launcher.py",
        update_command_line_args=update_command_line_args,
        EXPECTED_RETURNCODE=evaled_exit_code,
        wait_for_port=False,
    ) as writer:
        _attach_to_writer_pid(writer)
        wait_for_condition(lambda: hasattr(writer, "reader_thread"))

        json_facade = JsonFacade(writer)
        json_facade.write_set_debugger_property([], ["_debugger_case_sysexit_unhandled_launcher.py"])

        break_file = debugger_unittest._get_debugger_test_file("_debugger_case_sysexit_unhandled_break.py")
        target_file = debugger_unittest._get_debugger_test_file("_debugger_case_sysexit_unhandled_attach.py")

        bp_line = writer.get_line_index_with_content("break here", filename=break_file)
        handled_line = writer.get_line_index_with_content("@handled", filename=target_file)
        unhandled_line = writer.get_line_index_with_content("@unhandled", filename=target_file)
        original_ignore_stderr_line = writer._ignore_stderr_line

        @overrides(writer._ignore_stderr_line)
        def _ignore_stderr_line(line):
            if exit_code == "nan":
                return True
            return original_ignore_stderr_line(line)

        writer._ignore_stderr_line = _ignore_stderr_line

        # Not really a launch, but we want to send these before the make_initial_run.
        json_facade.write_launch(
            breakpointOnSystemExit=True if zero else False,
            debugOptions=["BreakOnSystemExitZero", "ShowReturnValue"] if zero else ["ShowReturnValue"],
        )

        json_facade.write_set_exception_breakpoints(filters)
        json_facade.write_set_breakpoints([bp_line], filename=break_file)
        json_facade.write_make_initial_run()
        hit = json_facade.wait_for_thread_stopped(line=bp_line, file=break_file)

        # Stop looping
        json_facade.get_global_var(hit.frame_id, "wait")
        json_facade.write_set_variable(hit.frame_id, "wait", "False")
        json_facade.write_set_breakpoints([])
        json_facade.write_continue()

        # When breaking on raised exceptions, we'll stop on both lines,
        # unless it's SystemExit(0) and we asked to ignore that.
        if raised and (zero or exit_code != 0):
            json_facade.wait_for_thread_stopped(
                "exception",
                line=handled_line,
            )
            json_facade.write_continue()

            json_facade.wait_for_thread_stopped(
                "exception",
                line=unhandled_line,
            )
            json_facade.write_continue()

        # When breaking on uncaught exceptions, we'll stop on the second line,
        # unless it's SystemExit(0) and we asked to ignore that.
        # Note that if both raised and uncaught filters are set, there will be
        # two stop for the second line - one for exception being raised, and one
        # for it unwinding the stack without finding a handler. The block above
        # takes care of the first stop, so here we just take care of the second.
        if uncaught and (zero or exit_code != 0):
            json_facade.wait_for_thread_stopped(
                "exception",
                line=unhandled_line,
            )
            json_facade.write_continue()

        writer.finished_ok = True


def test_case_handled_exception_breaks_by_type(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_exceptions.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        json_facade.write_set_exception_breakpoints(
            exception_options=[
                ExceptionOptions(
                    breakMode="always",
                    path=[
                        {"names": ["Python Exceptions"]},
                        {"names": ["IndexError"]},
                    ],
                )
            ]
        )
        json_facade.write_make_initial_run()

        json_facade.wait_for_thread_stopped(reason="exception", line=writer.get_line_index_with_content("raise indexerror line"))

        # Deal only with RuntimeErorr now.
        json_facade.write_set_exception_breakpoints(
            exception_options=[
                ExceptionOptions(
                    breakMode="always",
                    path=[
                        {"names": ["Python Exceptions"]},
                        {"names": ["RuntimeError"]},
                    ],
                )
            ]
        )

        json_facade.write_continue()

        writer.finished_ok = True


def test_case_json_protocol(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_print.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        break_line = writer.get_line_index_with_content("Break here")
        json_facade.write_set_breakpoints(break_line)
        json_facade.write_make_initial_run()

        json_facade.wait_for_json_message(ThreadEvent, lambda event: event.body.reason == "started")

        json_facade.wait_for_thread_stopped(line=break_line)

        # : :type response: ThreadsResponse
        response = json_facade.write_list_threads()
        assert len(response.body.threads) == 1
        assert next(iter(response.body.threads))["name"] == "MainThread"

        # Removes breakpoints and proceeds running.
        json_facade.write_disconnect()

        writer.finished_ok = True


def test_case_started_exited_threads_protocol(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_thread_started_exited.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        break_line = writer.get_line_index_with_content("Break here")
        json_facade.write_set_breakpoints(break_line)

        json_facade.write_make_initial_run()

        _stopped_event = json_facade.wait_for_json_message(StoppedEvent)
        started_events = json_facade.mark_messages(ThreadEvent, lambda x: x.body.reason == "started")
        exited_events = json_facade.mark_messages(ThreadEvent, lambda x: x.body.reason == "exited")
        assert len(started_events) == 4
        assert len(exited_events) == 3  # Main is still running.
        json_facade.write_continue()

        writer.finished_ok = True


def test_case_path_translation_not_skipped(case_setup_dap):
    import site

    sys_folder = None
    if hasattr(site, "getusersitepackages"):
        sys_folder = site.getusersitepackages()

    if not sys_folder and hasattr(site, "getsitepackages"):
        sys_folder = site.getsitepackages()

    if not sys_folder:
        sys_folder = sys.prefix

    if isinstance(sys_folder, (list, tuple)):
        sys_folder = next(iter(sys_folder))

    with case_setup_dap.test_file("my_code/my_code.py") as writer:
        json_facade = JsonFacade(writer)

        # We need to set up path mapping to enable source references.
        my_code = debugger_unittest._get_debugger_test_file("my_code")

        json_facade.write_launch(
            justMyCode=False,
            pathMappings=[
                {
                    "localRoot": sys_folder,
                    "remoteRoot": my_code,
                }
            ],
        )

        bp_line = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints(
            bp_line,
            filename=os.path.join(sys_folder, "my_code.py"),
        )
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(line=bp_line)

        stack_frame = json_hit.stack_trace_response.body.stackFrames[-1]
        assert stack_frame["source"]["path"] == os.path.join(sys_folder, "my_code.py")
        for stack_frame in json_hit.stack_trace_response.body.stackFrames:
            assert stack_frame["source"]["sourceReference"] == 0
        json_facade.write_continue()

        writer.finished_ok = True


def test_case_exclude_double_step(case_setup_dap):
    with case_setup_dap.test_file("my_code/my_code_double_step.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(
            justMyCode=False,  # i.e.: exclude through rules and not my code
            rules=[
                {"path": "**/other_noop.py", "include": False},
            ],
        )

        break_line = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints(break_line)
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(line=break_line)
        json_facade.write_step_in(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", file="my_code_double_step.py", line=break_line + 1)

        json_facade.write_continue()
        writer.finished_ok = True


def test_case_update_rules(case_setup_dap):
    with case_setup_dap.test_file("my_code/my_code.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(
            rules=[
                {"path": "**/other.py", "include": False},
            ]
        )

        break_line = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints(break_line)
        json_facade.write_make_initial_run()

        json_facade.wait_for_json_message(ThreadEvent, lambda event: event.body.reason == "started")

        json_hit = json_facade.wait_for_thread_stopped(line=break_line)
        json_facade.reset_sent_launch_or_attach()
        json_facade.write_launch(
            rules=[
                {"path": "**/other.py", "include": True},
            ]
        )
        json_facade.write_step_in(json_hit.thread_id)
        # Not how we stoppen in the file that wasn't initially included.
        json_hit = json_facade.wait_for_thread_stopped("step", name="call_me_back1")

        json_facade.reset_sent_launch_or_attach()
        json_facade.write_launch(
            rules=[
                {"path": "**/other.py", "include": False},
            ]
        )
        json_facade.write_step_in(json_hit.thread_id)
        # Not how we go back to the callback and not to the `call_me_back1` because
        # `call_me_back1` is now excluded again.
        json_hit = json_facade.wait_for_thread_stopped("step", name="callback1")

        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.parametrize(
    "custom_setup",
    [
        "set_exclude_launch_module_full",
        "set_exclude_launch_module_prefix",
        "set_exclude_launch_path_match_filename",
        "set_exclude_launch_path_match_folder",
        "set_just_my_code",
        "set_just_my_code_and_include",
    ],
)
def test_case_skipping_filters(case_setup_dap, custom_setup):
    with case_setup_dap.test_file("my_code/my_code.py") as writer:
        json_facade = JsonFacade(writer)

        expect_just_my_code = False
        if custom_setup == "set_exclude_launch_path_match_filename":
            json_facade.write_launch(
                justMyCode=False,
                rules=[
                    {"path": "**/other.py", "include": False},
                ],
            )

        elif custom_setup == "set_exclude_launch_path_match_folder":
            not_my_code_dir = debugger_unittest._get_debugger_test_file("not_my_code")
            json_facade.write_launch(
                debugStdLib=True,
                rules=[
                    {"path": not_my_code_dir, "include": False},
                ],
            )

            other_filename = os.path.join(not_my_code_dir, "other.py")
            response = json_facade.write_set_breakpoints(1, filename=other_filename, verified=False)
            assert response.body.breakpoints == [
                {
                    "verified": False,
                    "id": 0,
                    "message": "Breakpoint in file excluded by filters.",
                    "source": {"path": other_filename},
                    "line": 1,
                }
            ]
            # Note: there's actually a use-case where we'd hit that breakpoint even if it was excluded
            # by filters, so, we must actually clear it afterwards (the use-case is that when we're
            # stepping into the context with the breakpoint we wouldn't skip it).
            json_facade.write_set_breakpoints([], filename=other_filename)

            other_filename = os.path.join(not_my_code_dir, "file_that_does_not_exist.py")
            response = json_facade.write_set_breakpoints(1, filename=other_filename, verified=False)
            assert response.body.breakpoints == [
                {
                    "verified": False,
                    "id": 1,
                    "message": "Breakpoint in file that does not exist.",
                    "source": {"path": other_filename},
                    "line": 1,
                }
            ]

        elif custom_setup == "set_exclude_launch_module_full":
            json_facade.write_launch(
                debugOptions=["DebugStdLib"],
                rules=[
                    {"module": "not_my_code.other", "include": False},
                ],
            )

        elif custom_setup == "set_exclude_launch_module_prefix":
            json_facade.write_launch(
                debugOptions=["DebugStdLib"],
                rules=[
                    {"module": "not_my_code", "include": False},
                ],
            )

        elif custom_setup == "set_just_my_code":
            expect_just_my_code = True
            writer.write_set_project_roots([debugger_unittest._get_debugger_test_file("my_code")])
            json_facade.write_launch(debugOptions=[])

            not_my_code_dir = debugger_unittest._get_debugger_test_file("not_my_code")
            other_filename = os.path.join(not_my_code_dir, "other.py")
            response = json_facade.write_set_breakpoints(33, filename=other_filename, verified=False, expected_lines_in_response=[14])
            assert response.body.breakpoints == [
                {
                    "verified": False,
                    "id": 0,
                    "message": 'Breakpoint in file excluded by filters.\nNote: may be excluded because of "justMyCode" option (default == true).Try setting "justMyCode": false in the debug configuration (e.g., launch.json).\n',
                    "source": {"path": other_filename},
                    "line": 14,
                }
            ]
        elif custom_setup == "set_just_my_code_and_include":
            expect_just_my_code = True
            # I.e.: nothing in my_code (add it with rule).
            writer.write_set_project_roots([debugger_unittest._get_debugger_test_file("launch")])
            json_facade.write_launch(
                debugOptions=[],
                rules=[
                    {"module": "__main__", "include": True},
                ],
            )

        else:
            raise AssertionError("Unhandled: %s" % (custom_setup,))

        break_line = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints(break_line)
        json_facade.write_make_initial_run()

        json_facade.wait_for_json_message(ThreadEvent, lambda event: event.body.reason == "started")

        json_hit = json_facade.wait_for_thread_stopped(line=break_line)

        json_facade.write_step_in(json_hit.thread_id)

        json_hit = json_facade.wait_for_thread_stopped("step", name="callback1")

        messages = json_facade.mark_messages(
            OutputEvent, lambda output_event: "Frame skipped from debugging during step-in." in output_event.body.output
        )
        assert len(messages) == 1
        body = next(iter(messages)).body
        found_just_my_code = 'Note: may have been skipped because of "justMyCode" option (default == true)' in body.output

        assert found_just_my_code == expect_just_my_code
        assert body.category == "important"

        json_facade.write_step_in(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", name="callback2")

        json_facade.write_step_next(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", name="callback1")

        json_facade.write_step_next(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", name="<module>")

        json_facade.write_step_next(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", name="<module>")

        json_facade.write_step_next(json_hit.thread_id)

        if IS_JYTHON:
            json_facade.write_continue()

        # Check that it's sent only once.
        assert (
            len(
                json_facade.mark_messages(
                    OutputEvent, lambda output_event: "Frame skipped from debugging during step-in." in output_event.body.output
                )
            )
            == 0
        )

        writer.finished_ok = True


def test_case_completions_json(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_completions.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()

        first_hit = None
        for i in range(2):
            json_hit = json_facade.wait_for_thread_stopped()

            json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)
            if i == 0:
                first_hit = json_hit

            completions_arguments = pydevd_schema.CompletionsArguments("dict.", 6, frameId=json_hit.frame_id, line=0)
            completions_request = json_facade.write_request(pydevd_schema.CompletionsRequest(completions_arguments))

            response = json_facade.wait_for_response(completions_request)
            assert response.success
            labels = [x["label"] for x in response.body.targets]
            assert set(labels).issuperset(set(["__contains__", "items", "keys", "values"]))

            completions_arguments = pydevd_schema.CompletionsArguments("dict.item", 10, frameId=json_hit.frame_id)
            completions_request = json_facade.write_request(pydevd_schema.CompletionsRequest(completions_arguments))

            response = json_facade.wait_for_response(completions_request)
            assert response.success
            if IS_JYTHON:
                assert response.body.targets == [{"start": 5, "length": 4, "type": "keyword", "label": "items"}]
            else:
                assert response.body.targets == [{"start": 5, "length": 4, "type": "function", "label": "items"}]

            if i == 1:
                # Check with a previously existing frameId.
                assert first_hit.frame_id != json_hit.frame_id
                completions_arguments = pydevd_schema.CompletionsArguments("dict.item", 10, frameId=first_hit.frame_id)
                completions_request = json_facade.write_request(pydevd_schema.CompletionsRequest(completions_arguments))

                response = json_facade.wait_for_response(completions_request)
                assert not response.success
                assert response.message == "Thread to get completions seems to have resumed already."

                # Check with a never frameId which never existed.
                completions_arguments = pydevd_schema.CompletionsArguments("dict.item", 10, frameId=99999)
                completions_request = json_facade.write_request(pydevd_schema.CompletionsRequest(completions_arguments))

                response = json_facade.wait_for_response(completions_request)
                assert not response.success
                assert response.message.startswith("Wrong ID sent from the client:")

            json_facade.write_continue()

        writer.finished_ok = True


def test_modules(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_local_variables.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break 2 here"))
        json_facade.write_make_initial_run()

        stopped_event = json_facade.wait_for_json_message(StoppedEvent)
        thread_id = stopped_event.body.threadId

        json_facade.write_request(pydevd_schema.StackTraceRequest(pydevd_schema.StackTraceArguments(threadId=thread_id)))

        json_facade.wait_for_json_message(ModuleEvent)

        # : :type response: ModulesResponse
        # : :type modules_response_body: ModulesResponseBody
        response = json_facade.wait_for_response(json_facade.write_request(pydevd_schema.ModulesRequest(pydevd_schema.ModulesArguments())))
        modules_response_body = response.body
        assert len(modules_response_body.modules) == 1
        module = next(iter(modules_response_body.modules))
        assert module["name"] == "__main__"
        assert module["path"].endswith("_debugger_case_local_variables.py")

        json_facade.write_continue()
        writer.finished_ok = True


def test_dict_ordered(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_odict.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        variables_response = json_facade.get_variables_response(json_hit.frame_id)

        variables_references = variables_response.body.variables
        for dct in variables_references:
            if dct["name"] == "odict":
                break
        else:
            raise AssertionError('Expected to find "odict".')
        ref = dct["variablesReference"]

        assert isinstance(ref, int_types)
        # : :type variables_response: VariablesResponse

        variables_response = json_facade.get_variables_response(ref)
        assert [
            (d["name"], d["value"])
            for d in variables_response.body.variables
            if (not d["name"].startswith("_OrderedDict")) and (d["name"] not in DAPGrouper.SCOPES_SORTED)
        ] == [("4", "'first'"), ("3", "'second'"), ("2", "'last'"), (GENERATED_LEN_ATTR_NAME, "3")]

        json_facade.write_continue()
        writer.finished_ok = True


def test_dict_contents(case_setup_dap, pyfile):
    @pyfile
    def check():
        dct = {"a": 1, "_b_": 2, "__c__": 3}
        print("TEST SUCEEDED")  # break here

    with case_setup_dap.test_file(check) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(justMyCode=False)
        json_facade.write_set_breakpoints(writer.get_line_index_with_content("break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        variables_response = json_facade.get_variables_response(json_hit.frame_id)

        variables_references = variables_response.body.variables
        for dct in variables_references:
            if dct["name"] == "dct":
                break
        else:
            raise AssertionError('Expected to find "dct".')
        ref = dct["variablesReference"]

        assert isinstance(ref, int_types)
        # : :type variables_response: VariablesResponse

        variables_response = json_facade.get_variables_response(ref)
        variable_names = set(v["name"] for v in variables_response.body.variables)
        for n in ("'a'", "'_b_'", "'__c__'", "len()"):
            assert n in variable_names

        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.skipif(IS_JYTHON, reason="Putting unicode on frame vars does not work on Jython.")
def test_stack_and_variables_dict(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_local_variables.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break 2 here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        variables_response = json_facade.get_variables_response(json_hit.frame_id)

        variables_references = json_facade.pop_variables_reference(variables_response.body.variables)
        dict_variable_reference = variables_references[2]
        assert isinstance(dict_variable_reference, int_types)
        # : :type variables_response: VariablesResponse

        expected_unicode = {
            "name": "\u16a0",
            "value": "'\u16a1'",
            "type": "str",
            "presentationHint": {"attributes": ["rawString"]},
            "evaluateName": "\u16a0",
        }
        assert variables_response.body.variables == [
            {"name": "variable_for_test_1", "value": "10", "type": "int", "evaluateName": "variable_for_test_1"},
            {"name": "variable_for_test_2", "value": "20", "type": "int", "evaluateName": "variable_for_test_2"},
            {"name": "variable_for_test_3", "value": "{'a': 30, 'b': 20}", "type": "dict", "evaluateName": "variable_for_test_3"},
            expected_unicode,
        ]

        variables_response = json_facade.get_variables_response(dict_variable_reference)
        check = [x for x in variables_response.body.variables if x["name"] not in DAPGrouper.SCOPES_SORTED]
        assert check == [
            {"name": "'a'", "value": "30", "type": "int", "evaluateName": "variable_for_test_3['a']", "variablesReference": 0},
            {"name": "'b'", "value": "20", "type": "int", "evaluateName": "variable_for_test_3['b']", "variablesReference": 0},
            {
                "name": GENERATED_LEN_ATTR_NAME,
                "value": "2",
                "type": "int",
                "evaluateName": "len(variable_for_test_3)",
                "variablesReference": 0,
                "presentationHint": {"attributes": ["readOnly"]},
            },
        ]

        json_facade.write_continue()
        writer.finished_ok = True


def test_variables_with_same_name(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_variables_with_same_name.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        variables_response = json_facade.get_variables_response(json_hit.frame_id)

        variables_references = json_facade.pop_variables_reference(variables_response.body.variables)
        dict_variable_reference = variables_references[0]
        assert isinstance(dict_variable_reference, int_types)
        # : :type variables_response: VariablesResponse

        assert variables_response.body.variables == [
            {"name": "td", "value": "{foo: 'bar', gad: 'zooks', foo: 'bur'}", "type": "dict", "evaluateName": "td"}
        ]

        dict_variables_response = json_facade.get_variables_response(dict_variable_reference)
        # Note that we don't have the evaluateName because it's not possible to create a key
        # from the user object to actually get its value from the dict in this case.
        variables = dict_variables_response.body.variables[:]

        found_foo = False
        found_foo_with_id = False
        for v in variables:
            if v["name"].startswith("foo"):
                if not found_foo:
                    assert v["name"] == "foo"
                    found_foo = True
                else:
                    assert v["name"].startswith("foo (id: ")
                    v["name"] = "foo"
                    found_foo_with_id = True

        assert found_foo
        assert found_foo_with_id

        def compute_key(entry):
            return (entry["name"], entry["value"])

        # Sort because the order may be different on Py2/Py3.
        assert sorted(variables, key=compute_key) == sorted(
            [
                {
                    "name": "foo",
                    "value": "'bar'",
                    "type": "str",
                    "variablesReference": 0,
                    "presentationHint": {"attributes": ["rawString"]},
                },
                {
                    # 'name': 'foo (id: 2699272929584)', In the code above we changed this
                    # to 'name': 'foo' for the comparisson.
                    "name": "foo",
                    "value": "'bur'",
                    "type": "str",
                    "variablesReference": 0,
                    "presentationHint": {"attributes": ["rawString"]},
                },
                {
                    "name": "gad",
                    "value": "'zooks'",
                    "type": "str",
                    "variablesReference": 0,
                    "presentationHint": {"attributes": ["rawString"]},
                },
                {
                    "name": "len()",
                    "value": "3",
                    "type": "int",
                    "evaluateName": "len(td)",
                    "variablesReference": 0,
                    "presentationHint": {"attributes": ["readOnly"]},
                },
            ],
            key=compute_key,
        )

        json_facade.write_continue()
        writer.finished_ok = True


def test_hasattr_failure(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_hasattr_crash.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        variables_response = json_facade.get_variables_response(json_hit.frame_id)

        for variable in variables_response.body.variables:
            if variable["evaluateName"] == "obj":
                break
        else:
            raise AssertionError('Did not find "obj" in %s' % (variables_response.body.variables,))

        evaluate_response = json_facade.evaluate("obj", json_hit.frame_id, context="hover")
        evaluate_response_body = evaluate_response.body.to_dict()
        assert evaluate_response_body["result"] == "An exception was raised: RuntimeError()"

        json_facade.evaluate("not_there", json_hit.frame_id, context="hover", success=False)
        json_facade.evaluate("not_there", json_hit.frame_id, context="watch", success=False)

        json_facade.write_continue()

        writer.finished_ok = True


def test_getattr_warning(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_warnings.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        variables_response = json_facade.get_variables_response(json_hit.frame_id)

        for variable in variables_response.body.variables:
            if variable["evaluateName"] == "obj":
                break
        else:
            raise AssertionError('Did not find "obj" in %s' % (variables_response.body.variables,))

        json_facade.evaluate("obj", json_hit.frame_id, context="hover")
        json_facade.evaluate("not_there", json_hit.frame_id, context="hover", success=False)
        json_facade.evaluate("not_there", json_hit.frame_id, context="watch", success=False)

        json_facade.write_continue()

        # i.e.: the test will fail if anything is printed to stderr!
        writer.finished_ok = True


def test_warning_on_repl(case_setup_dap):
    def additional_output_checks(writer, stdout, stderr):
        assert "WarningCalledOnRepl" in stderr

    with case_setup_dap.test_file("_debugger_case_evaluate.py", additional_output_checks=additional_output_checks) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        # We want warnings from the in evaluate in the repl (but not hover/watch).
        json_facade.evaluate('import warnings; warnings.warn("WarningCalledOnRepl")', json_hit.frame_id, context="repl")

        json_facade.write_continue()

        writer.finished_ok = True


def test_evaluate_none(case_setup_dap, pyfile):
    @pyfile
    def eval_none():
        print("TEST SUCEEDED")  # break here

    with case_setup_dap.test_file(eval_none) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(justMyCode=False)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        evaluate_response = json_facade.evaluate("None", json_hit.frame_id, context="repl")
        assert evaluate_response.body.result is not None
        assert evaluate_response.body.result == ""

        json_facade.write_continue()

        writer.finished_ok = True


def test_evaluate_numpy(case_setup_dap, pyfile):
    try:
        import numpy
    except ImportError:
        pytest.skip("numpy not available")

    @pyfile
    def numpy_small_array_file():
        import numpy

        test_array = numpy.array(2)

        print("TEST SUCEEDED")  # break here

    with case_setup_dap.test_file(numpy_small_array_file) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(justMyCode=False)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        variables_response = json_facade.get_variables_response(json_hit.frame_id)

        for variable in variables_response.body.variables:
            if variable["evaluateName"] == "test_array":
                break
        else:
            raise AssertionError('Did not find "test_array" in %s' % (variables_response.body.variables,))

        evaluate_response = json_facade.evaluate("test_array", json_hit.frame_id, context="repl")

        variables_response = json_facade.get_variables_response(evaluate_response.body.variablesReference)

        check = [dict([(variable["name"], variable["value"])]) for variable in variables_response.body.variables]
        assert check in (
            [
                {"special variables": ""},
                {"dtype": "dtype('int64')"},
                {"max": "np.int64(2)"},
                {"min": "np.int64(2)"},
                {"shape": "()"},
                {"size": "1"},
            ],
            [
                {"special variables": ""},
                {"dtype": "dtype('int32')"},
                {"max": "np.int32(2)"},
                {"min": "np.int32(2)"},
                {"shape": "()"},
                {"size": "1"},
            ],
            [{"special variables": ""}, {"dtype": "dtype('int32')"}, {"max": "2"}, {"min": "2"}, {"shape": "()"}, {"size": "1"}],
            [{"special variables": ""}, {"dtype": "dtype('int64')"}, {"max": "2"}, {"min": "2"}, {"shape": "()"}, {"size": "1"}],
            [
                {"special variables": ""},
                {"dtype": "dtype('int64')"},
                {"max": "np.int64(2)"},
                {"min": "np.int64(2)"},
                {"shape": "()"},
                {"size": "1"},
            ],
        ), "Found: %s" % (check,)

        json_facade.write_continue()

        writer.finished_ok = True


def test_evaluate_name_mangling(case_setup_dap, pyfile):
    @pyfile
    def target():
        class SomeObj(object):
            def __init__(self):
                self.__value = 10
                print("here")  # Break here

        SomeObj()

        print("TEST SUCEEDED")

    with case_setup_dap.test_file(target) as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))
        json_facade.write_launch(justMyCode=False)
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        # Check eval with a properly indented block
        evaluate_response = json_facade.evaluate(
            "self.__value",
            frameId=json_hit.frame_id,
            context="repl",
        )

        assert evaluate_response.body.result == "10"
        json_facade.write_continue()
        writer.finished_ok = True


def test_evaluate_no_name_mangling(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_local_variables2.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        # Check eval with a properly indented block
        evaluate_response = json_facade.evaluate('x = "_"', frameId=json_hit.frame_id, context="repl")
        assert not evaluate_response.body.result

        evaluate_response = json_facade.evaluate("x", frameId=json_hit.frame_id, context="repl")
        assert evaluate_response.body.result == "'_'"

        evaluate_response = json_facade.evaluate('y = "__"', frameId=json_hit.frame_id, context="repl")
        assert not evaluate_response.body.result

        evaluate_response = json_facade.evaluate("y", frameId=json_hit.frame_id, context="repl")
        assert evaluate_response.body.result == "'__'"

        evaluate_response = json_facade.evaluate("None", json_hit.frame_id, context="repl")
        assert not evaluate_response.body.result

        json_facade.write_continue()
        writer.finished_ok = True


def test_evaluate_block_repl(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_local_variables2.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        # Check eval with a properly indented block
        json_facade.evaluate(
            "for i in range(2):\n  print('var%s' % i)",
            frameId=json_hit.frame_id,
            context="repl",
        )

        messages = json_facade.mark_messages(OutputEvent, lambda output_event: "var0" in output_event.body.output)
        assert len(messages) == 1
        messages = json_facade.mark_messages(OutputEvent, lambda output_event: "var1" in output_event.body.output)
        assert len(messages) == 1

        # Check eval with a block that needs to be dedented
        json_facade.evaluate(
            "  for i in range(2):\n    print('foo%s' % i)",
            frameId=json_hit.frame_id,
            context="repl",
        )

        messages = json_facade.mark_messages(OutputEvent, lambda output_event: "foo0" in output_event.body.output)
        assert len(messages) == 1
        messages = json_facade.mark_messages(OutputEvent, lambda output_event: "foo1" in output_event.body.output)
        assert len(messages) == 1

        json_facade.write_continue()
        writer.finished_ok = True


def test_evaluate_block_clipboard(case_setup_dap, pyfile):
    @pyfile
    def target():
        MAX_LIMIT = 65538

        class SomeObj(object):
            def __str__(self):
                return var1

            __repr__ = __str__

        var1 = "a" * 80000
        var2 = 20000
        var3 = SomeObj()

        print("TEST SUCEEDED")  # Break here

    def verify(evaluate_response):
        # : :type evaluate_response: EvaluateResponse
        assert len(evaluate_response.body.result) >= 80000
        assert "..." not in evaluate_response.body.result
        assert set(evaluate_response.body.result).issubset(set(["a", "'"]))

    with case_setup_dap.test_file(target) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)
        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        evaluate_response = json_facade.evaluate(
            "var1",
            frameId=json_hit.frame_id,
            context="clipboard",
        )
        verify(evaluate_response)

        evaluate_response = json_facade.evaluate("var2", frameId=json_hit.frame_id, context="clipboard", fmt={"hex": True})
        assert evaluate_response.body.result == "0x4e20"

        evaluate_response = json_facade.evaluate(
            "var3",
            frameId=json_hit.frame_id,
            context="clipboard",
        )
        verify(evaluate_response)

        json_facade.write_continue()
        writer.finished_ok = True


def test_exception_on_dir(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_dir_exception.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        variables_response = json_facade.get_variables_response(json_hit.frame_id)

        variables_references = json_facade.pop_variables_reference(variables_response.body.variables)
        variables_response = json_facade.get_variables_response(variables_references[0])
        assert variables_response.body.variables == [
            {"variablesReference": 0, "type": "int", "evaluateName": "self.__dict__[var1]", "name": "var1", "value": "10"}
        ]

        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.parametrize(
    "scenario",
    [
        "step_in",
        "step_next",
        "step_out",
    ],
)
@pytest.mark.parametrize("asyncio", [True, False])
def test_return_value_regular(case_setup_dap, scenario, asyncio):
    with case_setup_dap.test_file("_debugger_case_return_value.py" if not asyncio else "_debugger_case_return_value_asyncio.py") as writer:
        json_facade = JsonFacade(writer)

        break_line = writer.get_line_index_with_content("break here")
        json_facade.write_launch(debugOptions=["ShowReturnValue"])
        json_facade.write_set_breakpoints(break_line)
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        if scenario == "step_next":
            json_facade.write_step_next(json_hit.thread_id)
            json_hit = json_facade.wait_for_thread_stopped("step", name="main", line=break_line + 1)

        elif scenario == "step_in":
            json_facade.write_step_in(json_hit.thread_id)
            json_hit = json_facade.wait_for_thread_stopped("step", name="method1")

            json_facade.write_step_in(json_hit.thread_id)
            json_hit = json_facade.wait_for_thread_stopped("step", name="main")

        elif scenario == "step_out":
            json_facade.write_step_in(json_hit.thread_id)
            json_hit = json_facade.wait_for_thread_stopped("step", name="method1")

            json_facade.write_step_out(json_hit.thread_id)
            json_hit = json_facade.wait_for_thread_stopped("step", name="main")

        else:
            raise AssertionError("unhandled scenario: %s" % (scenario,))

        variables_response = json_facade.get_variables_response(json_hit.frame_id)
        return_variables = json_facade.filter_return_variables(variables_response.body.variables)
        assert return_variables == [
            {
                "name": "(return) method1",
                "value": "1",
                "type": "int",
                "evaluateName": "__pydevd_ret_val_dict['method1']",
                "presentationHint": {"attributes": ["readOnly"]},
                "variablesReference": 0,
            }
        ]

        json_facade.write_continue()
        writer.finished_ok = True


def test_stack_and_variables_set_and_list(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_local_variables2.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()
        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)
        variables_response = json_facade.get_variables_response(json_hit.frame_id)

        variables_references = json_facade.pop_variables_reference(variables_response.body.variables)
        expected_set = "{'a'}"
        assert variables_response.body.variables == [
            {"type": "list", "evaluateName": "variable_for_test_1", "name": "variable_for_test_1", "value": "['a', 'b']"},
            {"type": "set", "evaluateName": "variable_for_test_2", "name": "variable_for_test_2", "value": expected_set},
        ]

        variables_response = json_facade.get_variables_response(variables_references[0])
        cleaned_vars = _clear_groups(variables_response.body.variables)
        if IS_PYPY:
            # Functions are not found in PyPy.
            assert cleaned_vars.groups_found == set([DAPGrouper.SCOPE_SPECIAL_VARS])
        else:
            assert cleaned_vars.groups_found == set([DAPGrouper.SCOPE_SPECIAL_VARS, DAPGrouper.SCOPE_FUNCTION_VARS])
        assert cleaned_vars.variables == [
            {
                "name": "0",
                "type": "str",
                "value": "'a'",
                "presentationHint": {"attributes": ["rawString"]},
                "evaluateName": "variable_for_test_1[0]",
                "variablesReference": 0,
            },
            {
                "name": "1",
                "type": "str",
                "value": "'b'",
                "presentationHint": {"attributes": ["rawString"]},
                "evaluateName": "variable_for_test_1[1]",
                "variablesReference": 0,
            },
            {
                "name": GENERATED_LEN_ATTR_NAME,
                "type": "int",
                "value": "2",
                "evaluateName": "len(variable_for_test_1)",
                "variablesReference": 0,
                "presentationHint": {"attributes": ["readOnly"]},
            },
        ]

        json_facade.write_continue()
        writer.finished_ok = True


_CleanedVars = namedtuple("_CleanedVars", "variables, groups_found")


def _clear_groups(variables):
    groups_found = set()
    new_variables = []
    for v in variables:
        if v["name"] in DAPGrouper.SCOPES_SORTED:
            groups_found.add(v["name"])
            assert not v["type"]
            continue

        else:
            new_variables.append(v)

    return _CleanedVars(new_variables, groups_found)


@pytest.mark.skipif(IS_JYTHON, reason="Putting unicode on frame vars does not work on Jython.")
def test_evaluate_unicode(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_local_variables.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break 2 here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        evaluate_response = json_facade.evaluate("\u16a0", json_hit.frame_id)

        evaluate_response_body = evaluate_response.body.to_dict()

        assert evaluate_response_body == {
            "result": "'\u16a1'",
            "type": "str",
            "variablesReference": 0,
            "presentationHint": {"attributes": ["rawString"]},
        }

        json_facade.write_continue()
        writer.finished_ok = True


def test_evaluate_exec_unicode(case_setup_dap):
    def get_environ(writer):
        env = os.environ.copy()

        env["PYTHONIOENCODING"] = "utf-8"
        return env

    with case_setup_dap.test_file("_debugger_case_local_variables2.py", get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)
        writer.write_start_redirect()

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        # Check eval
        json_facade.evaluate(
            "print(u'中')",
            frameId=json_hit.frame_id,
            context="repl",
        )

        messages = json_facade.mark_messages(
            OutputEvent, lambda output_event: ("中" in output_event.body.output) and ("pydevd warning" not in output_event.body.output)
        )
        assert len(messages) == 1

        # Check exec
        json_facade.evaluate(
            "a=10;print(u'中')",
            frameId=json_hit.frame_id,
            context="repl",
        )

        messages = json_facade.mark_messages(
            OutputEvent, lambda output_event: ("中" in output_event.body.output) and ("pydevd warning" not in output_event.body.output)
        )
        assert len(messages) == 1

        response = json_facade.evaluate(
            "u'中'",
            frameId=json_hit.frame_id,
            context="repl",
        )
        assert response.body.result in ("u'\\u4e2d'", "'\u4e2d'")  # py2 or py3

        messages = json_facade.mark_messages(
            OutputEvent, lambda output_event: ("中" in output_event.body.output) and ("pydevd warning" not in output_event.body.output)
        )
        assert len(messages) == 0  # i.e.: we don't print in this case.

        json_facade.write_continue()
        writer.finished_ok = True


def test_evaluate_repl_redirect(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_local_variables2.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        # Check eval
        json_facade.evaluate(
            "print('var')",
            frameId=json_hit.frame_id,
            context="repl",
        )

        messages = json_facade.mark_messages(OutputEvent, lambda output_event: "var" in output_event.body.output)
        assert len(messages) == 1

        json_facade.write_continue()
        writer.finished_ok = True


def test_evaluate_no_double_exec(case_setup_dap, pyfile):
    @pyfile
    def exec_code():
        def print_and_raise():
            print("Something")
            raise RuntimeError()

        print("Break here")
        print("TEST SUCEEDED!")

    with case_setup_dap.test_file(exec_code) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)
        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        json_facade.evaluate(
            "print_and_raise()",
            frameId=json_hit.frame_id,
            context="repl",
            success=False,
        )

        messages = json_facade.mark_messages(OutputEvent, lambda output_event: "Something" in output_event.body.output)
        assert len(messages) == 1

        json_facade.write_continue()
        writer.finished_ok = True


def test_evaluate_variable_references(case_setup_dap):
    from _pydevd_bundle._debug_adapter.pydevd_schema import EvaluateRequest
    from _pydevd_bundle._debug_adapter.pydevd_schema import EvaluateArguments

    with case_setup_dap.test_file("_debugger_case_local_variables2.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        evaluate_response = json_facade.wait_for_response(
            json_facade.write_request(EvaluateRequest(EvaluateArguments("variable_for_test_2", json_hit.frame_id)))
        )

        evaluate_response_body = evaluate_response.body.to_dict()

        variables_reference = json_facade.pop_variables_reference([evaluate_response_body])

        assert evaluate_response_body == {
            "type": "set",
            "result": "{'a'}",
            "presentationHint": {},
        }
        assert len(variables_reference) == 1
        reference = variables_reference[0]
        assert reference > 0
        variables_response = json_facade.get_variables_response(reference)
        child_variables = variables_response.to_dict()["body"]["variables"]

        # The name for a reference in a set is the id() of the variable and can change at each run.
        del child_variables[0]["name"]

        assert child_variables == [
            {
                "type": "str",
                "value": "'a'",
                "presentationHint": {"attributes": ["rawString"]},
                "variablesReference": 0,
            },
            {
                "name": GENERATED_LEN_ATTR_NAME,
                "type": "int",
                "value": "1",
                "presentationHint": {"attributes": ["readOnly"]},
                "evaluateName": "len(variable_for_test_2)",
                "variablesReference": 0,
            },
        ]

        json_facade.write_continue()
        writer.finished_ok = True


def test_set_expression(case_setup_dap):
    from _pydevd_bundle._debug_adapter.pydevd_schema import SetExpressionRequest
    from _pydevd_bundle._debug_adapter.pydevd_schema import SetExpressionArguments

    with case_setup_dap.test_file("_debugger_case_local_variables2.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        set_expression_response = json_facade.wait_for_response(
            json_facade.write_request(SetExpressionRequest(SetExpressionArguments("bb", "20", frameId=json_hit.frame_id)))
        )
        assert set_expression_response.to_dict()["body"] == {"value": "20", "type": "int", "presentationHint": {}, "variablesReference": 0}

        variables_response = json_facade.get_variables_response(json_hit.frame_id)
        assert {"name": "bb", "value": "20", "type": "int", "evaluateName": "bb", "variablesReference": 0} in variables_response.to_dict()[
            "body"
        ]["variables"]

        json_facade.write_continue()
        writer.finished_ok = True


def test_set_expression_failures(case_setup_dap):
    from _pydevd_bundle._debug_adapter.pydevd_schema import SetExpressionRequest
    from _pydevd_bundle._debug_adapter.pydevd_schema import SetExpressionArguments

    with case_setup_dap.test_file("_debugger_case_local_variables2.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)

        set_expression_response = json_facade.wait_for_response(
            json_facade.write_request(SetExpressionRequest(SetExpressionArguments("frame_not_there", "10", frameId=0)))
        )
        assert not set_expression_response.success
        assert set_expression_response.message == "Unable to find thread to set expression."

        json_facade.write_continue()

        writer.finished_ok = True


def test_get_variable_errors(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_completions.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        # First, try with wrong id.
        response = json_facade.get_variables_response(9999, success=False)
        assert response.message == "Wrong ID sent from the client: 9999"

        first_hit = None
        for i in range(2):
            json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)
            if i == 0:
                first_hit = json_hit

            if i == 1:
                # Now, check with a previously existing frameId.
                response = json_facade.get_variables_response(first_hit.frame_id, success=False)
                assert response.message == "Unable to find thread to evaluate variable reference."

            json_facade.write_continue(wait_for_response=i == 0)
            if i == 0:
                json_hit = json_facade.wait_for_thread_stopped()

        writer.finished_ok = True


def test_set_variable_failure(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_local_variables2.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()

        json_facade.wait_for_thread_stopped()

        # Wrong frame
        set_variable_response = json_facade.write_set_variable(0, "invalid_reference", "invalid_reference", success=False)
        assert not set_variable_response.success
        assert set_variable_response.message == "Unable to find thread to evaluate variable reference."

        json_facade.write_continue()

        writer.finished_ok = True


def _check_list(json_facade, json_hit):
    variable = json_facade.get_local_var(json_hit.frame_id, "variable_for_test_1")
    assert variable.value == "['a', 'b', self.var1: 11]"

    var0 = json_facade.get_var(variable.variablesReference, "0")

    json_facade.write_set_variable(variable.variablesReference, var0.name, "1")

    # Check that it was actually changed.
    variable = json_facade.get_local_var(json_hit.frame_id, "variable_for_test_1")
    assert variable.value == "[1, 'b', self.var1: 11]"

    var1 = json_facade.get_var(variable.variablesReference, "var1")

    json_facade.write_set_variable(variable.variablesReference, var1.name, "2")

    variable = json_facade.get_local_var(json_hit.frame_id, "variable_for_test_1")
    assert variable.value == "[1, 'b', self.var1: 2]"


def _check_tuple(json_facade, json_hit):
    variable = json_facade.get_local_var(json_hit.frame_id, "variable_for_test_4")
    assert variable.value == "tuple('a', 1, self.var1: 13)"

    var0 = json_facade.get_var(variable.variablesReference, "0")

    response = json_facade.write_set_variable(variable.variablesReference, var0.name, "1", success=False)
    assert response.message.startswith("Unable to change: ")

    var1 = json_facade.get_var(variable.variablesReference, "var1")
    json_facade.write_set_variable(variable.variablesReference, var1.name, "2")

    variable = json_facade.get_local_var(json_hit.frame_id, "variable_for_test_4")
    assert variable.value == "tuple('a', 1, self.var1: 2)"


def _check_dict_subclass(json_facade, json_hit):
    variable = json_facade.get_local_var(json_hit.frame_id, "variable_for_test_3")
    assert variable.value == "{in_dct: 20; self.var1: 10}"

    var1 = json_facade.get_var(variable.variablesReference, "var1")

    json_facade.write_set_variable(variable.variablesReference, var1.name, "2")

    # Check that it was actually changed.
    variable = json_facade.get_local_var(json_hit.frame_id, "variable_for_test_3")
    assert variable.value == "{in_dct: 20; self.var1: 2}"

    var_in_dct = json_facade.get_var(variable.variablesReference, "'in_dct'")

    json_facade.write_set_variable(variable.variablesReference, var_in_dct.name, "5")

    # Check that it was actually changed.
    variable = json_facade.get_local_var(json_hit.frame_id, "variable_for_test_3")
    assert variable.value == "{in_dct: 5; self.var1: 2}"


def _check_set(json_facade, json_hit):
    set_var = json_facade.get_local_var(json_hit.frame_id, "variable_for_test_2")

    assert set_var.value == "set(['a', self.var1: 12])"

    var_in_set = json_facade.get_var(set_var.variablesReference, index=1)
    assert var_in_set.name != "var1"

    set_variables_response = json_facade.write_set_variable(set_var.variablesReference, var_in_set.name, "1")
    assert set_variables_response.body.type == "int"
    assert set_variables_response.body.value == "1"

    # Check that it was actually changed (which for a set means removing the existing entry
    # and adding a new one).
    set_var = json_facade.get_local_var(json_hit.frame_id, "variable_for_test_2")
    assert set_var.value == "set([1, self.var1: 12])"

    # Check that it can be changed again.
    var_in_set = json_facade.get_var(set_var.variablesReference, index=1)

    # Check that adding a mutable object to the set does not work.
    response = json_facade.write_set_variable(set_var.variablesReference, var_in_set.name, "[22]", success=False)
    assert response.message.startswith("Unable to change: ")

    # Check that it's still the same (the existing entry was not removed).
    assert json_facade.get_local_var(json_hit.frame_id, "variable_for_test_2").value == "set([1, self.var1: 12])"

    set_variables_response = json_facade.write_set_variable(set_var.variablesReference, var_in_set.name, "(22,)")
    assert set_variables_response.body.type == "tuple"
    assert set_variables_response.body.value == "(22,)"

    # Check that the tuple created can be accessed and is correct in the response.
    var_in_tuple_in_set = json_facade.get_var(set_variables_response.body.variablesReference, "0")
    assert var_in_tuple_in_set.name == "0"
    assert var_in_tuple_in_set.value == "22"

    # Check that we can change the variable in the instance.
    var1 = json_facade.get_var(set_var.variablesReference, "var1")

    json_facade.write_set_variable(set_var.variablesReference, var1.name, "2")

    # Check that it was actually changed.
    set_var = json_facade.get_local_var(json_hit.frame_id, "variable_for_test_2")
    assert set_var.value == "set([(22,), self.var1: 2])"


@pytest.mark.parametrize(
    "_check_func",
    [
        _check_tuple,
        _check_set,
        _check_list,
        _check_dict_subclass,
    ],
)
def test_set_variable_multiple_cases(case_setup_dap, _check_func):
    with case_setup_dap.test_file("_debugger_case_local_variables3.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        _check_func(json_facade, json_hit)

        json_facade.write_continue()

        writer.finished_ok = True


def test_get_variables_corner_case(case_setup_dap, pyfile):
    @pyfile
    def case_with_class_as_object():
        class ClassField(object):
            __name__ = "name?"

            def __hash__(self):
                raise RuntimeError()

        class SomeClass(object):
            __class__ = ClassField()

        some_class = SomeClass()
        print("TEST SUCEEDED")  # Break here

    with case_setup_dap.test_file(case_with_class_as_object) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)
        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        set_var = json_facade.get_local_var(json_hit.frame_id, "some_class")
        assert "__main__.SomeClass" in set_var.value

        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.skipif(IS_JYTHON, reason="Putting unicode on frame vars does not work on Jython.")
def test_stack_and_variables(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_local_variables.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        # : :type stack_trace_response: StackTraceResponse
        # : :type stack_trace_response_body: StackTraceResponseBody
        # : :type stack_frame: StackFrame

        # Check stack trace format.
        stack_trace_request = json_facade.write_request(
            pydevd_schema.StackTraceRequest(
                pydevd_schema.StackTraceArguments(threadId=json_hit.thread_id, format={"module": True, "line": True})
            )
        )
        stack_trace_response = json_facade.wait_for_response(stack_trace_request)
        stack_trace_response_body = stack_trace_response.body
        stack_frame = next(iter(stack_trace_response_body.stackFrames))
        assert stack_frame["name"] == "__main__.Call : 4"

        # Regular stack trace request (no format).
        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)
        stack_trace_response = json_hit.stack_trace_response
        stack_trace_response_body = stack_trace_response.body
        assert len(stack_trace_response_body.stackFrames) == 2
        stack_frame = next(iter(stack_trace_response_body.stackFrames))
        assert stack_frame["name"] == "Call"
        assert stack_frame["source"]["path"].endswith("_debugger_case_local_variables.py")

        name_to_scope = json_facade.get_name_to_scope(stack_frame["id"])
        scope = name_to_scope["Locals"]
        frame_variables_reference = scope.variablesReference
        assert isinstance(frame_variables_reference, int)

        variables_response = json_facade.get_variables_response(frame_variables_reference)
        # : :type variables_response: VariablesResponse
        assert len(variables_response.body.variables) == 0  # No variables expected here

        json_facade.write_step_next(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step")

        variables_response = json_facade.get_variables_response(frame_variables_reference)
        # : :type variables_response: VariablesResponse
        assert variables_response.body.variables == [
            {
                "name": "variable_for_test_1",
                "value": "10",
                "type": "int",
                "evaluateName": "variable_for_test_1",
                "variablesReference": 0,
            }
        ]

        # Same thing with hex format
        variables_response = json_facade.get_variables_response(frame_variables_reference, fmt={"hex": True})
        # : :type variables_response: VariablesResponse
        assert variables_response.body.variables == [
            {
                "name": "variable_for_test_1",
                "value": "0xa",
                "type": "int",
                "evaluateName": "variable_for_test_1",
                "variablesReference": 0,
            }
        ]

        # Note: besides the scope/stack/variables we can also have references when:
        # - setting variable
        #    * If the variable was changed to a container, the new reference should be returned.
        # - evaluate expression
        #    * Currently ptvsd returns a None value in on_setExpression, so, skip this for now.
        # - output
        #    * Currently not handled by ptvsd, so, skip for now.

        # Reference is for parent (in this case the frame).
        # We'll change `variable_for_test_1` from 10 to [1].
        set_variable_response = json_facade.write_set_variable(frame_variables_reference, "variable_for_test_1", "[1]")
        set_variable_response_as_dict = set_variable_response.to_dict()["body"]
        if not IS_JYTHON:
            # Not properly changing var on Jython.
            assert isinstance(set_variable_response_as_dict.pop("variablesReference"), int)
            assert set_variable_response_as_dict == {"value": "[1]", "type": "list"}

        variables_response = json_facade.get_variables_response(frame_variables_reference)
        # : :type variables_response: VariablesResponse
        variables = variables_response.body.variables
        assert len(variables) == 1
        var_as_dict = next(iter(variables))
        if not IS_JYTHON:
            # Not properly changing var on Jython.
            assert isinstance(var_as_dict.pop("variablesReference"), int)
            assert var_as_dict == {
                "name": "variable_for_test_1",
                "value": "[1]",
                "type": "list",
                "evaluateName": "variable_for_test_1",
            }

        json_facade.write_continue()

        writer.finished_ok = True


def test_hex_variables(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_local_variables_hex.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        # : :type stack_trace_response: StackTraceResponse
        # : :type stack_trace_response_body: StackTraceResponseBody
        # : :type stack_frame: StackFrame
        stack_trace_request = json_facade.write_request(
            pydevd_schema.StackTraceRequest(pydevd_schema.StackTraceArguments(threadId=json_hit.thread_id))
        )
        stack_trace_response = json_facade.wait_for_response(stack_trace_request)
        stack_trace_response_body = stack_trace_response.body
        assert len(stack_trace_response_body.stackFrames) == 2
        stack_frame = next(iter(stack_trace_response_body.stackFrames))
        assert stack_frame["name"] == "Call"
        assert stack_frame["source"]["path"].endswith("_debugger_case_local_variables_hex.py")

        name_to_scope = json_facade.get_name_to_scope(stack_frame["id"])

        scope = name_to_scope["Locals"]
        frame_variables_reference = scope.variablesReference
        assert isinstance(frame_variables_reference, int)

        fmt = {"hex": True}
        variables_request = json_facade.write_request(
            pydevd_schema.VariablesRequest(pydevd_schema.VariablesArguments(frame_variables_reference, format=fmt))
        )
        variables_response = json_facade.wait_for_response(variables_request)

        # : :type variables_response: VariablesResponse
        variable_for_test_1, variable_for_test_2, variable_for_test_3, variable_for_test_4 = sorted(
            list(v for v in variables_response.body.variables if v["name"].startswith("variables_for_test")), key=lambda v: v["name"]
        )
        assert variable_for_test_1 == {
            "name": "variables_for_test_1",
            "value": "0x64",
            "type": "int",
            "evaluateName": "variables_for_test_1",
            "variablesReference": 0,
        }

        assert isinstance(variable_for_test_2.pop("variablesReference"), int)
        assert variable_for_test_2 == {
            "name": "variables_for_test_2",
            "value": "[0x1, 0xa, 0x64]",
            "type": "list",
            "evaluateName": "variables_for_test_2",
        }

        assert isinstance(variable_for_test_3.pop("variablesReference"), int)
        assert variable_for_test_3 == {
            "name": "variables_for_test_3",
            "value": "{0xa: 0xa, 0x64: 0x64, 0x3e8: 0x3e8}",
            "type": "dict",
            "evaluateName": "variables_for_test_3",
        }

        assert isinstance(variable_for_test_4.pop("variablesReference"), int)
        assert variable_for_test_4 == {
            "name": "variables_for_test_4",
            "value": "{(0x1, 0xa, 0x64): (0x2710, 0x186a0, 0x186a0)}",
            "type": "dict",
            "evaluateName": "variables_for_test_4",
        }

        json_facade.write_continue()

        writer.finished_ok = True


def test_stopped_event(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_print.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        assert json_hit.thread_id

        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.skipif(IS_JYTHON, reason="Not Jython compatible (fails on set variable).")
def test_pause_and_continue(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_pause_continue.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()

        json_facade.wait_for_thread_stopped()

        json_facade.write_continue()

        json_facade.write_pause()

        json_hit = json_facade.wait_for_thread_stopped(reason="pause")

        stack_frame = next(iter(json_hit.stack_trace_response.body.stackFrames))

        name_to_scope = json_facade.get_name_to_scope(stack_frame["id"])
        frame_variables_reference = name_to_scope["Locals"].variablesReference

        set_variable_response = json_facade.write_set_variable(frame_variables_reference, "loop", "False")
        set_variable_response_as_dict = set_variable_response.to_dict()["body"]
        assert set_variable_response_as_dict == {"value": "False", "type": "bool", "variablesReference": 0}

        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.parametrize("stepping_resumes_all_threads", [False, True])
def test_step_out_multi_threads(case_setup_dap, stepping_resumes_all_threads):
    with case_setup_dap.test_file("_debugger_case_multi_threads_stepping.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(steppingResumesAllThreads=stepping_resumes_all_threads)
        json_facade.write_set_breakpoints(
            [
                writer.get_line_index_with_content("Break thread 1"),
            ]
        )
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        response = json_facade.write_list_threads()
        assert len(response.body.threads) == 3

        thread_name_to_id = dict((t["name"], t["id"]) for t in response.body.threads)
        assert json_hit.thread_id == thread_name_to_id["thread1"]

        if stepping_resumes_all_threads:
            # If we're stepping with multiple threads, we'll exit here.
            json_facade.write_step_out(thread_name_to_id["thread1"])
        else:
            json_facade.write_step_out(thread_name_to_id["thread1"])

            # Timeout is expected... make it shorter.
            writer.reader_thread.set_messages_timeout(2)
            try:
                json_hit = json_facade.wait_for_thread_stopped("step")
                raise AssertionError("Expected timeout!")
            except debugger_unittest.TimeoutError:
                pass

            json_facade.write_step_out(thread_name_to_id["thread2"])
            json_facade.write_step_next(thread_name_to_id["MainThread"])
            json_hit = json_facade.wait_for_thread_stopped("step")
            assert json_hit.thread_id == thread_name_to_id["MainThread"] or json_hit.thread_id == thread_name_to_id["thread2"]
            json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.parametrize("stepping_resumes_all_threads", [True, False])
@pytest.mark.parametrize("step_mode", ["step_next", "step_in"])
def test_step_next_step_in_multi_threads(case_setup_dap, stepping_resumes_all_threads, step_mode):
    with case_setup_dap.test_file("_debugger_case_multi_threads_stepping.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(steppingResumesAllThreads=stepping_resumes_all_threads, justMyCode=True)
        json_facade.write_set_breakpoints(
            [
                writer.get_line_index_with_content("Break thread 1"),
            ]
        )
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        response = json_facade.write_list_threads()
        assert len(response.body.threads) == 3

        thread_name_to_id = dict((t["name"], t["id"]) for t in response.body.threads)
        assert json_hit.thread_id == thread_name_to_id["thread1"]

        stopped_events = json_facade.mark_messages(StoppedEvent)
        assert len(stopped_events) == 1

        timeout_at = time.time() + 30
        checks = 0

        while True:
            checks += 1

            if step_mode == "step_next":
                json_facade.write_step_next(thread_name_to_id["thread1"])

            elif step_mode == "step_in":
                json_facade.write_step_in(thread_name_to_id["thread1"])

            else:
                raise AssertionError("Unexpected step_mode: %s" % (step_mode,))

            json_hit = json_facade.wait_for_thread_stopped("step")
            assert json_hit.thread_id == thread_name_to_id["thread1"]
            local_var = json_facade.get_local_var(json_hit.frame_id, "_event2_set")

            # We're stepping in a single thread which depends on events being set in
            # another thread, so, we can only get here if the other thread was also released.
            if local_var.value == "True":
                if stepping_resumes_all_threads:
                    break
                else:
                    raise AssertionError("Did not expect _event2_set to be set when not resuming other threads on step.")

            if stepping_resumes_all_threads:
                if timeout_at < time.time():
                    raise RuntimeError("Did not reach expected condition in time!")
            else:
                if checks == 15:
                    break  # yeap, we just check that we don't reach a given condition.
            time.sleep(0.01)
        else:
            if stepping_resumes_all_threads:
                raise AssertionError("Expected _event2_set to be set already.")
            else:
                # That's correct, we should never reach the condition where _event2_set is set if
                # we're not resuming other threads on step.
                pass

        json_facade.write_continue()

        writer.finished_ok = True


def test_stepping(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_stepping.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(justMyCode=False)
        json_facade.write_set_breakpoints(
            [writer.get_line_index_with_content("Break here 1"), writer.get_line_index_with_content("Break here 2")]
        )
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        # Test Step-Over or 'next'
        stack_trace_response = json_hit.stack_trace_response
        for stack_frame in stack_trace_response.body.stackFrames:
            assert stack_frame["source"]["sourceReference"] == 0

        stack_frame = next(iter(stack_trace_response.body.stackFrames))
        before_step_over_line = stack_frame["line"]

        json_facade.write_step_next(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", line=before_step_over_line + 1)

        # Test step into or 'stepIn'
        json_facade.write_step_in(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", name="step_into")

        # Test step return or 'stepOut'
        json_facade.write_continue()
        json_hit = json_facade.wait_for_thread_stopped(name="step_out")

        json_facade.write_step_out(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", name="Call")

        json_facade.write_continue()

        writer.finished_ok = True


def test_evaluate(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_evaluate.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        stack_trace_request = json_facade.write_request(
            pydevd_schema.StackTraceRequest(pydevd_schema.StackTraceArguments(threadId=json_hit.thread_id))
        )
        stack_trace_response = json_facade.wait_for_response(stack_trace_request)
        stack_frame = next(iter(stack_trace_response.body.stackFrames))
        stack_frame_id = stack_frame["id"]

        # Check that evaluating variable that does not exist in hover returns success == False.
        json_facade.evaluate("var_does_not_exist", frameId=stack_frame_id, context="hover", success=False)

        # Test evaluate request that results in 'eval'
        eval_response = json_facade.evaluate("var_1", frameId=stack_frame_id, context="repl")
        assert eval_response.body.result == "5"
        assert eval_response.body.type == "int"

        # Test evaluate request that results in 'exec'
        exec_response = json_facade.evaluate("var_1 = 6", frameId=stack_frame_id, context="repl")
        assert exec_response.body.result == ""

        # Test evaluate request that results in 'exec' but fails
        exec_response = json_facade.evaluate('var_1 = "abc"/6', frameId=stack_frame_id, context="repl", success=False)
        assert "TypeError" in exec_response.body.result
        assert "TypeError" in exec_response.message

        # Evaluate without a frameId.

        # Error because 'foo_value' is not set in 'sys'.
        exec_response = json_facade.evaluate("import email;email.foo_value", success=False)
        assert "AttributeError" in exec_response.body.result
        assert "AttributeError" in exec_response.message

        # Reading foo_value didn't work, but 'email' should be in the namespace now.
        json_facade.evaluate("email.foo_value=True")

        # Ok, 'foo_value' is now set in 'email' module.
        exec_response = json_facade.evaluate("email.foo_value")

        # We don't actually get variables without a frameId, we can just evaluate and observe side effects
        # (so, the result is always empty -- or an error).
        assert exec_response.body.result == ""

        json_facade.write_continue()

        writer.finished_ok = True


def test_evaluate_failures(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_completions.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        # First, try with wrong id.
        exec_request = json_facade.write_request(
            pydevd_schema.EvaluateRequest(pydevd_schema.EvaluateArguments("a = 10", frameId=9999, context="repl"))
        )
        exec_response = json_facade.wait_for_response(exec_request)
        assert exec_response.success == False
        assert exec_response.message == "Wrong ID sent from the client: 9999"

        first_hit = None
        for i in range(2):
            json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)
            if i == 0:
                first_hit = json_hit
                # Check that watch exceptions are shown as string/failure.
                response = json_facade.evaluate("invalid_var", frameId=first_hit.frame_id, context="watch", success=False)
                assert response.body.result == "NameError: name 'invalid_var' is not defined"
            if i == 1:
                # Now, check with a previously existing frameId.
                exec_request = json_facade.write_request(
                    pydevd_schema.EvaluateRequest(pydevd_schema.EvaluateArguments("a = 10", frameId=first_hit.frame_id, context="repl"))
                )
                exec_response = json_facade.wait_for_response(exec_request)
                assert exec_response.success == False
                assert exec_response.message == "Unable to find thread for evaluation."

            json_facade.write_continue(wait_for_response=i == 0)
            if i == 0:
                json_hit = json_facade.wait_for_thread_stopped()

        writer.finished_ok = True


def test_evaluate_exception_trace(case_setup_dap, pyfile):
    @pyfile
    def exception_trace_file():
        class A(object):
            def __init__(self, a):
                pass

        def method():
            A()

        def method2():
            method()

        def method3():
            method2()

        print("TEST SUCEEDED")  # Break here

    with case_setup_dap.test_file(exception_trace_file) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        exec_response = json_facade.evaluate("method3()", json_hit.frame_id, "repl", success=False)
        assert "pydevd" not in exec_response.message  # i.e.: don't show pydevd in the trace
        assert "method3" in exec_response.message
        assert "method2" in exec_response.message

        exec_response = json_facade.evaluate("method2()", json_hit.frame_id, "repl", success=False)
        assert "pydevd" not in exec_response.message
        assert "method3" not in exec_response.message
        assert "method2" in exec_response.message

        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.parametrize("max_frames", ["default", "all", 10])  # -1 = default, 0 = all, 10 = 10 frames
def test_exception_details(case_setup_dap, max_frames):
    with case_setup_dap.test_file("_debugger_case_large_exception_stack.py") as writer:
        json_facade = JsonFacade(writer)

        if max_frames == "all":
            json_facade.write_launch(maxExceptionStackFrames=0)
            # trace back compresses repeated text
            min_expected_lines = 100
            max_expected_lines = 220
        elif max_frames == "default":
            json_facade.write_launch()
            # default is all frames
            # trace back compresses repeated text
            min_expected_lines = 100
            max_expected_lines = 220
        else:
            json_facade.write_launch(maxExceptionStackFrames=max_frames)
            min_expected_lines = 10
            max_expected_lines = 22

        json_facade.write_set_exception_breakpoints(["raised"])

        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped("exception")

        exc_info_request = json_facade.write_request(
            pydevd_schema.ExceptionInfoRequest(pydevd_schema.ExceptionInfoArguments(json_hit.thread_id))
        )
        exc_info_response = json_facade.wait_for_response(exc_info_request)

        stack_frames = json_hit.stack_trace_response.body.stackFrames
        assert 100 <= len(stack_frames) <= 104
        assert stack_frames[-1]["name"] == "<module>"
        assert stack_frames[0]["name"] == "method1"

        body = exc_info_response.body
        assert body.exceptionId.endswith("IndexError")
        assert body.description == "foo"
        assert normcase(body.details.kwargs["source"]) == normcase(writer.TEST_FILE)
        stack_line_count = len(body.details.stackTrace.split("\n"))
        assert min_expected_lines <= stack_line_count <= max_expected_lines

        json_facade.write_set_exception_breakpoints([])  # Don't stop on reraises.
        json_facade.write_continue()

        writer.finished_ok = True


def test_stack_levels(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_deep_stacks.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped()

        # get full stack
        stack_trace_request = json_facade.write_request(
            pydevd_schema.StackTraceRequest(pydevd_schema.StackTraceArguments(threadId=json_hit.thread_id))
        )
        stack_trace_response = json_facade.wait_for_response(stack_trace_request)
        full_stack_frames = stack_trace_response.body.stackFrames
        total_frames = stack_trace_response.body.totalFrames

        startFrame = 0
        levels = 20
        received_frames = []
        while startFrame < total_frames:
            stack_trace_request = json_facade.write_request(
                pydevd_schema.StackTraceRequest(
                    pydevd_schema.StackTraceArguments(threadId=json_hit.thread_id, startFrame=startFrame, levels=20)
                )
            )
            stack_trace_response = json_facade.wait_for_response(stack_trace_request)
            received_frames += stack_trace_response.body.stackFrames
            startFrame += levels

        assert full_stack_frames == received_frames

        json_facade.write_continue()

        writer.finished_ok = True


def test_breakpoint_adjustment(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_adjust_breakpoint.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()

        bp_requested = writer.get_line_index_with_content("requested")
        bp_expected = writer.get_line_index_with_content("expected")

        set_bp_request = json_facade.write_request(
            pydevd_schema.SetBreakpointsRequest(
                pydevd_schema.SetBreakpointsArguments(
                    source=pydevd_schema.Source(path=writer.TEST_FILE, sourceReference=0),
                    breakpoints=[pydevd_schema.SourceBreakpoint(bp_requested).to_dict()],
                )
            )
        )
        set_bp_response = json_facade.wait_for_response(set_bp_request)
        assert set_bp_response.success
        assert set_bp_response.body.breakpoints[0]["line"] == bp_expected

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        stack_trace_request = json_facade.write_request(
            pydevd_schema.StackTraceRequest(pydevd_schema.StackTraceArguments(threadId=json_hit.thread_id))
        )
        stack_trace_response = json_facade.wait_for_response(stack_trace_request)
        stack_frame = next(iter(stack_trace_response.body.stackFrames))
        assert stack_frame["line"] == bp_expected

        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.skipif(IS_JYTHON, reason="No goto on Jython.")
def test_goto(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_set_next_statement.py") as writer:
        json_facade = JsonFacade(writer)

        break_line = writer.get_line_index_with_content("Break here")
        step_line = writer.get_line_index_with_content("Step here")
        json_facade.write_set_breakpoints(break_line)

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        stack_trace_request = json_facade.write_request(
            pydevd_schema.StackTraceRequest(pydevd_schema.StackTraceArguments(threadId=json_hit.thread_id))
        )
        stack_trace_response = json_facade.wait_for_response(stack_trace_request)
        stack_frame = next(iter(stack_trace_response.body.stackFrames))
        assert stack_frame["line"] == break_line

        goto_targets_request = json_facade.write_request(
            pydevd_schema.GotoTargetsRequest(
                pydevd_schema.GotoTargetsArguments(source=pydevd_schema.Source(path=writer.TEST_FILE, sourceReference=0), line=step_line)
            )
        )
        goto_targets_response = json_facade.wait_for_response(goto_targets_request)
        target_id = goto_targets_response.body.targets[0]["id"]

        goto_request = json_facade.write_request(
            pydevd_schema.GotoRequest(pydevd_schema.GotoArguments(threadId=json_hit.thread_id, targetId=12345))
        )
        goto_response = json_facade.wait_for_response(goto_request)
        assert not goto_response.success

        goto_request = json_facade.write_request(
            pydevd_schema.GotoRequest(pydevd_schema.GotoArguments(threadId=json_hit.thread_id, targetId=target_id))
        )
        goto_response = json_facade.wait_for_response(goto_request)

        json_hit = json_facade.wait_for_thread_stopped("goto")

        stack_trace_request = json_facade.write_request(
            pydevd_schema.StackTraceRequest(pydevd_schema.StackTraceArguments(threadId=json_hit.thread_id))
        )
        stack_trace_response = json_facade.wait_for_response(stack_trace_request)
        stack_frame = next(iter(stack_trace_response.body.stackFrames))
        assert stack_frame["line"] == step_line

        json_facade.write_continue()

        # we hit the breakpoint again. Since we moved back
        json_facade.wait_for_thread_stopped()
        json_facade.write_continue()

        writer.finished_ok = True


def _collect_stack_frames_ending_with(json_hit, end_with_pattern):
    stack_trace_response = json_hit.stack_trace_response
    dont_trace_frames = list(frame for frame in stack_trace_response.body.stackFrames if frame["source"]["path"].endswith(end_with_pattern))
    return dont_trace_frames


def _check_dont_trace_filtered_out(json_hit):
    assert _collect_stack_frames_ending_with(json_hit, "dont_trace.py") == []


def _check_dont_trace_not_filtered_out(json_hit):
    assert len(_collect_stack_frames_ending_with(json_hit, "dont_trace.py")) == 1


@pytest.mark.parametrize("dbg_property", ["dont_trace", "trace", "change_pattern", "dont_trace_after_start"])
def test_set_debugger_property(case_setup_dap, dbg_property):
    kwargs = {}

    with case_setup_dap.test_file("_debugger_case_dont_trace_test.py", **kwargs) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))

        if dbg_property in ("dont_trace", "change_pattern", "dont_trace_after_start"):
            json_facade.write_set_debugger_property([], ["dont_trace.py"] if not IS_WINDOWS else ["Dont_Trace.py"])

        if dbg_property == "change_pattern":
            json_facade.write_set_debugger_property([], ["something_else.py"])

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        if dbg_property in ("dont_trace", "dont_trace_after_start"):
            _check_dont_trace_filtered_out(json_hit)

        elif dbg_property in ("change_pattern", "trace"):
            _check_dont_trace_not_filtered_out(json_hit)

        else:
            raise AssertionError("Unexpected: %s" % (dbg_property,))

        if dbg_property == "dont_trace_after_start":
            json_facade.write_set_debugger_property([], ["something_else.py"])

        json_facade.write_continue()
        json_hit = json_facade.wait_for_thread_stopped()

        if dbg_property in ("dont_trace",):
            _check_dont_trace_filtered_out(json_hit)

        elif dbg_property in ("change_pattern", "trace", "dont_trace_after_start"):
            _check_dont_trace_not_filtered_out(json_hit)

        else:
            raise AssertionError("Unexpected: %s" % (dbg_property,))

        json_facade.write_continue()

        writer.finished_ok = True


def test_source_mapping_errors(case_setup_dap):
    from _pydevd_bundle._debug_adapter.pydevd_schema import Source
    from _pydevd_bundle._debug_adapter.pydevd_schema import PydevdSourceMap

    with case_setup_dap.test_file("_debugger_case_source_mapping.py") as writer:
        json_facade = JsonFacade(writer)

        map_to_cell_1_line2 = writer.get_line_index_with_content("map to cEll1, line 2")
        map_to_cell_2_line2 = writer.get_line_index_with_content("map to cEll2, line 2")

        cell1_map = PydevdSourceMap(map_to_cell_1_line2, map_to_cell_1_line2 + 1, Source(path="<cEll1>"), 2)
        cell2_map = PydevdSourceMap(map_to_cell_2_line2, map_to_cell_2_line2 + 1, Source(path="<cEll2>"), 2)
        pydevd_source_maps = [cell1_map, cell2_map]

        json_facade.write_set_pydevd_source_map(
            Source(path=writer.TEST_FILE),
            pydevd_source_maps=pydevd_source_maps,
        )
        # This will fail because file mappings must be 1:N, not M:N (i.e.: if there's a mapping from file1.py to <cEll1>,
        # there can be no other mapping from any other file to <cEll1>).
        # This is a limitation to make it easier to remove existing breakpoints when new breakpoints are
        # set to a file (so, any file matching that breakpoint can be removed instead of needing to check
        # which lines are corresponding to that file).
        json_facade.write_set_pydevd_source_map(
            Source(path=os.path.join(os.path.dirname(writer.TEST_FILE), "foo.py")),
            pydevd_source_maps=pydevd_source_maps,
            success=False,
        )
        json_facade.write_make_initial_run()

        writer.finished_ok = True


@pytest.mark.parametrize("target", ["_debugger_case_source_mapping.py", "_debugger_case_source_mapping_and_reference.py"])
@pytest.mark.parametrize("jmc", [True, False])
def test_source_mapping_base(case_setup_dap, target, jmc):
    from _pydevd_bundle._debug_adapter.pydevd_schema import Source
    from _pydevd_bundle._debug_adapter.pydevd_schema import PydevdSourceMap

    case_setup_dap.check_non_ascii = True

    def get_environ(self):
        env = os.environ.copy()
        env["IDE_PROJECT_ROOTS"] = os.path.dirname(self.TEST_FILE) + os.pathsep + os.path.abspath(".")
        return env

    with case_setup_dap.test_file(target, get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(justMyCode=jmc)

        map_to_cell_1_line2 = writer.get_line_index_with_content("map to cEll1, line 2")
        map_to_cell_2_line2 = writer.get_line_index_with_content("map to cEll2, line 2")

        cell1_map = PydevdSourceMap(map_to_cell_1_line2, map_to_cell_1_line2 + 1, Source(path="<cEll1>"), 2)
        cell2_map = PydevdSourceMap(map_to_cell_2_line2, map_to_cell_2_line2 + 1, Source(path="<cEll2>"), 2)
        pydevd_source_maps = [
            cell1_map,
            cell2_map,
            cell2_map,  # The one repeated should be ignored.
        ]

        # Set breakpoints before setting the source map (check that we reapply them).
        json_facade.write_set_breakpoints(map_to_cell_1_line2)

        test_file = writer.TEST_FILE
        if isinstance(test_file, bytes):
            # file is in the filesystem encoding (needed for launch) but protocol needs it in utf-8
            test_file = test_file.decode(file_system_encoding)
            test_file = test_file.encode("utf-8")

        json_facade.write_set_pydevd_source_map(
            Source(path=test_file),
            pydevd_source_maps=pydevd_source_maps,
        )

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(line=map_to_cell_1_line2, file=os.path.basename(test_file))
        for stack_frame in json_hit.stack_trace_response.body.stackFrames:
            assert stack_frame["source"]["sourceReference"] == 0

        # Check that we no longer stop at the cEll1 breakpoint (its mapping should be removed when
        # the new one is added and we should only stop at cEll2).
        json_facade.write_set_breakpoints(map_to_cell_2_line2)
        for stack_frame in json_hit.stack_trace_response.body.stackFrames:
            assert stack_frame["source"]["sourceReference"] == 0
        json_facade.write_continue()

        json_hit = json_facade.wait_for_thread_stopped(line=map_to_cell_2_line2, file=os.path.basename(test_file))
        json_facade.write_set_breakpoints([])  # Clears breakpoints
        json_facade.write_continue()

        writer.finished_ok = True


def test_source_mapping_just_my_code(case_setup_dap):
    from _pydevd_bundle._debug_adapter.pydevd_schema import Source
    from _pydevd_bundle._debug_adapter.pydevd_schema import PydevdSourceMap

    case_setup_dap.check_non_ascii = True

    def get_environ(self):
        env = os.environ.copy()
        env["IDE_PROJECT_ROOTS"] = os.path.dirname(self.TEST_FILE) + os.pathsep + os.path.abspath(".")
        return env

    with case_setup_dap.test_file("_debugger_case_source_mapping_jmc.py", get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(justMyCode=True)

        map_to_cell_1_line1 = writer.get_line_index_with_content("map to cEll1, line 1")
        map_to_cell_1_line6 = writer.get_line_index_with_content("map to cEll1, line 6")
        map_to_cell_1_line7 = writer.get_line_index_with_content("map to cEll1, line 7")

        cell1_map = PydevdSourceMap(map_to_cell_1_line1, map_to_cell_1_line7, Source(path="<cEll1>"), 1)
        pydevd_source_maps = [cell1_map]

        # Set breakpoints before setting the source map (check that we reapply them).
        json_facade.write_set_breakpoints(map_to_cell_1_line6)

        test_file = writer.TEST_FILE
        if isinstance(test_file, bytes):
            # file is in the filesystem encoding (needed for launch) but protocol needs it in utf-8
            test_file = test_file.decode(file_system_encoding)
            test_file = test_file.encode("utf-8")

        json_facade.write_set_pydevd_source_map(
            Source(path=test_file),
            pydevd_source_maps=pydevd_source_maps,
        )

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(line=map_to_cell_1_line6, file=os.path.basename(test_file))
        for stack_frame in json_hit.stack_trace_response.body.stackFrames:
            assert stack_frame["source"]["sourceReference"] == 0

        # i.e.: Remove the source maps
        json_facade.write_set_pydevd_source_map(
            Source(path=test_file),
            pydevd_source_maps=[],
        )

        json_facade.write_continue()

        writer.finished_ok = True


def test_source_mapping_goto_target(case_setup_dap):
    from _pydevd_bundle._debug_adapter.pydevd_schema import Source
    from _pydevd_bundle._debug_adapter.pydevd_schema import PydevdSourceMap

    def additional_output_checks(writer, stdout, stderr):
        assert "Skip this print" not in stdout
        assert "TEST SUCEEDED" in stdout

    with case_setup_dap.test_file("_debugger_case_source_map_goto_target.py", additional_output_checks=additional_output_checks) as writer:
        test_file = writer.TEST_FILE
        if isinstance(test_file, bytes):
            # file is in the filesystem encoding (needed for launch) but protocol needs it in utf-8
            test_file = test_file.decode(file_system_encoding)
            test_file = test_file.encode("utf-8")

        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)

        map_to_cell_1_line1 = writer.get_line_index_with_content("map to Cell1, line 1")
        map_to_cell_1_line2 = writer.get_line_index_with_content("map to Cell1, line 2")
        map_to_cell_1_line4 = writer.get_line_index_with_content("map to Cell1, line 4")
        map_to_cell_1_line5 = writer.get_line_index_with_content("map to Cell1, line 5")

        cell1_map = PydevdSourceMap(map_to_cell_1_line1, map_to_cell_1_line5, Source(path="<Cell1>"), 1)
        pydevd_source_maps = [cell1_map]
        json_facade.write_set_pydevd_source_map(
            Source(path=test_file),
            pydevd_source_maps=pydevd_source_maps,
        )
        json_facade.write_set_breakpoints(map_to_cell_1_line2)

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(line=map_to_cell_1_line2, file=os.path.basename(test_file))
        for stack_frame in json_hit.stack_trace_response.body.stackFrames:
            assert stack_frame["source"]["sourceReference"] == 0

        goto_targets_request = json_facade.write_request(
            pydevd_schema.GotoTargetsRequest(
                pydevd_schema.GotoTargetsArguments(
                    source=pydevd_schema.Source(path=writer.TEST_FILE, sourceReference=0), line=map_to_cell_1_line4
                )
            )
        )
        goto_targets_response = json_facade.wait_for_response(goto_targets_request)
        target_id = goto_targets_response.body.targets[0]["id"]

        goto_request = json_facade.write_request(
            pydevd_schema.GotoRequest(pydevd_schema.GotoArguments(threadId=json_hit.thread_id, targetId=target_id))
        )
        goto_response = json_facade.wait_for_response(goto_request)
        assert goto_response.success

        json_hit = json_facade.wait_for_thread_stopped("goto")

        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.skipif(not TEST_CHERRYPY or IS_WINDOWS, reason="No CherryPy available / not ok in Windows.")
def test_process_autoreload_cherrypy(case_setup_multiprocessing_dap, tmpdir):
    """
    CherryPy does an os.execv(...) which will kill the running process and replace
    it with a new process when a reload takes place, so, it mostly works as
    a new process connection (everything is the same except that the
    existing process is stopped).
    """
    raise pytest.skip("This is failing with the latest cherrypy -- needs investigation.")
    port = get_free_port()
    # We write a temp file because we'll change it to autoreload later on.
    f = tmpdir.join("_debugger_case_cherrypy.py")

    tmplt = """
import cherrypy
cherrypy.config.update({
    'engine.autoreload.on': True,
    'checker.on': False,
    'server.socket_port': %(port)s,
})
class HelloWorld(object):

    @cherrypy.expose
    def index(self):
        print('TEST SUCEEDED')
        return "Hello World %(str)s!"  # break here
    @cherrypy.expose('/exit')
    def exit(self):
        cherrypy.engine.exit()

cherrypy.quickstart(HelloWorld())
"""

    f.write(tmplt % dict(port=port, str="INITIAL"))

    file_to_check = str(f)

    def get_environ(writer):
        env = os.environ.copy()

        env["PYTHONIOENCODING"] = "utf-8"
        env["PYTHONPATH"] = str(tmpdir)
        return env

    import threading
    from tests_python.debugger_unittest import AbstractWriterThread

    with case_setup_multiprocessing_dap.test_file(file_to_check, get_environ=get_environ) as writer:
        original_ignore_stderr_line = writer._ignore_stderr_line

        @overrides(writer._ignore_stderr_line)
        def _ignore_stderr_line(line):
            if original_ignore_stderr_line(line):
                return True
            return "ENGINE " in line or "CherryPy Checker" in line or "has an empty config" in line

        writer._ignore_stderr_line = _ignore_stderr_line

        json_facade = JsonFacade(writer)
        json_facade.write_launch(debugOptions=["DebugStdLib"])

        break1_line = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints(break1_line)

        server_socket = writer.server_socket

        secondary_thread_log = []
        secondary_thread_errors = []

        class SecondaryProcessWriterThread(AbstractWriterThread):
            TEST_FILE = writer.get_main_filename()
            _sequence = -1

        class SecondaryProcessThreadCommunication(threading.Thread):
            def run(self):
                try:
                    from tests_python.debugger_unittest import ReaderThread

                    expected_connections = 1
                    for _ in range(expected_connections):
                        server_socket.listen(1)
                        self.server_socket = server_socket
                        new_sock, addr = server_socket.accept()

                        reader_thread = ReaderThread(new_sock)
                        reader_thread.name = "  *** Multiprocess Reader Thread"
                        reader_thread.start()

                        writer2 = SecondaryProcessWriterThread()

                        writer2.reader_thread = reader_thread
                        writer2.sock = new_sock

                        writer2.write_version()
                        writer2.write_add_breakpoint(break1_line)
                        writer2.write_make_initial_run()

                    secondary_thread_log.append("Initial run")

                    # Give it some time to startup
                    time.sleep(2)
                    t = writer.create_request_thread("http://127.0.0.1:%s/" % (port,))
                    t.start()

                    secondary_thread_log.append("Waiting for first breakpoint")
                    hit = writer2.wait_for_breakpoint_hit()
                    secondary_thread_log.append("Hit first breakpoint")
                    writer2.write_run_thread(hit.thread_id)

                    contents = t.wait_for_contents()
                    assert "Hello World NEW!" in contents

                    secondary_thread_log.append("Requesting exit.")
                    t = writer.create_request_thread("http://127.0.0.1:%s/exit" % (port,))
                    t.start()
                except Exception as e:
                    secondary_thread_errors.append("Error from secondary thread: %s" % (e,))
                    raise

        secondary_process_thread_communication = SecondaryProcessThreadCommunication()
        secondary_process_thread_communication.start()
        json_facade.write_make_initial_run()

        # Give it some time to startup
        time.sleep(2)

        t = writer.create_request_thread("http://127.0.0.1:%s/" % (port,))
        t.start()
        json_facade.wait_for_thread_stopped()
        json_facade.write_continue()

        contents = t.wait_for_contents()
        assert "Hello World INITIAL!" in contents

        # Sleep a bit more to make sure that the initial timestamp was gotten in the
        # CherryPy background thread.
        time.sleep(2)
        f.write(tmplt % dict(port=port, str="NEW"))

        def check_condition():
            return not secondary_process_thread_communication.is_alive()

        def create_msg():
            return "Expected secondary thread to finish before timeout.\nSecondary thread log:\n%s\nSecondary thread errors:\n%s\n" % (
                "\n".join(secondary_thread_log),
                "\n".join(secondary_thread_errors),
            )

        wait_for_condition(check_condition, msg=create_msg)

        if secondary_thread_errors:
            raise AssertionError("Found errors in secondary thread: %s" % (secondary_thread_errors,))

        writer.finished_ok = True


def test_wait_for_attach_debugpy_mode(case_setup_remote_attach_to_dap):
    host_port = get_socket_name(close=True)

    with case_setup_remote_attach_to_dap.test_file("_debugger_case_wait_for_attach_debugpy_mode.py", host_port[1]) as writer:
        time.sleep(1)  # Give some time for it to pass the first breakpoint and wait in 'wait_for_attach'.
        writer.start_socket_client(*host_port)

        # We don't send initial messages because everything should be pre-configured to
        # the DAP mode already (i.e.: making sure it works).
        json_facade = JsonFacade(writer)
        break2_line = writer.get_line_index_with_content("Break 2")

        json_facade.write_attach()
        # Make sure we also received the initialized in the attach.
        assert len(json_facade.mark_messages(InitializedEvent)) == 1

        json_facade.write_set_breakpoints([break2_line])

        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped(line=break2_line)
        json_facade.write_continue()
        writer.finished_ok = True


def test_wait_for_attach(case_setup_remote_attach_to_dap):
    host_port = get_socket_name(close=True)

    def check_thread_events(json_facade):
        json_facade.write_list_threads()
        # Check that we have the started thread event (whenever we reconnect).
        started_events = json_facade.mark_messages(ThreadEvent, lambda x: x.body.reason == "started")
        assert len(started_events) >= 1

    def check_process_event(json_facade, start_method):
        if start_method == "attach":
            json_facade.write_attach()

        elif start_method == "launch":
            json_facade.write_launch()

        else:
            raise AssertionError("Unexpected: %s" % (start_method,))

        process_events = json_facade.mark_messages(ProcessEvent)
        assert len(process_events) == 1
        assert next(iter(process_events)).body.startMethod == start_method

    with case_setup_remote_attach_to_dap.test_file("_debugger_case_wait_for_attach.py", host_port[1]) as writer:
        writer.TEST_FILE = debugger_unittest._get_debugger_test_file("_debugger_case_wait_for_attach_impl.py")
        time.sleep(1)  # Give some time for it to pass the first breakpoint and wait in 'wait_for_attach'.
        writer.start_socket_client(*host_port)

        json_facade = JsonFacade(writer)
        check_thread_events(json_facade)

        break1_line = writer.get_line_index_with_content("Break 1")
        break2_line = writer.get_line_index_with_content("Break 2")
        break3_line = writer.get_line_index_with_content("Break 3")

        pause1_line = writer.get_line_index_with_content("Pause 1")
        pause2_line = writer.get_line_index_with_content("Pause 2")

        check_process_event(json_facade, start_method="launch")
        json_facade.write_set_breakpoints([break1_line, break2_line, break3_line])
        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped(line=break2_line)

        # Upon disconnect, all threads should be running again.
        json_facade.write_disconnect()

        # Connect back (socket should remain open).
        writer.start_socket_client(*host_port)
        json_facade = JsonFacade(writer)
        check_thread_events(json_facade)
        check_process_event(json_facade, start_method="attach")
        json_facade.write_set_breakpoints([break1_line, break2_line, break3_line])
        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped(line=break3_line)

        # Upon disconnect, all threads should be running again.
        json_facade.write_disconnect()

        # Connect back (socket should remain open).
        writer.start_socket_client(*host_port)
        json_facade = JsonFacade(writer)
        check_thread_events(json_facade)
        check_process_event(json_facade, start_method="attach")
        json_facade.write_make_initial_run()

        # Connect back without a disconnect (auto-disconnects previous and connects new client).
        writer.start_socket_client(*host_port)
        json_facade = JsonFacade(writer)
        check_thread_events(json_facade)
        check_process_event(json_facade, start_method="attach")
        json_facade.write_make_initial_run()

        json_facade.write_pause()
        json_hit = json_facade.wait_for_thread_stopped(reason="pause", line=[pause1_line, pause2_line])

        # Change value of 'a' for test to finish.
        json_facade.write_set_variable(json_hit.frame_id, "a", "10")

        json_facade.write_disconnect()
        writer.finished_ok = True


@pytest.mark.skipif(not TEST_GEVENT, reason="Gevent not installed.")
def test_wait_for_attach_gevent(case_setup_remote_attach_to_dap):
    host_port = get_socket_name(close=True)

    def get_environ(writer):
        env = os.environ.copy()
        env["GEVENT_SUPPORT"] = "True"
        return env

    def check_thread_events(json_facade):
        json_facade.write_list_threads()
        # Check that we have the started thread event (whenever we reconnect).
        started_events = json_facade.mark_messages(ThreadEvent, lambda x: x.body.reason == "started")
        assert len(started_events) == 1

    with case_setup_remote_attach_to_dap.test_file(
        "_debugger_case_gevent.py", host_port[1], additional_args=["remote", "as-server"], get_environ=get_environ
    ) as writer:
        writer.TEST_FILE = debugger_unittest._get_debugger_test_file("_debugger_case_gevent.py")
        time.sleep(0.5)  # Give some time for it to pass the first breakpoint and wait.
        writer.start_socket_client(*host_port)

        json_facade = JsonFacade(writer)
        check_thread_events(json_facade)

        break1_line = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints(break1_line)
        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped(line=break1_line)

        json_facade.write_disconnect()
        writer.finished_ok = True


@pytest.mark.skipif(not TEST_GEVENT, reason="Gevent not installed.")
@pytest.mark.parametrize("show", [True, False])
def test_gevent_show_paused_greenlets(case_setup_dap, show):
    def get_environ(writer):
        env = os.environ.copy()
        env["GEVENT_SUPPORT"] = "True"
        if show:
            env["GEVENT_SHOW_PAUSED_GREENLETS"] = "True"
        else:
            env["GEVENT_SHOW_PAUSED_GREENLETS"] = "False"
        return env

    with case_setup_dap.test_file("_debugger_case_gevent_simple.py", get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)

        break1_line = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints(break1_line)
        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped(line=break1_line)

        response = json_facade.write_list_threads()
        if show:
            assert len(response.body.threads) > 1

            thread_name_to_id = dict((t["name"], t["id"]) for t in response.body.threads)
            assert set(thread_name_to_id.keys()) == set(
                (
                    "MainThread",
                    "greenlet: <module> - _debugger_case_gevent_simple.py",
                    "Greenlet: foo - _debugger_case_gevent_simple.py",
                    "Hub: run - hub.py",
                )
            )

            for tname, tid in thread_name_to_id.items():
                stack = json_facade.get_stack_as_json_hit(tid, no_stack_frame=tname == "Hub: run - hub.py")
                assert stack

        else:
            assert len(response.body.threads) == 1

        json_facade.write_continue(wait_for_response=False)
        writer.finished_ok = True


@pytest.mark.skipif(not TEST_GEVENT, reason="Gevent not installed.")
@pytest.mark.skipif(sys.platform == "win32", reason="tput requires Linux.")
def test_gevent_subprocess_not_python(case_setup_dap):
    def get_environ(writer):
        env = os.environ.copy()
        env["GEVENT_SUPPORT"] = "True"
        env["CALL_PYTHON_SUB"] = "0"
        return env

    with case_setup_dap.test_file("_debugger_case_gevent_subprocess.py", get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)

        break1_line = writer.get_line_index_with_content("print('TEST SUCEEDED')")
        json_facade.write_set_breakpoints(break1_line)
        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped(line=break1_line)

        json_facade.write_continue(wait_for_response=False)
        writer.finished_ok = True


@pytest.mark.skipif(not TEST_GEVENT, reason="Gevent not installed.")
def test_gevent_subprocess_python(case_setup_multiprocessing_dap):
    import threading
    from tests_python.debugger_unittest import AbstractWriterThread

    def get_environ(writer):
        env = os.environ.copy()
        env["GEVENT_SUPPORT"] = "True"
        env["CALL_PYTHON_SUB"] = "1"
        return env

    with case_setup_multiprocessing_dap.test_file(
        "_debugger_case_gevent_subprocess.py",
        get_environ=get_environ,
    ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch()

        break1_line = writer.get_line_index_with_content("print('foo called')")
        json_facade.write_set_breakpoints([break1_line])

        server_socket = writer.server_socket
        secondary_finished_ok = [False]

        class SecondaryProcessWriterThread(AbstractWriterThread):
            TEST_FILE = writer.get_main_filename()
            _sequence = -1

        class SecondaryProcessThreadCommunication(threading.Thread):
            def run(self):
                from tests_python.debugger_unittest import ReaderThread

                server_socket.listen(1)
                self.server_socket = server_socket
                new_sock, addr = server_socket.accept()

                reader_thread = ReaderThread(new_sock)
                reader_thread.name = "  *** Multiprocess Reader Thread"
                reader_thread.start()

                writer2 = SecondaryProcessWriterThread()
                writer2.reader_thread = reader_thread
                writer2.sock = new_sock
                json_facade2 = JsonFacade(writer2)

                json_facade2.write_set_breakpoints(
                    [
                        break1_line,
                    ]
                )
                json_facade2.write_make_initial_run()

                json_facade2.wait_for_thread_stopped()
                json_facade2.write_continue()
                secondary_finished_ok[0] = True

        secondary_process_thread_communication = SecondaryProcessThreadCommunication()
        secondary_process_thread_communication.start()
        time.sleep(0.1)

        json_facade.write_make_initial_run()
        secondary_process_thread_communication.join(10)
        if secondary_process_thread_communication.is_alive():
            raise AssertionError("The SecondaryProcessThreadCommunication did not finish")

        assert secondary_finished_ok[0]
        writer.finished_ok = True


@pytest.mark.skipif(
    not TEST_GEVENT or IS_WINDOWS or True,  # Always skipping now as this can be flaky!
    reason="Gevent not installed / Sometimes the debugger crashes on Windows as the compiled extensions conflict with gevent.",
)
def test_notify_gevent(case_setup_dap, pyfile):
    def get_environ(writer):
        # I.e.: Make sure that gevent support is disabled
        env = os.environ.copy()
        env["GEVENT_SUPPORT"] = ""
        return env

    @pyfile
    def case_gevent():
        from gevent import monkey
        import os

        monkey.patch_all()
        print("TEST SUCEEDED")  # Break here
        os._exit(0)

    def additional_output_checks(writer, stdout, stderr):
        assert "environment variable" in stderr
        assert "GEVENT_SUPPORT=True" in stderr

    with case_setup_dap.test_file(
        case_gevent,
        get_environ=get_environ,
        additional_output_checks=additional_output_checks,
        EXPECTED_RETURNCODE="any",
        FORCE_KILL_PROCESS_WHEN_FINISHED_OK=True,
    ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)
        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped()
        json_facade.write_continue(wait_for_response=False)

        wait_for_condition(lambda: "GEVENT_SUPPORT=True" in writer.get_stderr())

        writer.finished_ok = True


def test_ppid(case_setup_dap, pyfile):
    @pyfile
    def case_ppid():
        from pydevd import get_global_debugger

        assert get_global_debugger().get_arg_ppid() == 22
        print("TEST SUCEEDED")

    def update_command_line_args(writer, args):
        ret = debugger_unittest.AbstractWriterThread.update_command_line_args(writer, args)
        ret.insert(ret.index("--client"), "--ppid")
        ret.insert(ret.index("--client"), "22")
        return ret

    with case_setup_dap.test_file(
        case_ppid,
        update_command_line_args=update_command_line_args,
    ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch()
        json_facade.write_make_initial_run()

        writer.finished_ok = True


@pytest.mark.skipif(IS_JYTHON, reason="Flaky on Jython.")
def test_path_translation_and_source_reference(case_setup_dap):
    translated_dir_not_ascii = "áéíóú汉字"

    def get_file_in_client(writer):
        # Instead of using: test_python/_debugger_case_path_translation.py
        # we'll set the breakpoints at foo/_debugger_case_path_translation.py
        file_in_client = os.path.dirname(os.path.dirname(writer.TEST_FILE))
        return os.path.join(os.path.dirname(file_in_client), translated_dir_not_ascii, "_debugger_case_path_translation.py")

    def get_environ(writer):
        env = os.environ.copy()

        env["PYTHONIOENCODING"] = "utf-8"
        return env

    with case_setup_dap.test_file("_debugger_case_path_translation.py", get_environ=get_environ) as writer:
        file_in_client = get_file_in_client(writer)
        assert "tests_python" not in file_in_client
        assert translated_dir_not_ascii in file_in_client

        json_facade = JsonFacade(writer)

        bp_line = writer.get_line_index_with_content("break here")
        assert writer.TEST_FILE.endswith("_debugger_case_path_translation.py")
        local_root = os.path.dirname(get_file_in_client(writer))
        json_facade.write_launch(
            pathMappings=[
                {
                    "localRoot": local_root,
                    "remoteRoot": os.path.dirname(writer.TEST_FILE),
                }
            ]
        )
        json_facade.write_set_breakpoints(bp_line, filename=file_in_client)
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()

        # : :type stack_trace_response: StackTraceResponse
        # : :type stack_trace_response_body: StackTraceResponseBody
        # : :type stack_frame: StackFrame

        # Check stack trace format.
        stack_trace_request = json_facade.write_request(
            pydevd_schema.StackTraceRequest(
                pydevd_schema.StackTraceArguments(threadId=json_hit.thread_id, format={"module": True, "line": True})
            )
        )
        stack_trace_response = json_facade.wait_for_response(stack_trace_request)
        stack_trace_response_body = stack_trace_response.body
        stack_frame = stack_trace_response_body.stackFrames[0]
        assert stack_frame["name"] == "__main__.call_this : %s" % (bp_line,)

        path = stack_frame["source"]["path"]
        file_in_client_unicode = file_in_client

        assert path == file_in_client_unicode
        source_reference = stack_frame["source"]["sourceReference"]
        assert source_reference == 0  # When it's translated the source reference must be == 0

        stack_frame_not_path_translated = stack_trace_response_body.stackFrames[1]
        if not stack_frame_not_path_translated["name"].startswith("tests_python.resource_path_translation.other.call_me_back1 :"):
            raise AssertionError("Error. Found: >>%s<<." % (stack_frame_not_path_translated["name"],))

        assert stack_frame_not_path_translated["source"]["path"].endswith("other.py")
        source_reference = stack_frame_not_path_translated["source"]["sourceReference"]
        assert source_reference != 0  # Not translated

        response = json_facade.write_get_source(source_reference)
        assert "def call_me_back1(callback):" in response.body.content

        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.skipif(IS_JYTHON, reason="Flaky on Jython.")
def test_source_reference_no_file(case_setup_dap, tmpdir):
    with case_setup_dap.test_file("_debugger_case_source_reference.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(
            debugOptions=["DebugStdLib"],
            pathMappings=[
                {
                    "localRoot": os.path.dirname(writer.TEST_FILE),
                    "remoteRoot": os.path.dirname(writer.TEST_FILE),
                }
            ],
        )

        writer.write_add_breakpoint(writer.get_line_index_with_content("breakpoint"))
        json_facade.write_make_initial_run()

        # First hit is for breakpoint reached via a stack frame that doesn't have source.

        json_hit = json_facade.wait_for_thread_stopped()
        stack_trace_request = json_facade.write_request(
            pydevd_schema.StackTraceRequest(
                pydevd_schema.StackTraceArguments(threadId=json_hit.thread_id, format={"module": True, "line": True})
            )
        )
        stack_trace_response = json_facade.wait_for_response(stack_trace_request)
        stack_trace_response_body = stack_trace_response.body
        stack_frame = stack_trace_response_body.stackFrames[1]
        assert stack_frame["source"]["path"] == "<string>"
        source_reference = stack_frame["source"]["sourceReference"]
        assert source_reference != 0

        json_facade.write_get_source(source_reference, success=False)

        json_facade.write_continue()

        # First hit is for breakpoint reached via a stack frame that doesn't have source
        # on disk, but which can be retrieved via linecache.

        json_hit = json_facade.wait_for_thread_stopped()
        stack_trace_request = json_facade.write_request(
            pydevd_schema.StackTraceRequest(
                pydevd_schema.StackTraceArguments(threadId=json_hit.thread_id, format={"module": True, "line": True})
            )
        )
        stack_trace_response = json_facade.wait_for_response(stack_trace_request)
        stack_trace_response_body = stack_trace_response.body
        stack_frame = stack_trace_response_body.stackFrames[1]
        print(stack_frame["source"]["path"])
        assert stack_frame["source"]["path"] == "<something>"
        source_reference = stack_frame["source"]["sourceReference"]
        assert source_reference != 0

        response = json_facade.write_get_source(source_reference)
        assert response.body.content == "foo()\n"

        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.skipif(not IS_CPYTHON, reason="CPython only test.")
def test_linecache_json_existing_file(case_setup_dap, tmpdir):
    with case_setup_dap.test_file("_debugger_case_linecache_existing_file.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(justMyCode=False)

        debugger_case_stepping_filename = debugger_unittest._get_debugger_test_file("_debugger_case_stepping.py")
        bp_line = writer.get_line_index_with_content("Break here 1", filename=debugger_case_stepping_filename)
        json_facade.write_set_breakpoints(bp_line, filename=debugger_case_stepping_filename)
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        stack_trace_response_body = json_hit.stack_trace_response.body
        for stack_frame in stack_trace_response_body.stackFrames:
            source_reference = stack_frame["source"]["sourceReference"]
            assert source_reference == 0

        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.skipif(not IS_CPYTHON, reason="CPython only test.")
def test_linecache_json(case_setup_dap, tmpdir):
    with case_setup_dap.test_file("_debugger_case_linecache.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(justMyCode=False)

        writer.write_add_breakpoint(writer.get_line_index_with_content("breakpoint"))
        json_facade.write_make_initial_run()

        # First hit is for breakpoint reached via a stack frame that doesn't have source.

        json_hit = json_facade.wait_for_thread_stopped()
        stack_trace_response_body = json_hit.stack_trace_response.body
        source_references = []
        for stack_frame in stack_trace_response_body.stackFrames:
            if stack_frame["source"]["path"] == "<foo bar>":
                source_reference = stack_frame["source"]["sourceReference"]
                assert source_reference != 0
                source_references.append(source_reference)

        # Each frame gets its own source reference.
        assert len(set(source_references)) == 2

        for source_reference in source_references:
            response = json_facade.write_get_source(source_reference)
            assert "def somemethod():" in response.body.content
            assert "    foo()" in response.body.content
            assert "[x for x in range(10)]" in response.body.content

        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.skipif(not IS_CPYTHON, reason="CPython only test.")
def test_show_bytecode_json(case_setup_dap, tmpdir):
    with case_setup_dap.test_file("_debugger_case_show_bytecode.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(justMyCode=False)

        writer.write_add_breakpoint(writer.get_line_index_with_content("breakpoint"))
        json_facade.write_make_initial_run()

        # First hit is for breakpoint reached via a stack frame that doesn't have source.

        json_hit = json_facade.wait_for_thread_stopped()
        stack_trace_response_body = json_hit.stack_trace_response.body
        source_references = []
        for stack_frame in stack_trace_response_body.stackFrames:
            if stack_frame["source"]["path"] == "<something>":
                source_reference = stack_frame["source"]["sourceReference"]
                assert source_reference != 0
                source_references.append(source_reference)

        # Each frame gets its own source reference.
        assert len(set(source_references)) == 2

        for source_reference in source_references:
            response = json_facade.write_get_source(source_reference)
            assert "MyClass" in response.body.content or "foo()" in response.body.content

        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.skipif(not TEST_DJANGO, reason="No django available")
@pytest.mark.parametrize("jmc", [False, True])
def test_case_django_no_attribute_exception_breakpoint(case_setup_django_dap, jmc):
    import django  # noqa (may not be there if TEST_DJANGO == False)

    django_version = [int(x) for x in django.get_version().split(".")][:2]

    if django_version < [2, 1]:
        pytest.skip("Template exceptions only supporting Django 2.1 onwards.")

    with case_setup_django_dap.test_file(EXPECTED_RETURNCODE="any") as writer:
        json_facade = JsonFacade(writer)

        if jmc:
            writer.write_set_project_roots([debugger_unittest._get_debugger_test_file("my_code")])
            json_facade.write_launch(
                debugOptions=["Django"],
                variablePresentation={
                    "all": "hide",
                    "protected": "inline",
                },
            )
            json_facade.write_set_exception_breakpoints(["raised", "uncaught"])
        else:
            json_facade.write_launch(
                debugOptions=["DebugStdLib", "Django"],
                variablePresentation={
                    "all": "hide",
                    "protected": "inline",
                },
            )
            # Don't set to all 'raised' because we'd stop on standard library exceptions here
            # (which is not something we want).
            json_facade.write_set_exception_breakpoints(
                exception_options=[
                    ExceptionOptions(
                        breakMode="always",
                        path=[
                            {"names": ["Python Exceptions"]},
                            {"names": ["AssertionError"]},
                        ],
                    )
                ]
            )

        writer.write_make_initial_run()

        t = writer.create_request_thread("my_app/template_error")
        time.sleep(5)  # Give django some time to get to startup before requesting the page
        t.start()

        json_hit = json_facade.wait_for_thread_stopped("exception", line=7, file="template_error.html")

        stack_trace_request = json_facade.write_request(
            pydevd_schema.StackTraceRequest(
                pydevd_schema.StackTraceArguments(threadId=json_hit.thread_id, format={"module": True, "line": True})
            )
        )
        stack_trace_response = json_facade.wait_for_response(stack_trace_request)
        stack_trace_response_body = stack_trace_response.body
        stack_frame = next(iter(stack_trace_response_body.stackFrames))
        assert stack_frame["source"]["path"].endswith("template_error.html")

        json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)
        variables_response = json_facade.get_variables_response(json_hit.frame_id)
        entries = [x for x in variables_response.to_dict()["body"]["variables"] if x["name"] == "entry"]
        assert len(entries) == 1
        variables_response = json_facade.get_variables_response(entries[0]["variablesReference"])
        assert variables_response.to_dict()["body"]["variables"] == [
            {
                "name": "key",
                "value": "'v1'",
                "type": "str",
                "evaluateName": "entry.key",
                "presentationHint": {"attributes": ["rawString"]},
                "variablesReference": 0,
            },
            {
                "name": "val",
                "value": "'v1'",
                "type": "str",
                "evaluateName": "entry.val",
                "presentationHint": {"attributes": ["rawString"]},
                "variablesReference": 0,
            },
        ]

        json_facade.write_continue()

        if jmc:
            # If one jmc, uncaught should come through as well
            json_hit = json_facade.wait_for_thread_stopped("exception", line=7, file="template_error.html")
            json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.skipif(not TEST_DJANGO, reason="No django available")
def test_case_django_line_validation(case_setup_django_dap):
    import django  # noqa (may not be there if TEST_DJANGO == False)

    django_version = [int(x) for x in django.get_version().split(".")][:2]

    support_lazy_line_validation = django_version >= [1, 9]

    import django  # noqa (may not be there if TEST_DJANGO == False)

    with case_setup_django_dap.test_file(EXPECTED_RETURNCODE="any") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch(debugOptions=["DebugStdLib", "Django"])
        template_file = debugger_unittest._get_debugger_test_file(
            os.path.join(writer.DJANGO_FOLDER, "my_app", "templates", "my_app", "index.html")
        )
        file_doesnt_exist = os.path.join(os.path.dirname(template_file), "this_does_not_exist.html")

        # At this point, breakpoints will still not be verified (that'll happen when we
        # actually load the template).
        if support_lazy_line_validation:
            json_facade.write_set_breakpoints([1, 2, 4], template_file, verified=False)
        else:
            json_facade.write_set_breakpoints([1, 2, 4], template_file, verified=True)

        writer.write_make_initial_run()

        t = writer.create_request_thread("my_app")
        time.sleep(5)  # Give django some time to get to startup before requesting the page
        t.start()

        json_facade.wait_for_thread_stopped(line=1)
        breakpoint_events = json_facade.mark_messages(BreakpointEvent)

        found = {}
        for breakpoint_event in breakpoint_events:
            bp = breakpoint_event.body.breakpoint
            found[bp.id] = (bp.verified, bp.line)

        if support_lazy_line_validation:
            # At this point breakpoints were added.
            # id=0 / Line 1 is ok
            # id=1 / Line 2 will be disabled (because line 1 is already taken)
            # id=2 / Line 4 will be moved to line 3
            assert found == {
                0: (True, 1),
                1: (False, 2),
                2: (True, 3),
            }
        else:
            assert found == {}

        # Now, after the template was loaded, when setting the breakpoints we can already
        # know about the template validation.
        if support_lazy_line_validation:
            json_facade.write_set_breakpoints(
                [1, 2, 8],
                template_file,
                expected_lines_in_response=set((1, 2, 7)),
                # i.e.: breakpoint id to whether it's verified.
                verified={3: True, 4: False, 5: True},
            )
        else:
            json_facade.write_set_breakpoints([1, 2, 7], template_file, verified=True)

        json_facade.write_continue()
        json_facade.wait_for_thread_stopped(line=7)

        json_facade.write_continue()
        json_facade.wait_for_thread_stopped(line=7)

        # To finish, check that setting on a file that doesn't exist is not verified.
        response = json_facade.write_set_breakpoints([1], file_doesnt_exist, verified=False)
        for bp in response.body.breakpoints:
            assert "Breakpoint in file that does not exist" in bp["message"]

        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.skipif(not TEST_FLASK, reason="No flask available")
def test_case_flask_line_validation(case_setup_flask_dap):
    with case_setup_flask_dap.test_file(EXPECTED_RETURNCODE="any") as writer:
        json_facade = JsonFacade(writer)
        writer.write_set_project_roots([debugger_unittest._get_debugger_test_file("flask1")])
        json_facade.write_launch(debugOptions=["Jinja"])
        json_facade.write_make_initial_run()

        template_file = debugger_unittest._get_debugger_test_file(os.path.join("flask1", "templates", "hello.html"))

        # At this point, breakpoints will still not be verified (that'll happen when we
        # actually load the template).
        json_facade.write_set_breakpoints([1, 5, 6, 10], template_file, verified=False)

        writer.write_make_initial_run()

        t = writer.create_request_thread()
        time.sleep(2)  # Give flask some time to get to startup before requesting the page
        t.start()

        json_facade.wait_for_thread_stopped(line=5)
        breakpoint_events = json_facade.mark_messages(BreakpointEvent)

        found = {}
        for breakpoint_event in breakpoint_events:
            bp = breakpoint_event.body.breakpoint
            found[bp.id] = (bp.verified, bp.line)

        # At this point breakpoints were added.
        # id=0 / Line 1 will be disabled
        # id=1 / Line 5 is correct
        # id=2 / Line 6 will be disabled (because line 5 is already taken)
        # id=3 / Line 10 will be moved to line 8
        assert found == {
            0: (False, 1),
            1: (True, 5),
            2: (False, 6),
            3: (True, 8),
        }

        json_facade.write_continue()

        json_facade.wait_for_thread_stopped(line=8)
        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.skipif(not TEST_FLASK, reason="No flask available")
@pytest.mark.parametrize("jmc", [False, True])
def test_case_flask_exceptions(case_setup_flask_dap, jmc):
    with case_setup_flask_dap.test_file(EXPECTED_RETURNCODE="any") as writer:
        json_facade = JsonFacade(writer)

        if jmc:
            ignore_py_exceptions = False
            writer.write_set_project_roots([debugger_unittest._get_debugger_test_file("my_code")])
            json_facade.write_launch(debugOptions=["Jinja"])
            json_facade.write_set_exception_breakpoints(["raised"])
        else:
            ignore_py_exceptions = True
            json_facade.write_launch(debugOptions=["DebugStdLib", "Jinja"])
            # Don't set to all 'raised' because we'd stop on standard library exceptions here
            # (which is not something we want).
            json_facade.write_set_exception_breakpoints(
                exception_options=[
                    ExceptionOptions(
                        breakMode="always",
                        path=[
                            {"names": ["Python Exceptions"]},
                            {"names": ["IndexError"]},
                        ],
                    )
                ]
            )
        json_facade.write_make_initial_run()

        t = writer.create_request_thread("/bad_template")
        time.sleep(2)  # Give flask some time to get to startup before requesting the page
        t.start()

        while True:
            json_hit = json_facade.wait_for_thread_stopped("exception")
            path = json_hit.stack_trace_response.body.stackFrames[0]["source"]["path"]
            found_line = json_hit.stack_trace_response.body.stackFrames[0]["line"]
            if path.endswith("bad.html"):
                assert found_line == 8
                json_facade.write_continue()
                break

            if ignore_py_exceptions and path.endswith(".py"):
                json_facade.write_continue()
                continue

            raise AssertionError("Unexpected thread stop: at %s, %s" % (path, found_line))

        writer.finished_ok = True


@pytest.mark.skipif(IS_APPVEYOR or IS_JYTHON, reason="Flaky on appveyor / Jython encoding issues (needs investigation).")
def test_redirect_output(case_setup_dap):
    def get_environ(writer):
        env = os.environ.copy()

        env["PYTHONIOENCODING"] = "utf-8"
        return env

    with case_setup_dap.test_file("_debugger_case_redirect.py", get_environ=get_environ) as writer:
        original_ignore_stderr_line = writer._ignore_stderr_line

        json_facade = JsonFacade(writer)

        @overrides(writer._ignore_stderr_line)
        def _ignore_stderr_line(line):
            if original_ignore_stderr_line(line):
                return True

            binary_junk = b"\xe8\xf0\x80\x80\x80"
            if sys.version_info[0] >= 3:
                binary_junk = binary_junk.decode("utf-8", "replace")

            return line.startswith(
                (
                    "text",
                    "binary",
                    "a",
                    binary_junk,
                )
            )

        writer._ignore_stderr_line = _ignore_stderr_line

        # Note: writes to stdout and stderr are now synchronous (so, the order
        # must always be consistent and there's a message for each write).

        expected = [
            "text\n",
            "binary or text\n",
            "ação1\n",
        ]

        if sys.version_info[0] >= 3:
            expected.extend(
                (
                    "binary\n",
                    "ação2\n".encode(encoding="latin1").decode("utf-8", "replace"),
                    "ação3\n",
                )
            )

        binary_junk = "\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\n\n"
        if sys.version_info[0] >= 3:
            binary_junk = "\ufffd\ufffd\ufffd\ufffd\ufffd\n\n"
        expected.append(binary_junk)

        new_expected = [(x, "stdout") for x in expected]
        new_expected.extend([(x, "stderr") for x in expected])

        writer.write_start_redirect()

        writer.write_make_initial_run()
        msgs = []
        ignored = []
        while len(msgs) < len(new_expected):
            try:
                output_event = json_facade.wait_for_json_message(OutputEvent)
                output = output_event.body.output
                category = output_event.body.category
                msg = (output, category)
            except Exception:
                for msg in msgs:
                    sys.stderr.write("Found: %s\n" % (msg,))
                for msg in new_expected:
                    sys.stderr.write("Expected: %s\n" % (msg,))
                for msg in ignored:
                    sys.stderr.write("Ignored: %s\n" % (msg,))
                raise
            if msg not in new_expected:
                ignored.append(msg)
                continue
            msgs.append(msg)

        if msgs != new_expected:
            print(msgs)
            print(new_expected)
        assert msgs == new_expected
        writer.finished_ok = True


def test_listen_dap_messages(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_listen_dap_messages.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(
            debugOptions=["RedirectOutput"],
        )

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))
        json_facade.write_make_initial_run()

        json_facade.wait_for_thread_stopped()
        json_facade.write_continue()

        writer.finished_ok = True


def _attach_to_writer_pid(writer):
    import pydevd
    import threading
    import subprocess

    assert writer.process is not None

    def attach():
        attach_pydevd_file = os.path.join(os.path.dirname(pydevd.__file__), "pydevd_attach_to_process", "attach_pydevd.py")
        subprocess.call(
            [
                sys.executable,
                attach_pydevd_file,
                "--pid",
                str(writer.process.pid),
                "--port",
                str(writer.port),
                "--protocol",
                "http_json",
                "--debug-mode",
                "debugpy-dap",
            ]
        )

    threading.Thread(target=attach).start()

    wait_for_condition(lambda: writer.finished_initialization)


@pytest.mark.parametrize("reattach", [True, False])
@pytest.mark.skipif(not IS_CPYTHON or IS_MAC, reason="Attach to pid only available in CPython (brittle on Mac).")
@pytest.mark.skipif(not SUPPORT_ATTACH_TO_PID, reason="Attach to pid not supported.")
def test_attach_to_pid(case_setup_remote, reattach):
    import threading

    with case_setup_remote.test_file("_debugger_case_attach_to_pid_simple.py", wait_for_port=False) as writer:
        time.sleep(1)  # Give it some time to initialize to get to the while loop.
        _attach_to_writer_pid(writer)
        json_facade = JsonFacade(writer)

        bp_line = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints(bp_line)
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped(line=bp_line)

        if reattach:
            # This would be the same as a second attach to pid, so, the idea is closing the current
            # connection and then doing a new attach to pid.
            json_facade.write_set_breakpoints([])
            json_facade.write_continue()

            writer.do_kill()  # This will simply close the open sockets without doing anything else.
            time.sleep(1)

            t = threading.Thread(target=writer.start_socket)
            t.start()
            wait_for_condition(lambda: hasattr(writer, "port"))
            time.sleep(1)
            writer.process = writer.process
            _attach_to_writer_pid(writer)
            wait_for_condition(lambda: hasattr(writer, "reader_thread"))
            time.sleep(1)

            json_facade = JsonFacade(writer)
            json_facade.write_set_breakpoints(bp_line)
            json_facade.write_make_initial_run()

            json_hit = json_facade.wait_for_thread_stopped(line=bp_line)

        json_facade.write_set_variable(json_hit.frame_id, "wait", "0")

        json_facade.write_continue()

        writer.finished_ok = True


def test_remote_debugger_basic(case_setup_remote_dap):
    with case_setup_remote_dap.test_file("_debugger_case_remote.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch()
        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped()
        json_facade.write_continue()

        writer.finished_ok = True


PYDEVD_CUSTOMIZATION_COMMAND_LINE_ARGS = ["", "--use-c-switch"]
if hasattr(os, "posix_spawn"):
    PYDEVD_CUSTOMIZATION_COMMAND_LINE_ARGS.append("--posix-spawn")


@pytest.mark.parametrize("command_line_args", PYDEVD_CUSTOMIZATION_COMMAND_LINE_ARGS)
def test_subprocess_pydevd_customization(case_setup_remote_dap, command_line_args):
    import threading
    from tests_python.debugger_unittest import AbstractWriterThread

    with case_setup_remote_dap.test_file(
        "_debugger_case_pydevd_customization.py",
        append_command_line_args=command_line_args if command_line_args else [],
    ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.writer.write_multi_threads_single_notification(True)
        json_facade.write_launch()

        break1_line = writer.get_line_index_with_content("break 1 here")
        break2_line = writer.get_line_index_with_content("break 2 here")
        json_facade.write_set_breakpoints([break1_line, break2_line])

        server_socket = writer.server_socket

        class SecondaryProcessWriterThread(AbstractWriterThread):
            TEST_FILE = writer.get_main_filename()
            _sequence = -1

        class SecondaryProcessThreadCommunication(threading.Thread):
            def run(self):
                from tests_python.debugger_unittest import ReaderThread

                expected_connections = 1

                for _ in range(expected_connections):
                    server_socket.listen(1)
                    self.server_socket = server_socket
                    writer.log.append("  *** Multiprocess waiting on server_socket.accept()")
                    new_sock, addr = server_socket.accept()
                    writer.log.append("  *** Multiprocess completed server_socket.accept()")

                    reader_thread = ReaderThread(new_sock)
                    reader_thread.name = "  *** Multiprocess Reader Thread"
                    reader_thread.start()
                    writer.log.append("  *** Multiprocess started ReaderThread")

                    writer2 = SecondaryProcessWriterThread()
                    writer2._WRITE_LOG_PREFIX = "  *** Multiprocess write: "
                    writer2.reader_thread = reader_thread
                    writer2.sock = new_sock
                    json_facade2 = JsonFacade(writer2)
                    json_facade2.writer.write_multi_threads_single_notification(True)

                    json_facade2.write_set_breakpoints([break1_line, break2_line])
                    json_facade2.write_make_initial_run()

                json_facade2.wait_for_thread_stopped()
                json_facade2.write_continue()

        secondary_process_thread_communication = SecondaryProcessThreadCommunication()
        secondary_process_thread_communication.start()
        time.sleep(0.1)

        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped()

        json_facade.write_continue()
        json_facade.wait_for_thread_stopped()
        json_facade.write_continue()

        secondary_process_thread_communication.join(5)
        if secondary_process_thread_communication.is_alive():
            raise AssertionError("The SecondaryProcessThreadCommunication did not finish")
        writer.finished_ok = True


def test_subprocess_then_fork(case_setup_multiprocessing_dap):
    import threading
    from tests_python.debugger_unittest import AbstractWriterThread

    with case_setup_multiprocessing_dap.test_file("_debugger_case_subprocess_and_fork.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)

        break_line = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints([break_line])

        server_socket = writer.server_socket

        class SecondaryProcessWriterThread(AbstractWriterThread):
            TEST_FILE = writer.get_main_filename()
            _sequence = -1

        class SecondaryProcessThreadCommunication(threading.Thread):
            def run(self):
                from tests_python.debugger_unittest import ReaderThread

                # Note that we accept 2 connections and then we proceed to receive the breakpoints.
                json_facades = []
                for i in range(2):
                    server_socket.listen(1)
                    self.server_socket = server_socket
                    writer.log.append("  *** Multiprocess %s waiting on server_socket.accept()" % (i,))
                    new_sock, addr = server_socket.accept()
                    writer.log.append("  *** Multiprocess %s completed server_socket.accept()" % (i,))

                    reader_thread = ReaderThread(new_sock)
                    reader_thread.name = "  *** Multiprocess %s Reader Thread" % i
                    reader_thread.start()
                    writer.log.append("  *** Multiprocess %s started ReaderThread" % (i,))

                    writer2 = SecondaryProcessWriterThread()
                    writer2._WRITE_LOG_PREFIX = "  *** Multiprocess %s write: " % i
                    writer2.reader_thread = reader_thread
                    writer2.sock = new_sock
                    json_facade2 = JsonFacade(writer2)
                    json_facade2.writer.write_multi_threads_single_notification(True)
                    writer.log.append("  *** Multiprocess %s write attachThread" % (i,))
                    json_facade2.write_attach(justMyCode=False)

                    writer.log.append("  *** Multiprocess %s write set breakpoints" % (i,))
                    json_facade2.write_set_breakpoints([break_line])
                    writer.log.append("  *** Multiprocess %s write make initial run" % (i,))
                    json_facade2.write_make_initial_run()
                    json_facades.append(json_facade2)

                for i, json_facade3 in enumerate(json_facades):
                    writer.log.append("  *** Multiprocess %s wait for thread stopped" % (i,))
                    json_facade3.wait_for_thread_stopped(line=break_line)
                    writer.log.append("  *** Multiprocess %s continue" % (i,))
                    json_facade3.write_continue()

        secondary_process_thread_communication = SecondaryProcessThreadCommunication()
        secondary_process_thread_communication.start()
        time.sleep(0.1)
        json_facade.write_make_initial_run()

        secondary_process_thread_communication.join(20)
        if secondary_process_thread_communication.is_alive():
            raise AssertionError("The SecondaryProcessThreadCommunication did not finish")

        json_facade.wait_for_thread_stopped(line=break_line)
        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.parametrize("apply_multiprocessing_patch", [True])
def test_no_subprocess_patching(case_setup_multiprocessing_dap, apply_multiprocessing_patch):
    import threading
    from tests_python.debugger_unittest import AbstractWriterThread

    def update_command_line_args(writer, args):
        ret = debugger_unittest.AbstractWriterThread.update_command_line_args(writer, args)
        ret.insert(ret.index("--client"), "--multiprocess")
        ret.insert(ret.index("--client"), "--debug-mode")
        ret.insert(ret.index("--client"), "debugpy-dap")
        ret.insert(ret.index("--client"), "--json-dap-http")

        if apply_multiprocessing_patch:
            ret.append("apply-multiprocessing-patch")
        return ret

    with case_setup_multiprocessing_dap.test_file(
        "_debugger_case_no_subprocess_patching.py", update_command_line_args=update_command_line_args
    ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch()

        break1_line = writer.get_line_index_with_content("break 1 here")
        break2_line = writer.get_line_index_with_content("break 2 here")
        json_facade.write_set_breakpoints([break1_line, break2_line])

        server_socket = writer.server_socket

        class SecondaryProcessWriterThread(AbstractWriterThread):
            TEST_FILE = writer.get_main_filename()
            _sequence = -1

        class SecondaryProcessThreadCommunication(threading.Thread):
            def run(self):
                from tests_python.debugger_unittest import ReaderThread

                expected_connections = 1

                for _ in range(expected_connections):
                    server_socket.listen(1)
                    self.server_socket = server_socket
                    new_sock, addr = server_socket.accept()

                    reader_thread = ReaderThread(new_sock)
                    reader_thread.name = "  *** Multiprocess Reader Thread"
                    reader_thread.start()

                    writer2 = SecondaryProcessWriterThread()
                    writer2.reader_thread = reader_thread
                    writer2.sock = new_sock
                    json_facade2 = JsonFacade(writer2)

                    json_facade2.write_set_breakpoints([break1_line, break2_line])
                    json_facade2.write_make_initial_run()

                json_facade2.wait_for_thread_stopped()
                json_facade2.write_continue()

        if apply_multiprocessing_patch:
            secondary_process_thread_communication = SecondaryProcessThreadCommunication()
            secondary_process_thread_communication.start()
            time.sleep(0.1)

        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped()
        json_facade.write_continue()

        if apply_multiprocessing_patch:
            secondary_process_thread_communication.join(10)
            if secondary_process_thread_communication.is_alive():
                raise AssertionError("The SecondaryProcessThreadCommunication did not finish")
        writer.finished_ok = True


def test_module_crash(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_module.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()

        stopped_event = json_facade.wait_for_json_message(StoppedEvent)
        thread_id = stopped_event.body.threadId

        json_facade.write_request(pydevd_schema.StackTraceRequest(pydevd_schema.StackTraceArguments(threadId=thread_id)))

        module_event = json_facade.wait_for_json_message(ModuleEvent)  # : :type module_event: ModuleEvent
        assert "MyName" in module_event.body.module.name
        assert "MyVersion" in module_event.body.module.version
        assert "MyPackage" in module_event.body.module.kwargs["package"]

        json_facade.write_continue()

        writer.finished_ok = True


def test_pydevd_systeminfo(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_print.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        assert json_hit.thread_id

        info_request = json_facade.write_request(pydevd_schema.PydevdSystemInfoRequest(pydevd_schema.PydevdSystemInfoArguments()))
        info_response = json_facade.wait_for_response(info_request)
        body = info_response.to_dict()["body"]

        assert body["python"]["version"] == PY_VERSION_STR
        assert body["python"]["implementation"]["name"] == PY_IMPL_NAME
        assert body["python"]["implementation"]["version"] == PY_IMPL_VERSION_STR
        assert "description" in body["python"]["implementation"]

        assert body["platform"] == {"name": sys.platform}

        assert "pid" in body["process"]
        assert "ppid" in body["process"]
        assert body["process"]["executable"] == sys.executable
        assert body["process"]["bitness"] == 64 if IS_64BIT_PROCESS else 32

        assert "usingCython" in body["pydevd"]
        assert "usingFrameEval" in body["pydevd"]

        use_cython = os.getenv("PYDEVD_USE_CYTHON")
        if use_cython is not None:
            using_cython = use_cython == "YES"
            assert body["pydevd"]["usingCython"] == using_cython
            assert body["pydevd"]["usingFrameEval"] == (using_cython and IS_PY36_OR_GREATER and not IS_PY311_OR_GREATER)

        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.parametrize("scenario", ["terminate_request", "terminate_debugee"])
@pytest.mark.parametrize(
    "check_subprocesses",
    [
        "no_subprocesses",
        "kill_subprocesses",
        "kill_subprocesses_ignore_pid",
        "dont_kill_subprocesses",
    ],
)
def test_terminate(case_setup_dap, scenario, check_subprocesses):
    import psutil

    def check_test_suceeded_msg(writer, stdout, stderr):
        return "TEST SUCEEDED" not in "".join(stdout)

    def update_command_line_args(writer, args):
        ret = debugger_unittest.AbstractWriterThread.update_command_line_args(writer, args)
        if check_subprocesses in ("kill_subprocesses", "dont_kill_subprocesses"):
            ret.append("check-subprocesses")
        if check_subprocesses in ("kill_subprocesses_ignore_pid",):
            ret.append("check-subprocesses-ignore-pid")
        return ret

    with case_setup_dap.test_file(
        "_debugger_case_terminate.py",
        check_test_suceeded_msg=check_test_suceeded_msg,
        update_command_line_args=update_command_line_args,
        EXPECTED_RETURNCODE="any" if check_subprocesses == "kill_subprocesses_ignore_pid" else 0,
    ) as writer:
        json_facade = JsonFacade(writer)
        if check_subprocesses == "dont_kill_subprocesses":
            json_facade.write_launch(terminateChildProcesses=False)

        json_facade.write_make_initial_run()
        response = json_facade.write_initialize()
        pid = response.to_dict()["body"]["pydevd"]["processId"]

        if check_subprocesses in ("kill_subprocesses", "dont_kill_subprocesses", "kill_subprocesses_ignore_pid"):
            process_ids_to_check = [pid]
            p = psutil.Process(pid)

            def wait_for_child_processes():
                children = p.children(recursive=True)
                found = len(children)
                if found == 8:
                    process_ids_to_check.extend([x.pid for x in children])
                    return True
                return False

            wait_for_condition(wait_for_child_processes)

        if scenario == "terminate_request":
            json_facade.write_terminate()
        elif scenario == "terminate_debugee":
            json_facade.write_disconnect(terminate_debugee=True)
        else:
            raise AssertionError("Unexpected: %s" % (scenario,))
        json_facade.wait_for_terminated()

        if check_subprocesses in ("kill_subprocesses", "dont_kill_subprocesses", "kill_subprocesses_ignore_pid"):

            def is_pid_alive(pid):
                # Note: the process may be a zombie process in Linux
                # (althought it's killed it remains in that state
                # because we're monitoring it).
                try:
                    proc = psutil.Process(pid)
                    if proc.status() == psutil.STATUS_ZOMBIE:
                        return False
                except psutil.NoSuchProcess:
                    return False
                return True

            def get_live_pids():
                return [pid for pid in process_ids_to_check if is_pid_alive(pid)]

            if check_subprocesses == "kill_subprocesses":

                def all_pids_exited():
                    live_pids = get_live_pids()
                    if live_pids:
                        return False

                    return True

                wait_for_condition(all_pids_exited)

            elif check_subprocesses == "kill_subprocesses_ignore_pid":

                def all_pids_exited():
                    live_pids = get_live_pids()
                    if len(live_pids) == 1:
                        return False

                    return True

                wait_for_condition(all_pids_exited)

                # Now, let's kill the remaining process ourselves.
                for pid in get_live_pids():
                    proc = psutil.Process(pid)
                    proc.kill()

            else:  # 'dont_kill_subprocesses'
                time.sleep(1)

                def only_main_pid_exited():
                    live_pids = get_live_pids()
                    if len(live_pids) == len(process_ids_to_check) - 1:
                        return True

                    return False

                wait_for_condition(only_main_pid_exited)

                # Now, let's kill the remaining processes ourselves.
                for pid in get_live_pids():
                    proc = psutil.Process(pid)
                    proc.kill()

        writer.finished_ok = True


def test_access_token(case_setup_dap):
    def update_command_line_args(self, args):
        args.insert(1, "--json-dap-http")
        args.insert(2, "--access-token")
        args.insert(3, "bar123")
        args.insert(4, "--client-access-token")
        args.insert(5, "foo321")
        return args

    with case_setup_dap.test_file("_debugger_case_pause_continue.py", update_command_line_args=update_command_line_args) as writer:
        json_facade = JsonFacade(writer)

        response = json_facade.write_set_debugger_property(multi_threads_single_notification=True, success=False)
        assert response.message == "Client not authenticated."

        response = json_facade.write_authorize(access_token="wrong", success=False)
        assert response.message == "Client not authenticated."

        response = json_facade.write_set_debugger_property(multi_threads_single_notification=True, success=False)
        assert response.message == "Client not authenticated."

        authorize_response = json_facade.write_authorize(access_token="bar123", success=True)
        # : :type authorize_response:PydevdAuthorizeResponse
        assert authorize_response.body.clientAccessToken == "foo321"

        json_facade.write_set_debugger_property(multi_threads_single_notification=True)
        json_facade.write_launch()

        break_line = writer.get_line_index_with_content("Pause here and change loop to False")
        json_facade.write_set_breakpoints(break_line)
        json_facade.write_make_initial_run()

        json_facade.wait_for_json_message(ThreadEvent, lambda event: event.body.reason == "started")
        json_facade.wait_for_thread_stopped(line=break_line)

        # : :type response: ThreadsResponse
        response = json_facade.write_list_threads()
        assert len(response.body.threads) == 1
        assert next(iter(response.body.threads))["name"] == "MainThread"

        json_facade.write_disconnect()

        response = json_facade.write_authorize(access_token="wrong", success=False)
        assert response.message == "Client not authenticated."

        authorize_response = json_facade.write_authorize(access_token="bar123")
        assert authorize_response.body.clientAccessToken == "foo321"

        json_facade.write_set_breakpoints(break_line)
        json_hit = json_facade.wait_for_thread_stopped(line=break_line)
        json_facade.write_set_variable(json_hit.frame_id, "loop", "False")
        json_facade.write_continue()
        json_facade.wait_for_terminated()

        writer.finished_ok = True


def test_stop_on_entry(case_setup_dap):
    with case_setup_dap.test_file("not_my_code/main_on_entry.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(
            justMyCode=False,
            stopOnEntry=True,
            rules=[
                {"path": "**/not_my_code/**", "include": False},
            ],
        )

        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped(
            "entry",
            file=(
                # We need to match the end with the proper slash.
                "my_code/__init__.py",
                "my_code\\__init__.py",
            ),
        )
        json_facade.write_continue()
        writer.finished_ok = True


def test_stop_on_entry2(case_setup_dap):
    with case_setup_dap.test_file("not_my_code/main_on_entry2.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(
            justMyCode=False,
            stopOnEntry=True,
            showReturnValue=True,
            rules=[
                {"path": "**/main_on_entry2.py", "include": False},
            ],
        )

        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped("entry", file="empty_file.py")
        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.parametrize("val", [True, False])
def test_debug_options(case_setup_dap, val):
    with case_setup_dap.test_file("_debugger_case_debug_options.py") as writer:
        json_facade = JsonFacade(writer)
        gui_event_loop = "matplotlib"
        if val:
            try:
                import PySide2.QtCore
            except ImportError:
                pass
            else:
                gui_event_loop = "pyside2"
        args = dict(
            justMyCode=val,
            redirectOutput=True,  # Always redirect the output regardless of other values.
            showReturnValue=val,
            breakOnSystemExitZero=val,
            django=val,
            flask=val,
            stopOnEntry=val,
            maxExceptionStackFrames=4 if val else 5,
            guiEventLoop=gui_event_loop,
            clientOS="UNIX" if val else "WINDOWS",
        )
        json_facade.write_launch(**args)

        json_facade.write_make_initial_run()
        if args["stopOnEntry"]:
            json_facade.wait_for_thread_stopped("entry")
            json_facade.write_continue()

        output = json_facade.wait_for_json_message(
            OutputEvent, lambda msg: msg.body.category == "stdout" and msg.body.output.startswith("{") and msg.body.output.endswith("}")
        )

        # The values printed are internal values from _pydevd_bundle.pydevd_json_debug_options.DebugOptions,
        # not the parameters we passed.
        translation = {
            "django": "django_debug",
            "flask": "flask_debug",
            "justMyCode": "just_my_code",
            "redirectOutput": "redirect_output",
            "showReturnValue": "show_return_value",
            "breakOnSystemExitZero": "break_system_exit_zero",
            "stopOnEntry": "stop_on_entry",
            "maxExceptionStackFrames": "max_exception_stack_frames",
            "guiEventLoop": "gui_event_loop",
            "clientOS": "client_os",
        }

        assert json.loads(output.body.output) == dict((translation[key], val) for key, val in args.items())
        json_facade.wait_for_terminated()
        writer.finished_ok = True


def test_gui_event_loop_custom(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_gui_event_loop.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(guiEventLoop="__main__.LoopHolder.gui_loop", redirectOutput=True)
        break_line = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints(break_line)

        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped()

        json_facade.wait_for_json_message(OutputEvent, lambda msg: msg.body.category == "stdout" and "gui_loop() called" in msg.body.output)

        json_facade.write_continue()
        json_facade.wait_for_terminated()
        writer.finished_ok = True


def test_gui_event_loop_qt5(case_setup_dap):
    try:
        from PySide2 import QtCore
    except ImportError:
        pytest.skip("PySide2 not available")

    with case_setup_dap.test_file("_debugger_case_gui_event_loop_qt5.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(guiEventLoop="qt5", redirectOutput=True)
        break_line = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints(break_line)

        json_facade.write_make_initial_run()
        json_facade.wait_for_thread_stopped()

        # i.e.: if we don't have the event loop running in this test, this
        # output is not shown (as the QTimer timeout wouldn't be executed).
        for _i in range(3):
            json_facade.wait_for_json_message(
                OutputEvent, lambda msg: msg.body.category == "stdout" and "on_timeout() called" in msg.body.output
            )

        json_facade.write_continue()
        json_facade.wait_for_terminated()
        writer.finished_ok = True


@pytest.mark.parametrize("debug_stdlib", [True, False])
def test_just_my_code_debug_option_deprecated(case_setup_dap, debug_stdlib, debugger_runner_simple):
    from _pydev_bundle import pydev_log

    with case_setup_dap.test_file("_debugger_case_debug_options.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(
            redirectOutput=True,  # Always redirect the output regardless of other values.
            debugStdLib=debug_stdlib,
        )
        json_facade.write_make_initial_run()
        output = json_facade.wait_for_json_message(
            OutputEvent, lambda msg: msg.body.category == "stdout" and msg.body.output.startswith("{") and msg.body.output.endswith("}")
        )

        settings = json.loads(output.body.output)
        # Note: the internal attribute is just_my_code.
        assert settings["just_my_code"] == (not debug_stdlib)
        json_facade.wait_for_terminated()

        contents = []
        for f in pydev_log.list_log_files(debugger_runner_simple.pydevd_debug_file):
            if os.path.exists(f):
                with open(f, "r") as stream:
                    contents.append(stream.read())

        writer.finished_ok = True


def test_send_invalid_messages(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_local_variables.py") as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break 2 here"))
        json_facade.write_make_initial_run()

        stopped_event = json_facade.wait_for_json_message(StoppedEvent)
        thread_id = stopped_event.body.threadId

        json_facade.write_request(pydevd_schema.StackTraceRequest(pydevd_schema.StackTraceArguments(threadId=thread_id)))

        # : :type response: ModulesResponse
        # : :type modules_response_body: ModulesResponseBody

        # *** Check that we accept an invalid modules request (i.e.: without arguments).
        response = json_facade.wait_for_response(json_facade.write_request({"type": "request", "command": "modules"}))

        modules_response_body = response.body
        assert len(modules_response_body.modules) == 1
        module = next(iter(modules_response_body.modules))
        assert module["name"] == "__main__"
        assert module["path"].endswith("_debugger_case_local_variables.py")

        # *** Check that we don't fail on request without command.
        request = json_facade.write_request({"type": "request"})
        response = json_facade.wait_for_response(request, Response)
        assert not response.success
        assert response.command == "<unknown>"

        # *** Check that we don't crash if we can't decode message.
        json_facade.writer.write_with_content_len("invalid json here")

        # *** Check that we get a failure from a completions without arguments.
        response = json_facade.wait_for_response(json_facade.write_request({"type": "request", "command": "completions"}))
        assert not response.success

        json_facade.write_continue()
        writer.finished_ok = True


def test_send_json_message(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_custom_message.py") as writer:
        json_facade = JsonFacade(writer)

        json_facade.write_launch()

        json_facade.write_make_initial_run()

        json_facade.wait_for_json_message(OutputEvent, lambda msg: msg.body.category == "my_category" and msg.body.output == "some output")

        json_facade.wait_for_json_message(
            OutputEvent, lambda msg: msg.body.category == "my_category2" and msg.body.output == "some output 2"
        )

        writer.finished_ok = True


def test_global_scope(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_globals.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_set_breakpoints(writer.get_line_index_with_content("breakpoint here"))

        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped()

        local_var = json_facade.get_global_var(json_hit.frame_id, "in_global_scope")
        assert local_var.value == "'in_global_scope_value'"
        json_facade.write_continue()

        writer.finished_ok = True


def _check_inline_var_presentation(json_facade, json_hit, variables_response):
    var_names = [v["name"] for v in variables_response.body.variables]
    assert var_names[:3] == ["SomeClass", "in_global_scope", "__builtins__"]


def _check_hide_var_presentation(json_facade, json_hit, variables_response):
    var_names = [v["name"] for v in variables_response.body.variables]
    assert var_names == ["in_global_scope"]


def _check_class_group_special_inline_presentation(json_facade, json_hit, variables_response):
    var_names = [v["name"] for v in variables_response.body.variables]
    assert var_names[:3] == ["class variables", "in_global_scope", "__builtins__"]

    variables_response = json_facade.get_variables_response(variables_response.body.variables[0]["variablesReference"])
    var_names = [v["name"] for v in variables_response.body.variables]
    assert var_names == ["SomeClass"]


@pytest.mark.parametrize(
    "var_presentation, check_func",
    [
        ({"all": "inline"}, _check_inline_var_presentation),
        ({"all": "hide"}, _check_hide_var_presentation),
        ({"class": "group", "special": "inline"}, _check_class_group_special_inline_presentation),
    ],
)
def test_variable_presentation(case_setup_dap, var_presentation, check_func):
    with case_setup_dap.test_file("_debugger_case_globals.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(variablePresentation=var_presentation)
        json_facade.write_set_breakpoints(writer.get_line_index_with_content("breakpoint here"))

        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped()
        name_to_scope = json_facade.get_name_to_scope(json_hit.frame_id)

        variables_response = json_facade.get_variables_response(name_to_scope["Globals"].variablesReference)
        check_func(json_facade, json_hit, variables_response)

        json_facade.write_continue()

        writer.finished_ok = True


def test_debugger_case_deadlock_thread_eval(case_setup_dap):
    def get_environ(self):
        env = os.environ.copy()
        env["PYDEVD_UNBLOCK_THREADS_TIMEOUT"] = "0.5"
        return env

    with case_setup_dap.test_file("_debugger_case_deadlock_thread_eval.py", get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch()
        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here 1"))

        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped()

        # If threads aren't resumed, this will deadlock.
        json_facade.evaluate('processor.process("process in evaluate")', json_hit.frame_id)

        json_facade.write_continue()

        writer.finished_ok = True


def test_debugger_case_breakpoint_on_unblock_thread_eval(case_setup_dap):
    from _pydevd_bundle._debug_adapter.pydevd_schema import EvaluateResponse

    def get_environ(self):
        env = os.environ.copy()
        env["PYDEVD_UNBLOCK_THREADS_TIMEOUT"] = "0.5"
        return env

    with case_setup_dap.test_file("_debugger_case_deadlock_thread_eval.py", get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch()
        break1 = writer.get_line_index_with_content("Break here 1")
        break2 = writer.get_line_index_with_content("Break here 2")
        json_facade.write_set_breakpoints([break1, break2])

        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped(line=break1)

        # If threads aren't resumed, this will deadlock.
        evaluate_request = json_facade.evaluate('processor.process("process in evaluate")', json_hit.frame_id, wait_for_response=False)

        # We'll hit another breakpoint during that evaluation.
        json_hit = json_facade.wait_for_thread_stopped(line=break2)
        json_facade.write_set_breakpoints([])
        json_facade.write_continue()

        json_hit = json_facade.wait_for_thread_stopped(line=break1)
        json_facade.write_continue()

        # Check that we got the evaluate responses.
        messages = json_facade.mark_messages(
            EvaluateResponse, lambda evaluate_response: evaluate_response.request_seq == evaluate_request.seq
        )
        assert len(messages) == 1

        writer.finished_ok = True


def test_debugger_case_unblock_manually(case_setup_dap):
    from _pydevd_bundle._debug_adapter.pydevd_schema import EvaluateResponse

    def get_environ(self):
        env = os.environ.copy()
        env["PYDEVD_WARN_EVALUATION_TIMEOUT"] = "0.5"
        return env

    with case_setup_dap.test_file("_debugger_case_deadlock_thread_eval.py", get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch()
        break1 = writer.get_line_index_with_content("Break here 1")
        json_facade.write_set_breakpoints([break1])

        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped(line=break1)

        # If threads aren't resumed, this will deadlock.
        evaluate_request = json_facade.evaluate('processor.process("process in evaluate")', json_hit.frame_id, wait_for_response=False)

        json_facade.wait_for_json_message(OutputEvent, lambda output_event: "did not finish after" in output_event.body.output)

        # User may manually resume it.
        json_facade.write_continue()

        # Check that we got the evaluate responses.
        json_facade.wait_for_json_message(EvaluateResponse, lambda evaluate_response: evaluate_response.request_seq == evaluate_request.seq)

        writer.finished_ok = True


def test_debugger_case_deadlock_notify_evaluate_timeout(case_setup_dap, pyfile):
    @pyfile
    def case_slow_evaluate():
        def slow_evaluate():
            import time

            time.sleep(2)

        print("TEST SUCEEDED!")  # Break here

    def get_environ(self):
        env = os.environ.copy()
        env["PYDEVD_WARN_EVALUATION_TIMEOUT"] = "0.5"
        return env

    with case_setup_dap.test_file(case_slow_evaluate, get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)
        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped()

        # If threads aren't resumed, this will deadlock.
        json_facade.evaluate("slow_evaluate()", json_hit.frame_id)

        json_facade.write_continue()

        messages = json_facade.mark_messages(OutputEvent, lambda output_event: "did not finish after" in output_event.body.output)
        assert len(messages) == 1

        writer.finished_ok = True


def test_debugger_case_deadlock_interrupt_thread(case_setup_dap, pyfile):
    @pyfile
    def case_infinite_evaluate():
        def infinite_evaluate():
            import time

            while True:
                time.sleep(0.1)

        print("TEST SUCEEDED!")  # Break here

    def get_environ(self):
        env = os.environ.copy()
        env["PYDEVD_INTERRUPT_THREAD_TIMEOUT"] = "0.5"
        return env

    # Sometimes we end up with a different return code on Linux when interrupting (even
    # though we go through completion and print the 'TEST SUCEEDED' msg).
    with case_setup_dap.test_file(case_infinite_evaluate, get_environ=get_environ, EXPECTED_RETURNCODE="any") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)
        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped()

        # If threads aren't resumed, this will deadlock.
        json_facade.evaluate("infinite_evaluate()", json_hit.frame_id, wait_for_response=False)

        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.parametrize("launch_through_link", [True, False])
@pytest.mark.parametrize("breakpoints_through_link", [True, False])
def test_debugger_case_symlink(case_setup_dap, tmpdir, launch_through_link, breakpoints_through_link):
    """
    Test that even if we resolve links internally, externally the contents will be
    related to the version launched.
    """

    from tests_python.debugger_unittest import _get_debugger_test_file

    original_filename = _get_debugger_test_file("_debugger_case2.py")

    target_link = str(tmpdir.join("resources_link"))
    if pydevd_constants.IS_WINDOWS and not pydevd_constants.IS_PY38_OR_GREATER:
        pytest.skip("Symlink support not available.")

    try:
        os.symlink(os.path.dirname(original_filename), target_link, target_is_directory=True)
    except (OSError, TypeError, AttributeError):
        pytest.skip("Symlink support not available.")

    try:
        target_filename_in_link = os.path.join(target_link, "_debugger_case2.py")

        with case_setup_dap.test_file(target_filename_in_link if launch_through_link else original_filename) as writer:
            json_facade = JsonFacade(writer)
            json_facade.write_launch(justMyCode=False)

            # Note that internally links are resolved to match the breakpoint, so,
            # it doesn't matter if the breakpoint was added as viewed through the
            # link or the real path.
            json_facade.write_set_breakpoints(
                writer.get_line_index_with_content("print('Start Call1')"),
                filename=target_filename_in_link if breakpoints_through_link else original_filename,
            )

            json_facade.write_make_initial_run()
            json_hit = json_facade.wait_for_thread_stopped()
            path = json_hit.stack_trace_response.body.stackFrames[0]["source"]["path"]

            # Regardless of how it was hit, what's shown is what was launched.
            assert path == target_filename_in_link if launch_through_link else original_filename

            json_facade.write_continue()

            writer.finished_ok = True
    finally:
        # We must remove the link, otherwise pytest can end up removing things under that
        # directory when collecting temporary files.
        os.unlink(target_link)


@pytest.mark.skipif(not IS_LINUX, reason="Linux only test.")
def test_debugger_case_sensitive(case_setup_dap, tmpdir):
    path = os.path.abspath(str(tmpdir.join("Path1").join("PaTh2")))
    os.makedirs(path)
    target = os.path.join(path, "myFile.py")
    with open(target, "w") as stream:
        stream.write(
            """
print('current file', __file__) # Break here
print('TEST SUCEEDED')
"""
        )
    assert not os.path.exists(target.lower())
    assert os.path.exists(target)

    def get_environ(self):
        env = os.environ.copy()
        # Force to normalize by doing filename.lower().
        env["PYDEVD_FILENAME_NORMALIZATION"] = "lower"
        return env

    # Sometimes we end up with a different return code on Linux when interrupting (even
    # though we go through completion and print the 'TEST SUCEEDED' msg).
    with case_setup_dap.test_file(target, get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)
        json_facade.write_set_breakpoints(writer.get_line_index_with_content("Break here"))

        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped()
        path = json_hit.stack_trace_response.body.stackFrames[0]["source"]["path"]
        assert path == target

        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.skipif(
    not (IS_PY312_OR_GREATER and IS_WINDOWS)  # Always works with sys.monitoring (even without TEST_CYTHON)
    and (
        not IS_WINDOWS
        or not IS_PY36_OR_GREATER
        or not IS_CPYTHON
        or not TEST_CYTHON
        or IS_PY311  # Requires frame-eval mode (not available for Python 3.11).
    ),
    # Note that this works in Python 3.12 as it uses sys.monitoring.
    reason="Windows only test and only Python 3.6 onwards.",
)
def test_native_threads(case_setup_dap, pyfile):
    @pyfile
    def case_native_thread():
        from ctypes import windll, WINFUNCTYPE, c_uint32, c_void_p, c_size_t
        import time

        ThreadProc = WINFUNCTYPE(c_uint32, c_void_p)

        entered_thread = [False]

        @ThreadProc
        def method(_):
            entered_thread[0] = True  # Break here
            return 0

        windll.kernel32.CreateThread(None, c_size_t(0), method, None, c_uint32(0), None)
        while not entered_thread[0]:
            time.sleep(0.1)

        print("TEST SUCEEDED")

    with case_setup_dap.test_file(case_native_thread) as writer:
        json_facade = JsonFacade(writer)

        line = writer.get_line_index_with_content("Break here")
        json_facade.write_launch(justMyCode=False)
        json_facade.write_set_breakpoints(line)
        json_facade.write_make_initial_run()

        json_facade.wait_for_thread_stopped(line=line)

        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.skipif(not IS_PY313_OR_GREATER, reason="3.13 onwards only test.")
def test_internal_thread(case_setup_dap, pyfile):
    @pyfile
    def case_native_thread():
        import _thread
        import time

        entered_thread = [False]

        def method(*args, **kwargs):
            entered_thread[0] = True  # Break here
            return 0

        # Using it directly must still work!
        _thread.start_joinable_thread(method)

        while not entered_thread[0]:
            time.sleep(0.1)

        print("TEST SUCEEDED")

    with case_setup_dap.test_file(case_native_thread) as writer:
        json_facade = JsonFacade(writer)

        line = writer.get_line_index_with_content("Break here")
        json_facade.write_launch(justMyCode=False)
        json_facade.write_set_breakpoints(line)
        json_facade.write_make_initial_run()

        json_facade.wait_for_thread_stopped(line=line)

        json_facade.write_continue()
        writer.finished_ok = True


def test_code_reload(case_setup_dap, pyfile):
    @pyfile
    def mod1():
        import mod2
        import time

        finish = False
        for _ in range(50):
            finish = mod2.do_something()
            if finish:
                break
            time.sleep(0.1)  # Break 1
        else:
            raise AssertionError("It seems the reload was not done in the available amount of time.")

        print("TEST SUCEEDED")  # Break 2

    @pyfile
    def mod2():
        def do_something():
            return False

    with case_setup_dap.test_file(mod1) as writer:
        json_facade = JsonFacade(writer)

        line1 = writer.get_line_index_with_content("Break 1")
        line2 = writer.get_line_index_with_content("Break 2")
        json_facade.write_launch(justMyCode=False, autoReload={"pollingInterval": 0, "enable": True})
        json_facade.write_set_breakpoints([line1, line2])
        json_facade.write_make_initial_run()

        # At this point we know that 'do_something' was called at least once.
        json_facade.wait_for_thread_stopped(line=line1)
        json_facade.write_set_breakpoints(line2)

        with open(mod2, "w") as stream:
            stream.write(
                """
def do_something():
    return True
"""
            )

        json_facade.write_continue()
        json_facade.wait_for_thread_stopped(line=line2)
        json_facade.write_continue()

        writer.finished_ok = True


def test_step_into_target_basic(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_smart_step_into.py") as writer:
        json_facade = JsonFacade(writer)

        bp = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints([bp])
        json_facade.write_make_initial_run()

        # At this point we know that 'do_something' was called at least once.
        hit = json_facade.wait_for_thread_stopped(line=bp)

        # : :type step_in_targets: List[StepInTarget]
        step_in_targets = json_facade.get_step_in_targets(hit.frame_id)
        label_to_id = dict((target["label"], target["id"]) for target in step_in_targets)
        if IS_PY311_OR_GREATER:
            assert set(label_to_id.keys()) == {"call_outer(foo(bar()))", "foo(bar())", "bar()"}
            target = "foo(bar())"
        else:
            assert set(label_to_id.keys()) == {"bar", "foo", "call_outer"}
            target = "foo"
        json_facade.write_step_in(hit.thread_id, target_id=label_to_id[target])

        on_foo_mark_line = writer.get_line_index_with_content("on foo mark")
        hit = json_facade.wait_for_thread_stopped(reason="step", line=on_foo_mark_line)
        json_facade.write_continue()

        writer.finished_ok = True


def test_step_into_target_multiple(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_smart_step_into2.py") as writer:
        json_facade = JsonFacade(writer)

        bp = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints([bp])
        json_facade.write_make_initial_run()

        # At this point we know that 'do_something' was called at least once.
        hit = json_facade.wait_for_thread_stopped(line=bp)

        # : :type step_in_targets: List[StepInTarget]
        step_in_targets = json_facade.get_step_in_targets(hit.frame_id)
        label_to_id = dict((target["label"], target["id"]) for target in step_in_targets)
        if IS_PY311_OR_GREATER:
            assert set(label_to_id.keys()) == {"foo(foo(foo(foo(1))))", "foo(foo(foo(1)))", "foo(foo(1))", "foo(1)"}
            target = "foo(foo(1))"
        else:
            assert set(label_to_id.keys()) == {"foo", "foo (call 2)", "foo (call 3)", "foo (call 4)"}
            target = "foo (call 2)"
        json_facade.write_step_in(hit.thread_id, target_id=label_to_id[target])

        on_foo_mark_line = writer.get_line_index_with_content("on foo mark")
        hit = json_facade.wait_for_thread_stopped(reason="step", line=on_foo_mark_line)
        json_facade.write_continue()

        writer.finished_ok = True


def test_step_into_target_genexpr(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_smart_step_into3.py") as writer:
        json_facade = JsonFacade(writer)

        bp = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints([bp])
        json_facade.write_make_initial_run()

        # At this point we know that 'do_something' was called at least once.
        hit = json_facade.wait_for_thread_stopped(line=bp)

        # : :type step_in_targets: List[StepInTarget]
        step_in_targets = json_facade.get_step_in_targets(hit.frame_id)
        label_to_id = dict((target["label"], target["id"]) for target in step_in_targets)
        if IS_PY311_OR_GREATER:
            assert set(label_to_id) == {"foo(arg)", "list(gen)"}
            json_facade.write_step_in(hit.thread_id, target_id=label_to_id["foo(arg)"])
        else:
            assert set(label_to_id) == {"foo", "list"}
            json_facade.write_step_in(hit.thread_id, target_id=label_to_id["foo"])

        on_foo_mark_line = writer.get_line_index_with_content("on foo mark")
        hit = json_facade.wait_for_thread_stopped(reason="step", line=on_foo_mark_line)
        json_facade.write_continue()

        writer.finished_ok = True


def test_function_breakpoints_basic(case_setup_dap, pyfile):
    @pyfile
    def module():
        def do_something():  # break here
            print("TEST SUCEEDED")

        if __name__ == "__main__":
            do_something()

    with case_setup_dap.test_file(module) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)
        bp = writer.get_line_index_with_content("break here")
        json_facade.write_set_function_breakpoints(["do_something"])
        json_facade.write_make_initial_run()

        json_facade.wait_for_thread_stopped("function breakpoint", line=bp, preserve_focus_hint=False)
        json_facade.write_continue()

        writer.finished_ok = True


@pytest.mark.skipif(not IS_PY36_OR_GREATER, reason="Python 3.6 onwards required for test.")
def test_function_breakpoints_async(case_setup_dap):
    with case_setup_dap.test_file("_debugger_case_stop_async_iteration.py") as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)
        bp = writer.get_line_index_with_content("async def gen():")
        json_facade.write_set_function_breakpoints(["gen"])
        json_facade.write_make_initial_run()

        json_facade.wait_for_thread_stopped("function breakpoint", line=bp, preserve_focus_hint=False)
        json_facade.write_continue()

        writer.finished_ok = True


try:
    import pandas
except:
    pandas = None


@pytest.mark.skipif(pandas is None, reason="Pandas not installed.")
def test_pandas(case_setup_dap, pyfile):
    @pyfile
    def pandas_mod():
        import pandas as pd
        import numpy as np

        rows = 5000
        cols = 50

        # i.e.: even with these setting our repr will print at most 300 lines/cols by default.
        pd.set_option("display.max_columns", None)
        pd.set_option("display.max_rows", None)

        items = rows * cols
        df = pd.DataFrame(np.arange(items).reshape(rows, cols)).map(lambda x: "Test String")
        series = df._series[0]
        styler = df.style

        print("TEST SUCEEDED")  # Break here

    with case_setup_dap.test_file(pandas_mod) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)

        bp = writer.get_line_index_with_content("Break here")
        json_facade.write_set_breakpoints([bp])

        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        # json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id)
        name_to_var = json_facade.get_locals_name_to_var(json_hit.frame_id)

        # Check the custom repr(DataFrame)
        assert name_to_var["df"].value.count("\n") <= 63
        assert "..." in name_to_var["df"].value

        evaluate_response = json_facade.evaluate("df", json_hit.frame_id, context="repl")
        evaluate_response_body = evaluate_response.body.to_dict()
        assert "..." not in evaluate_response_body["result"]
        assert evaluate_response_body["result"].count("\n") > 4999

        # Check the custom repr(Series)
        assert name_to_var["series"].value.count("\n") <= 60
        assert "..." in name_to_var["series"].value

        # Check custom listing (DataFrame)
        df_variables_response = json_facade.get_variables_response(name_to_var["df"].variablesReference)
        for v in df_variables_response.body.variables:
            if v["name"] == "T":
                assert v["value"] == "'<transposed dataframe -- debugger:skipped eval>'"
                break
        else:
            raise AssertionError('Did not find variable "T".')

        # Check custom listing (Series)
        df_variables_response = json_facade.get_variables_response(name_to_var["series"].variablesReference)
        for v in df_variables_response.body.variables:
            if v["name"] == "T":
                assert v["value"] == "'<transposed dataframe -- debugger:skipped eval>'"
                break
        else:
            raise AssertionError('Did not find variable "T".')

        # Check custom listing (Styler)
        df_variables_response = json_facade.get_variables_response(name_to_var["styler"].variablesReference)
        for v in df_variables_response.body.variables:
            if v["name"] == "data":
                assert v["value"] == "'<Styler data -- debugger:skipped eval>'"
                break
        else:
            raise AssertionError('Did not find variable "data".')

        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.skipif(not IS_PY38_OR_GREATER, reason="Python 3.8 onwards required for test.")
def test_same_lineno_and_filename(case_setup_dap, pyfile):
    @pyfile
    def target():
        def some_code():
            print("1")  # Break here

        code_obj = compile(
            """
        func()
        """,
            __file__,
            "exec",
        )

        code_obj = code_obj.replace(co_name=some_code.__code__.co_name, co_firstlineno=some_code.__code__.co_firstlineno)
        exec(code_obj, {"func": some_code})

        print("TEST SUCEEDED")

    with case_setup_dap.test_file(target) as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"))
        json_facade.write_launch(justMyCode=False)
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        json_facade.write_continue()

        if sys.version_info[:2] >= (3, 10):
            # On Python 3.10 we'll stop twice in this specific case
            # because the line actually matches in the caller (so
            # this is correct based on what the debugger is seeing...)
            json_hit = json_facade.wait_for_thread_stopped()
            json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.skipif(sys.platform == "win32", reason="Windows does not have execvp.")
def test_replace_process(case_setup_multiprocessing_dap):
    import threading
    from tests_python.debugger_unittest import AbstractWriterThread
    from _pydevd_bundle._debug_adapter.pydevd_schema import ExitedEvent

    with case_setup_multiprocessing_dap.test_file(
        "_debugger_case_replace_process.py",
    ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch()

        break1_line = writer.get_line_index_with_content("print('In sub')")
        json_facade.write_set_breakpoints([break1_line])

        server_socket = writer.server_socket
        secondary_finished_ok = [False]

        class SecondaryProcessWriterThread(AbstractWriterThread):
            TEST_FILE = writer.get_main_filename()
            _sequence = -1

        class SecondaryProcessThreadCommunication(threading.Thread):
            def run(self):
                from tests_python.debugger_unittest import ReaderThread

                server_socket.listen(1)
                self.server_socket = server_socket
                new_sock, addr = server_socket.accept()

                reader_thread = ReaderThread(new_sock)
                reader_thread.name = "  *** Multiprocess Reader Thread"
                reader_thread.start()

                writer2 = SecondaryProcessWriterThread()
                writer2.reader_thread = reader_thread
                writer2.sock = new_sock
                json_facade2 = JsonFacade(writer2)

                json_facade2.write_set_breakpoints(
                    [
                        break1_line,
                    ]
                )
                json_facade2.write_make_initial_run()

                json_facade2.wait_for_thread_stopped()
                json_facade2.write_continue()
                secondary_finished_ok[0] = True

        secondary_process_thread_communication = SecondaryProcessThreadCommunication()
        secondary_process_thread_communication.start()
        time.sleep(0.1)

        json_facade.write_make_initial_run()
        exited_event = json_facade.wait_for_json_message(ExitedEvent)
        assert exited_event.body.kwargs["pydevdReason"] == "processReplaced"

        secondary_process_thread_communication.join(10)
        if secondary_process_thread_communication.is_alive():
            raise AssertionError("The SecondaryProcessThreadCommunication did not finish")

        assert secondary_finished_ok[0]
        writer.finished_ok = True


@pytest.mark.parametrize("resolve_symlinks", [True, False])
def test_use_real_path_and_not_links(case_setup_dap, tmpdir, resolve_symlinks):
    dira = tmpdir.join("dira")
    dira.mkdir()

    dirb = tmpdir.join("dirb")
    dirb.mkdir()

    original_file = dira.join("test.py")
    original_file.write(
        """
print('p1')  # Break here
print('p2')
print('TEST SUCEEDED')
"""
    )

    symlinked_file = dirb.join("testit.py")
    os.symlink(str(original_file), str(symlinked_file))

    # I.e.: we're launching the symlinked file but we're actually
    # working with the original file afterwards.
    with case_setup_dap.test_file(str(symlinked_file)) as writer:
        json_facade = JsonFacade(writer)

        writer.write_add_breakpoint(writer.get_line_index_with_content("Break here"), filename=str(original_file))
        json_facade.write_launch(justMyCode=False, resolveSymlinks=resolve_symlinks)
        json_facade.write_make_initial_run()

        json_hit = json_facade.wait_for_thread_stopped()
        filename = json_hit.stack_trace_response.body.stackFrames[0]["source"]["path"]
        if resolve_symlinks:
            assert filename == str(original_file)
        else:
            assert filename == str(symlinked_file)
        json_facade.write_continue()
        writer.finished_ok = True


_TOP_LEVEL_AWAIT_AVAILABLE = False
try:
    from ast import PyCF_ONLY_AST, PyCF_ALLOW_TOP_LEVEL_AWAIT

    _TOP_LEVEL_AWAIT_AVAILABLE = True
except ImportError:
    pass


@pytest.mark.skipif(not _TOP_LEVEL_AWAIT_AVAILABLE, reason="Top-level await required.")
def test_ipython_stepping_basic(case_setup_dap):
    def get_environ(self):
        env = os.environ.copy()

        # Test setup
        env["SCOPED_STEPPING_TARGET"] = "_debugger_case_scoped_stepping_target.py"

        # Actually setup the debugging
        env["PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING"] = "1"
        env["PYDEVD_IPYTHON_CONTEXT"] = "_debugger_case_scoped_stepping.py, run_code, run_ast_nodes"
        return env

    with case_setup_dap.test_file("_debugger_case_scoped_stepping.py", get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)

        target_file = debugger_unittest._get_debugger_test_file("_debugger_case_scoped_stepping_target.py")
        break_line = writer.get_line_index_with_content("a = 1", filename=target_file)
        assert break_line == 1
        json_facade.write_set_breakpoints(break_line, filename=target_file)
        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped(line=break_line, file="_debugger_case_scoped_stepping_target.py")

        json_facade.write_step_next(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", line=break_line + 1, file="_debugger_case_scoped_stepping_target.py")

        json_facade.write_step_next(json_hit.thread_id)
        json_hit = json_facade.wait_for_thread_stopped("step", line=break_line + 2, file="_debugger_case_scoped_stepping_target.py")

        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.skipif(not _TOP_LEVEL_AWAIT_AVAILABLE, reason="Top-level await required.")
def test_ipython_stepping_step_in(case_setup_dap):
    def get_environ(self):
        env = os.environ.copy()

        # Test setup
        env["SCOPED_STEPPING_TARGET"] = "_debugger_case_scoped_stepping_target2.py"

        # Actually setup the debugging
        env["PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING"] = "1"
        env["PYDEVD_IPYTHON_CONTEXT"] = "_debugger_case_scoped_stepping.py, run_code, run_ast_nodes"
        return env

    with case_setup_dap.test_file("_debugger_case_scoped_stepping.py", get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=False)

        target_file = debugger_unittest._get_debugger_test_file("_debugger_case_scoped_stepping_target2.py")
        break_line = writer.get_line_index_with_content("break here", filename=target_file)
        json_facade.write_set_breakpoints(break_line, filename=target_file)
        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped(line=break_line, file="_debugger_case_scoped_stepping_target2.py")

        json_facade.write_step_in(json_hit.thread_id)
        stop_at = writer.get_line_index_with_content("b = 2", filename=target_file)
        json_hit = json_facade.wait_for_thread_stopped("step", line=stop_at, file="_debugger_case_scoped_stepping_target2.py")

        json_facade.write_step_in(json_hit.thread_id)
        stop_at = writer.get_line_index_with_content("method()  # break here", filename=target_file)
        json_hit = json_facade.wait_for_thread_stopped("step", line=stop_at, file="_debugger_case_scoped_stepping_target2.py")

        json_facade.write_step_in(json_hit.thread_id)
        stop_at = writer.get_line_index_with_content("c = 3", filename=target_file)
        json_hit = json_facade.wait_for_thread_stopped("step", line=stop_at, file="_debugger_case_scoped_stepping_target2.py")

        json_facade.write_continue()
        writer.finished_ok = True


@pytest.mark.skipif(not _TOP_LEVEL_AWAIT_AVAILABLE, reason="Top-level await required.")
def test_ipython_stepping_step_in_justmycode(case_setup_dap):
    def get_environ(self):
        env = os.environ.copy()

        # Test setup
        env["SCOPED_STEPPING_TARGET"] = "_debugger_case_scoped_stepping_print.py"

        # Actually setup the debugging
        env["PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING"] = "1"
        env["PYDEVD_IPYTHON_CONTEXT"] = "_debugger_case_scoped_stepping.py, run_code, run_ast_nodes"
        return env

    with case_setup_dap.test_file("_debugger_case_scoped_stepping.py", get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(justMyCode=True)

        target_file = debugger_unittest._get_debugger_test_file("_debugger_case_scoped_stepping_print.py")
        break_line = writer.get_line_index_with_content("break here", filename=target_file)
        json_facade.write_set_breakpoints(break_line, filename=target_file)
        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped(line=break_line, file="_debugger_case_scoped_stepping_print.py")

        json_facade.write_step_in(json_hit.thread_id)
        stop_at = writer.get_line_index_with_content("pause 1", filename=target_file)
        json_hit = json_facade.wait_for_thread_stopped("step", line=stop_at, file="_debugger_case_scoped_stepping_print.py")

        json_facade.write_step_in(json_hit.thread_id)
        stop_at = writer.get_line_index_with_content("pause 2", filename=target_file)
        json_hit = json_facade.wait_for_thread_stopped("step", line=stop_at, file="_debugger_case_scoped_stepping_print.py")

        json_facade.write_step_in(json_hit.thread_id)
        stop_at = writer.get_line_index_with_content("pause 3", filename=target_file)
        json_hit = json_facade.wait_for_thread_stopped("step", line=stop_at, file="_debugger_case_scoped_stepping_print.py")

        json_facade.write_continue()
        writer.finished_ok = True


def test_logging_api(case_setup_multiprocessing_dap, tmpdir):
    import threading
    from tests_python.debugger_unittest import AbstractWriterThread

    log_file = str(tmpdir.join("pydevd_in_test_logging.log"))

    def get_environ(self):
        env = os.environ.copy()
        env["TARGET_LOG_FILE"] = log_file
        return env

    with case_setup_multiprocessing_dap.test_file("_debugger_case_logging.py", get_environ=get_environ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch()

        break1_line = writer.get_line_index_with_content("break on 2nd process")
        json_facade.write_set_breakpoints([break1_line])

        server_socket = writer.server_socket
        secondary_finished_ok = [False]

        class SecondaryProcessWriterThread(AbstractWriterThread):
            TEST_FILE = writer.get_main_filename()
            _sequence = -1

        class SecondaryProcessThreadCommunication(threading.Thread):
            def run(self):
                from tests_python.debugger_unittest import ReaderThread

                server_socket.listen(1)
                self.server_socket = server_socket
                new_sock, addr = server_socket.accept()

                reader_thread = ReaderThread(new_sock)
                reader_thread.name = "  *** Multiprocess Reader Thread"
                reader_thread.start()

                writer2 = SecondaryProcessWriterThread()
                writer2.reader_thread = reader_thread
                writer2.sock = new_sock
                json_facade2 = JsonFacade(writer2)

                json_facade2.write_set_breakpoints(
                    [
                        break1_line,
                    ]
                )
                json_facade2.write_make_initial_run()

                json_facade2.wait_for_thread_stopped()
                json_facade2.write_continue()
                secondary_finished_ok[0] = True

        secondary_process_thread_communication = SecondaryProcessThreadCommunication()
        secondary_process_thread_communication.start()
        time.sleep(0.1)

        json_facade.write_make_initial_run()
        secondary_process_thread_communication.join(10)
        if secondary_process_thread_communication.is_alive():
            raise AssertionError("The SecondaryProcessThreadCommunication did not finish")

        assert secondary_finished_ok[0]
        writer.finished_ok = True


@pytest.mark.parametrize("soft_kill", [False, True])
def test_soft_terminate(case_setup_dap, pyfile, soft_kill):
    if soft_kill and PYDEVD_USE_SYS_MONITORING:
        pytest.skip("Right now when using sys.monitoring exceptions are be handled in callbacks.")

    @pyfile
    def target():
        import time

        try:
            while True:
                time.sleep(0.2)  # break here
        except KeyboardInterrupt:
            # i.e.: The test succeeds if a keyboard interrupt is received.
            print("TEST SUCEEDED!")
            raise

    def check_test_suceeded_msg(self, stdout, stderr):
        if soft_kill:
            return "TEST SUCEEDED" in "".join(stdout)
        else:
            return "TEST SUCEEDED" not in "".join(stdout)

    def additional_output_checks(writer, stdout, stderr):
        if soft_kill:
            assert "KeyboardInterrupt" in stderr
        else:
            assert not stderr

    with case_setup_dap.test_file(
        target,
        EXPECTED_RETURNCODE="any",
        check_test_suceeded_msg=check_test_suceeded_msg,
        additional_output_checks=additional_output_checks,
    ) as writer:
        json_facade = JsonFacade(writer)
        json_facade.write_launch(onTerminate="KeyboardInterrupt" if soft_kill else "kill", justMyCode=False)

        break_line = writer.get_line_index_with_content("break here")
        json_facade.write_set_breakpoints(break_line)
        json_facade.write_make_initial_run()
        json_hit = json_facade.wait_for_thread_stopped(line=break_line)

        # Interrupting when inside a breakpoint will actually make the
        # debugger stop working in that thread (because there's no way
        # to keep debugging after an exception exits the tracing).

        json_facade.write_terminate()

        if soft_kill:
            json_facade.wait_for_json_message(
                OutputEvent, lambda output_event: "raised from within the callback set" in output_event.body.output
            )

        writer.finished_ok = True


if __name__ == "__main__":
    pytest.main(["-k", "test_replace_process", "-s"])