File: test_completer.py

package info (click to toggle)
ipython 9.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 8,624 kB
  • sloc: python: 45,268; sh: 317; makefile: 168
file content (2872 lines) | stat: -rw-r--r-- 95,927 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
# encoding: utf-8
"""Tests for the IPython tab-completion machinery."""

# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.

import os
import pytest
import sys
import textwrap
import types
import unittest
import random

from importlib.metadata import version

from contextlib import contextmanager

from traitlets.config.loader import Config
from IPython import get_ipython
from IPython.core import completer
from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
from IPython.utils.generics import complete_object
from IPython.testing import decorators as dec
from IPython.core.latex_symbols import latex_symbols

from IPython.core.completer import (
    Completion,
    provisionalcompleter,
    match_dict_keys,
    _deduplicate_completions,
    _match_number_in_dict_key_prefix,
    completion_matcher,
    SimpleCompletion,
    CompletionContext,
    _unicode_name_compute,
    _UNICODE_RANGES,
)

from packaging.version import parse


@contextmanager
def jedi_status(status: bool):
    completer = get_ipython().Completer
    try:
        old = completer.use_jedi
        completer.use_jedi = status
        yield
    finally:
        completer.use_jedi = old


# -----------------------------------------------------------------------------
# Test functions
# -----------------------------------------------------------------------------


def recompute_unicode_ranges():
    """
    utility to recompute the largest unicode range without any characters

    use to recompute the gap in the global _UNICODE_RANGES of completer.py
    """
    import itertools
    import unicodedata

    valid = []
    for c in range(0, 0x10FFFF + 1):
        try:
            unicodedata.name(chr(c))
        except ValueError:
            continue
        valid.append(c)

    def ranges(i):
        for a, b in itertools.groupby(enumerate(i), lambda pair: pair[1] - pair[0]):
            b = list(b)
            yield b[0][1], b[-1][1]

    rg = list(ranges(valid))
    lens = []
    gap_lens = []
    _pstart, pstop = 0, 0
    for start, stop in rg:
        lens.append(stop - start)
        gap_lens.append(
            (
                start - pstop,
                hex(pstop + 1),
                hex(start),
                f"{round((start - pstop)/0xe01f0*100)}%",
            )
        )
        _pstart, pstop = start, stop

    return sorted(gap_lens)[-1]


def test_unicode_range():
    """
    Test that the ranges we test for unicode names give the same number of
    results than testing the full length.
    """

    expected_list = _unicode_name_compute([(0, 0x110000)])
    test = _unicode_name_compute(_UNICODE_RANGES)
    len_exp = len(expected_list)
    len_test = len(test)

    # do not inline the len() or on error pytest will try to print the 130 000 +
    # elements.
    message = None
    if len_exp != len_test or len_exp > 131808:
        size, start, stop, prct = recompute_unicode_ranges()
        message = f"""_UNICODE_RANGES likely wrong and need updating. This is
        likely due to a new release of Python. We've find that the biggest gap
        in unicode characters has reduces in size to be {size} characters
        ({prct}), from {start}, to {stop}. In completer.py likely update to

            _UNICODE_RANGES = [(32, {start}), ({stop}, 0xe01f0)]

        And update the assertion below to use

            len_exp <= {len_exp}
        """
    assert len_exp == len_test, message

    # fail if new unicode symbols have been added.
    assert len_exp <= 148853, message


@contextmanager
def greedy_completion():
    ip = get_ipython()
    greedy_original = ip.Completer.greedy
    try:
        ip.Completer.greedy = True
        yield
    finally:
        ip.Completer.greedy = greedy_original


@contextmanager
def evaluation_policy(evaluation: str, **overrides):
    ip = get_ipython()
    evaluation_original = ip.Completer.evaluation
    overrides_original = ip.Completer.policy_overrides
    try:
        ip.Completer.evaluation = evaluation
        ip.Completer.policy_overrides = overrides
        yield
    finally:
        ip.Completer.evaluation = evaluation_original
        ip.Completer.policy_overrides = overrides_original


@contextmanager
def custom_matchers(matchers):
    ip = get_ipython()
    try:
        ip.Completer.custom_matchers.extend(matchers)
        yield
    finally:
        ip.Completer.custom_matchers.clear()


if sys.platform == "win32":
    pairs = [
        ("abc", "abc"),
        (" abc", '" abc"'),
        ("a bc", '"a bc"'),
        ("a  bc", '"a  bc"'),
        ("  bc", '"  bc"'),
    ]
else:
    pairs = [
        ("abc", "abc"),
        (" abc", r"\ abc"),
        ("a bc", r"a\ bc"),
        ("a  bc", r"a\ \ bc"),
        ("  bc", r"\ \ bc"),
        # On posix, we also protect parens and other special characters.
        ("a(bc", r"a\(bc"),
        ("a)bc", r"a\)bc"),
        ("a( )bc", r"a\(\ \)bc"),
        ("a[1]bc", r"a\[1\]bc"),
        ("a{1}bc", r"a\{1\}bc"),
        ("a#bc", r"a\#bc"),
        ("a?bc", r"a\?bc"),
        ("a=bc", r"a\=bc"),
        ("a\\bc", r"a\\bc"),
        ("a|bc", r"a\|bc"),
        ("a;bc", r"a\;bc"),
        ("a:bc", r"a\:bc"),
        ("a'bc", r"a\'bc"),
        ("a*bc", r"a\*bc"),
        ('a"bc', r"a\"bc"),
        ("a^bc", r"a\^bc"),
        ("a&bc", r"a\&bc"),
    ]


@pytest.mark.parametrize("s1,expected", pairs)
def test_protect_filename(s1, expected):
    assert completer.protect_filename(s1) == expected


def check_line_split(splitter, test_specs):
    for part1, part2, split in test_specs:
        cursor_pos = len(part1)
        line = part1 + part2
        out = splitter.split_line(line, cursor_pos)
        assert out == split


def test_line_split():
    """Basic line splitter test with default specs."""
    sp = completer.CompletionSplitter()
    # The format of the test specs is: part1, part2, expected answer.  Parts 1
    # and 2 are joined into the 'line' sent to the splitter, as if the cursor
    # was at the end of part1.  So an empty part2 represents someone hitting
    # tab at the end of the line, the most common case.
    t = [
        ("run some/script", "", "some/script"),
        ("run scripts/er", "ror.py foo", "scripts/er"),
        ("echo $HOM", "", "HOM"),
        ("print sys.pa", "", "sys.pa"),
        ("print(sys.pa", "", "sys.pa"),
        ("execfile('scripts/er", "", "scripts/er"),
        ("a[x.", "", "x."),
        ("a[x.", "y", "x."),
        ('cd "some_file/', "", "some_file/"),
    ]
    check_line_split(sp, t)
    # Ensure splitting works OK with unicode by re-running the tests with
    # all inputs turned into unicode
    check_line_split(sp, [map(str, p) for p in t])


class NamedInstanceClass:
    instances = {}

    def __init__(self, name):
        self.instances[name] = self

    @classmethod
    def _ipython_key_completions_(cls):
        return cls.instances.keys()


class KeyCompletable:
    def __init__(self, things=()):
        self.things = things

    def _ipython_key_completions_(self):
        return list(self.things)


class TestCompleter(unittest.TestCase):
    def setUp(self):
        """
        We want to silence all PendingDeprecationWarning when testing the completer
        """
        self._assertwarns = self.assertWarns(PendingDeprecationWarning)
        self._assertwarns.__enter__()

    def tearDown(self):
        try:
            self._assertwarns.__exit__(None, None, None)
        except AssertionError:
            pass

    def test_custom_completion_error(self):
        """Test that errors from custom attribute completers are silenced."""
        ip = get_ipython()

        class A:
            pass

        ip.user_ns["x"] = A()

        @complete_object.register(A)
        def complete_A(a, existing_completions):
            raise TypeError("this should be silenced")

        ip.complete("x.")

    def test_custom_completion_ordering(self):
        """Test that errors from custom attribute completers are silenced."""
        ip = get_ipython()

        _, matches = ip.complete("in")
        assert matches.index("input") < matches.index("int")

        def complete_example(a):
            return ["example2", "example1"]

        ip.Completer.custom_completers.add_re("ex*", complete_example)
        _, matches = ip.complete("ex")
        assert matches.index("example2") < matches.index("example1")

    def test_unicode_completions(self):
        ip = get_ipython()
        # Some strings that trigger different types of completion.  Check them both
        # in str and unicode forms
        s = ["ru", "%ru", "cd /", "floa", "float(x)/"]
        for t in s + list(map(str, s)):
            # We don't need to check exact completion values (they may change
            # depending on the state of the namespace, but at least no exceptions
            # should be thrown and the return value should be a pair of text, list
            # values.
            text, matches = ip.complete(t)
            self.assertIsInstance(text, str)
            self.assertIsInstance(matches, list)

    def test_latex_completions(self):
        ip = get_ipython()
        # Test some random unicode symbols
        keys = random.sample(sorted(latex_symbols), 10)
        for k in keys:
            text, matches = ip.complete(k)
            self.assertEqual(text, k)
            self.assertEqual(matches, [latex_symbols[k]])
        # Test a more complex line
        text, matches = ip.complete("print(\\alpha")
        self.assertEqual(text, "\\alpha")
        self.assertEqual(matches[0], latex_symbols["\\alpha"])
        # Test multiple matching latex symbols
        text, matches = ip.complete("\\al")
        self.assertIn("\\alpha", matches)
        self.assertIn("\\aleph", matches)

    def test_latex_no_results(self):
        """
        forward latex should really return nothing in either field if nothing is found.
        """
        ip = get_ipython()
        text, matches = ip.Completer.latex_matches("\\really_i_should_match_nothing")
        self.assertEqual(text, "")
        self.assertEqual(matches, ())

    def test_back_latex_completion(self):
        ip = get_ipython()

        # do not return more than 1 matches for \beta, only the latex one.
        name, matches = ip.complete("\\β")
        self.assertEqual(matches, ["\\beta"])

    def test_back_unicode_completion(self):
        ip = get_ipython()

        name, matches = ip.complete("\\â…¤")
        self.assertEqual(matches, ["\\ROMAN NUMERAL FIVE"])

    def test_forward_unicode_completion(self):
        ip = get_ipython()

        name, matches = ip.complete("\\ROMAN NUMERAL FIVE")
        self.assertEqual(matches, ["â…¤"])  # This is not a V
        self.assertEqual(matches, ["\u2164"])  # same as above but explicit.

    def test_delim_setting(self):
        sp = completer.CompletionSplitter()
        sp.delims = " "
        self.assertEqual(sp.delims, " ")
        self.assertEqual(sp._delim_expr, r"[\ ]")

    def test_spaces(self):
        """Test with only spaces as split chars."""
        sp = completer.CompletionSplitter()
        sp.delims = " "
        t = [("foo", "", "foo"), ("run foo", "", "foo"), ("run foo", "bar", "foo")]
        check_line_split(sp, t)

    def test_has_open_quotes1(self):
        for s in ["'", "'''", "'hi' '"]:
            self.assertEqual(completer.has_open_quotes(s), "'")

    def test_has_open_quotes2(self):
        for s in ['"', '"""', '"hi" "']:
            self.assertEqual(completer.has_open_quotes(s), '"')

    def test_has_open_quotes3(self):
        for s in ["''", "''' '''", "'hi' 'ipython'"]:
            self.assertFalse(completer.has_open_quotes(s))

    def test_has_open_quotes4(self):
        for s in ['""', '""" """', '"hi" "ipython"']:
            self.assertFalse(completer.has_open_quotes(s))

    @pytest.mark.xfail(
        sys.platform == "win32", reason="abspath completions fail on Windows"
    )
    def test_abspath_file_completions(self):
        ip = get_ipython()
        with TemporaryDirectory() as tmpdir:
            prefix = os.path.join(tmpdir, "foo")
            suffixes = ["1", "2"]
            names = [prefix + s for s in suffixes]
            for n in names:
                open(n, "w", encoding="utf-8").close()

            # Check simple completion
            c = ip.complete(prefix)[1]
            self.assertEqual(c, names)

            # Now check with a function call
            cmd = 'a = f("%s' % prefix
            c = ip.complete(prefix, cmd)[1]
            comp = [prefix + s for s in suffixes]
            self.assertEqual(c, comp)

    def test_local_file_completions(self):
        ip = get_ipython()
        with TemporaryWorkingDirectory():
            prefix = "./foo"
            suffixes = ["1", "2"]
            names = [prefix + s for s in suffixes]
            for n in names:
                open(n, "w", encoding="utf-8").close()

            # Check simple completion
            c = ip.complete(prefix)[1]
            self.assertEqual(c, names)

            test_cases = {
                "function call": 'a = f("',
                "shell bang": "!ls ",
                "ls magic": r"%ls ",
                "alias ls": "ls ",
            }
            for name, code in test_cases.items():
                cmd = f"{code}{prefix}"
                c = ip.complete(prefix, cmd)[1]
                comp = {prefix + s for s in suffixes}
                self.assertTrue(comp.issubset(set(c)), msg=f"completes in {name}")

    def test_quoted_file_completions(self):
        ip = get_ipython()

        def _(text):
            return ip.Completer._complete(
                cursor_line=0, cursor_pos=len(text), full_text=text
            )["IPCompleter.file_matcher"]["completions"]

        with TemporaryWorkingDirectory():
            name = "foo'bar"
            open(name, "w", encoding="utf-8").close()

            # Don't escape Windows
            escaped = name if sys.platform == "win32" else "foo\\'bar"

            # Single quote matches embedded single quote
            c = _("open('foo")[0]
            self.assertEqual(c.text, escaped)

            # Double quote requires no escape
            c = _('open("foo')[0]
            self.assertEqual(c.text, name)

            # No quote requires an escape
            c = _("%ls foo")[0]
            self.assertEqual(c.text, escaped)

    @pytest.mark.xfail(
        sys.version_info.releaselevel in ("alpha",),
        reason="Parso does not yet parse 3.13",
    )
    def test_all_completions_dups(self):
        """
        Make sure the output of `IPCompleter.all_completions` does not have
        duplicated prefixes.
        """
        ip = get_ipython()
        c = ip.Completer
        ip.ex("class TestClass():\n\ta=1\n\ta1=2")
        for jedi_status in [True, False]:
            with provisionalcompleter():
                ip.Completer.use_jedi = jedi_status
                matches = c.all_completions("TestCl")
                assert matches == ["TestClass"], (jedi_status, matches)
                matches = c.all_completions("TestClass.")
                assert len(matches) > 2, (jedi_status, matches)
                matches = c.all_completions("TestClass.a")
                if jedi_status:
                    assert matches == ["TestClass.a", "TestClass.a1"], jedi_status
                else:
                    assert matches == [".a", ".a1"], jedi_status

    @pytest.mark.xfail(
        sys.version_info.releaselevel in ("alpha",),
        reason="Parso does not yet parse 3.13",
    )
    def test_jedi(self):
        """
        A couple of issue we had with Jedi
        """
        ip = get_ipython()

        def _test_complete(reason, s, comp, start=None, end=None):
            l = len(s)
            start = start if start is not None else l
            end = end if end is not None else l
            with provisionalcompleter():
                ip.Completer.use_jedi = True
                completions = set(ip.Completer.completions(s, l))
                ip.Completer.use_jedi = False
                assert Completion(start, end, comp) in completions, reason

        def _test_not_complete(reason, s, comp):
            l = len(s)
            with provisionalcompleter():
                ip.Completer.use_jedi = True
                completions = set(ip.Completer.completions(s, l))
                ip.Completer.use_jedi = False
                assert Completion(l, l, comp) not in completions, reason

        import jedi

        jedi_version = tuple(int(i) for i in jedi.__version__.split(".")[:3])
        if jedi_version > (0, 10):
            _test_complete("jedi >0.9 should complete and not crash", "a=1;a.", "real")
        _test_complete("can infer first argument", 'a=(1,"foo");a[0].', "real")
        _test_complete("can infer second argument", 'a=(1,"foo");a[1].', "capitalize")
        _test_complete("cover duplicate completions", "im", "import", 0, 2)

        _test_not_complete("does not mix types", 'a=(1,"foo");a[0].', "capitalize")

    @pytest.mark.xfail(
        sys.version_info.releaselevel in ("alpha",),
        reason="Parso does not yet parse 3.13",
    )
    def test_completion_have_signature(self):
        """
        Lets make sure jedi is capable of pulling out the signature of the function we are completing.
        """
        ip = get_ipython()
        with provisionalcompleter():
            ip.Completer.use_jedi = True
            completions = ip.Completer.completions("ope", 3)
            c = next(completions)  # should be `open`
            ip.Completer.use_jedi = False
        assert "file" in c.signature, "Signature of function was not found by completer"
        assert (
            "encoding" in c.signature
        ), "Signature of function was not found by completer"

    @pytest.mark.xfail(
        sys.version_info.releaselevel in ("alpha",),
        reason="Parso does not yet parse 3.13",
    )
    def test_completions_have_type(self):
        """
        Lets make sure matchers provide completion type.
        """
        ip = get_ipython()
        with provisionalcompleter():
            ip.Completer.use_jedi = False
            completions = ip.Completer.completions("%tim", 3)
            c = next(completions)  # should be `%time` or similar
        assert c.type == "magic", "Type of magic was not assigned by completer"

    @pytest.mark.xfail(
        parse(version("jedi")) <= parse("0.18.0"),
        reason="Known failure on jedi<=0.18.0",
        strict=True,
    )
    def test_deduplicate_completions(self):
        """
        Test that completions are correctly deduplicated (even if ranges are not the same)
        """
        ip = get_ipython()
        ip.ex(
            textwrap.dedent(
                """
        class Z:
            zoo = 1
        """
            )
        )
        with provisionalcompleter():
            ip.Completer.use_jedi = True
            l = list(
                _deduplicate_completions("Z.z", ip.Completer.completions("Z.z", 3))
            )
            ip.Completer.use_jedi = False

        assert len(l) == 1, "Completions (Z.z<tab>) correctly deduplicate: %s " % l
        assert l[0].text == "zoo"  # and not `it.accumulate`

    @pytest.mark.xfail(
        sys.version_info.releaselevel in ("alpha",),
        reason="Parso does not yet parse 3.13",
    )
    def test_greedy_completions(self):
        """
        Test the capability of the Greedy completer.

        Most of the test here does not really show off the greedy completer, for proof
        each of the text below now pass with Jedi. The greedy completer is capable of more.

        See the :any:`test_dict_key_completion_contexts`

        """
        ip = get_ipython()
        ip.ex("a=list(range(5))")
        ip.ex("b,c = 1, 1.2")
        ip.ex("d = {'a b': str}")
        ip.ex("x=y='a'")
        _, c = ip.complete(".", line="a[0].")
        self.assertFalse(".real" in c, "Shouldn't have completed on a[0]: %s" % c)

        def _(line, cursor_pos, expect, message, completion):
            with greedy_completion(), provisionalcompleter():
                ip.Completer.use_jedi = False
                _, c = ip.complete(".", line=line, cursor_pos=cursor_pos)
                self.assertIn(expect, c, message % c)

                ip.Completer.use_jedi = True
                with provisionalcompleter():
                    completions = ip.Completer.completions(line, cursor_pos)
                self.assertIn(completion, list(completions))

        with provisionalcompleter():
            _(
                "a[0].",
                5,
                ".real",
                "Should have completed on a[0].: %s",
                Completion(5, 5, "real"),
            )
            _(
                "a[0].r",
                6,
                ".real",
                "Should have completed on a[0].r: %s",
                Completion(5, 6, "real"),
            )
            _(
                "a[0].from_",
                10,
                ".from_bytes",
                "Should have completed on a[0].from_: %s",
                Completion(5, 10, "from_bytes"),
            )
            _(
                "assert str.star",
                14,
                ".startswith",
                "Should have completed on `assert str.star`: %s",
                Completion(11, 14, "startswith"),
            )
            _(
                "d['a b'].str",
                12,
                ".strip",
                "Should have completed on `d['a b'].str`: %s",
                Completion(9, 12, "strip"),
            )
            _(
                "a.app",
                4,
                ".append",
                "Should have completed on `a.app`: %s",
                Completion(2, 4, "append"),
            )
            _(
                "x.upper() == y.",
                15,
                ".upper",
                "Should have completed on `x.upper() == y.`: %s",
                Completion(15, 15, "upper"),
            )
            _(
                "(x.upper() == y.",
                16,
                ".upper",
                "Should have completed on `(x.upper() == y.`: %s",
                Completion(16, 16, "upper"),
            )
            _(
                "(x.upper() == y).",
                17,
                ".bit_length",
                "Should have completed on `(x.upper() == y).`: %s",
                Completion(17, 17, "bit_length"),
            )
            _(
                "{'==', 'abc'}.",
                14,
                ".add",
                "Should have completed on `{'==', 'abc'}.`: %s",
                Completion(14, 14, "add"),
            )
            _(
                "b + c.",
                6,
                ".hex",
                "Should have completed on `b + c.`: %s",
                Completion(6, 6, "hex"),
            )

    def test_omit__names(self):
        # also happens to test IPCompleter as a configurable
        ip = get_ipython()
        ip._hidden_attr = 1
        ip._x = {}
        c = ip.Completer
        ip.ex("ip=get_ipython()")
        cfg = Config()
        cfg.IPCompleter.omit__names = 0
        c.update_config(cfg)
        with provisionalcompleter():
            c.use_jedi = False
            s, matches = c.complete("ip.")
            self.assertIn(".__str__", matches)
            self.assertIn("._hidden_attr", matches)

            # c.use_jedi = True
            # completions = set(c.completions('ip.', 3))
            # self.assertIn(Completion(3, 3, '__str__'), completions)
            # self.assertIn(Completion(3,3, "_hidden_attr"), completions)

        cfg = Config()
        cfg.IPCompleter.omit__names = 1
        c.update_config(cfg)
        with provisionalcompleter():
            c.use_jedi = False
            s, matches = c.complete("ip.")
            self.assertNotIn(".__str__", matches)
            # self.assertIn('ip._hidden_attr', matches)

            # c.use_jedi = True
            # completions = set(c.completions('ip.', 3))
            # self.assertNotIn(Completion(3,3,'__str__'), completions)
            # self.assertIn(Completion(3,3, "_hidden_attr"), completions)

        cfg = Config()
        cfg.IPCompleter.omit__names = 2
        c.update_config(cfg)
        with provisionalcompleter():
            c.use_jedi = False
            s, matches = c.complete("ip.")
            self.assertNotIn(".__str__", matches)
            self.assertNotIn("._hidden_attr", matches)

            # c.use_jedi = True
            # completions = set(c.completions('ip.', 3))
            # self.assertNotIn(Completion(3,3,'__str__'), completions)
            # self.assertNotIn(Completion(3,3, "_hidden_attr"), completions)

        with provisionalcompleter():
            c.use_jedi = False
            s, matches = c.complete("ip._x.")
            self.assertIn(".keys", matches)

            # c.use_jedi = True
            # completions = set(c.completions('ip._x.', 6))
            # self.assertIn(Completion(6,6, "keys"), completions)

        del ip._hidden_attr
        del ip._x

    def test_limit_to__all__False_ok(self):
        """
        Limit to all is deprecated, once we remove it this test can go away.
        """
        ip = get_ipython()
        c = ip.Completer
        c.use_jedi = False
        ip.ex("class D: x=24")
        ip.ex("d=D()")
        cfg = Config()
        cfg.IPCompleter.limit_to__all__ = False
        c.update_config(cfg)
        s, matches = c.complete("d.")
        self.assertIn(".x", matches)

    def test_get__all__entries_ok(self):
        class A:
            __all__ = ["x", 1]

        words = completer.get__all__entries(A())
        self.assertEqual(words, ["x"])

    def test_get__all__entries_no__all__ok(self):
        class A:
            pass

        words = completer.get__all__entries(A())
        self.assertEqual(words, [])

    def test_completes_globals_as_args_of_methods(self):
        ip = get_ipython()
        c = ip.Completer
        c.use_jedi = False
        ip.ex("long_variable_name = 1")
        ip.ex("a = []")
        s, matches = c.complete(None, "a.sort(lo")
        self.assertIn("long_variable_name", matches)

    def test_completes_attributes_in_fstring_expressions(self):
        ip = get_ipython()
        c = ip.Completer
        c.use_jedi = False

        class CustomClass:
            def method_one(self):
                pass

        ip.user_ns["custom_obj"] = CustomClass()

        # Test completion inside f-string expressions
        s, matches = c.complete(None, "f'{custom_obj.meth")
        self.assertIn(".method_one", matches)

    def test_completes_in_dict_expressions(self):
        ip = get_ipython()
        c = ip.Completer
        c.use_jedi = False
        ip.ex("class Test: pass")
        ip.ex("test_obj = Test()")
        ip.ex("test_obj.attribute = 'value'")

        # Test completion in dictionary expressions
        s, matches = c.complete(None, "d = {'key': test_obj.attr")
        self.assertIn(".attribute", matches)

        # Test global completion in dictionary expressions with dots
        s, matches = c.complete(None, "d = {'k.e.y': Te")
        self.assertIn("Test", matches)

    def test_func_kw_completions(self):
        ip = get_ipython()
        c = ip.Completer
        c.use_jedi = False
        ip.ex("def myfunc(a=1,b=2): return a+b")
        s, matches = c.complete(None, "myfunc(1,b")
        self.assertIn("b=", matches)
        # Simulate completing with cursor right after b (pos==10):
        s, matches = c.complete(None, "myfunc(1,b)", 10)
        self.assertIn("b=", matches)
        s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
        self.assertIn("b=", matches)
        # builtin function
        s, matches = c.complete(None, "min(k, k")
        self.assertIn("key=", matches)

    def test_default_arguments_from_docstring(self):
        ip = get_ipython()
        c = ip.Completer
        kwd = c._default_arguments_from_docstring("min(iterable[, key=func]) -> value")
        self.assertEqual(kwd, ["key"])
        # with cython type etc
        kwd = c._default_arguments_from_docstring(
            "Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n"
        )
        self.assertEqual(kwd, ["ncall", "resume", "nsplit"])
        # white spaces
        kwd = c._default_arguments_from_docstring(
            "\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n"
        )
        self.assertEqual(kwd, ["ncall", "resume", "nsplit"])

    def test_line_magics(self):
        ip = get_ipython()
        c = ip.Completer
        s, matches = c.complete(None, "lsmag")
        self.assertIn("%lsmagic", matches)
        s, matches = c.complete(None, "%lsmag")
        self.assertIn("%lsmagic", matches)

    def test_cell_magics(self):
        from IPython.core.magic import register_cell_magic

        @register_cell_magic
        def _foo_cellm(line, cell):
            pass

        ip = get_ipython()
        c = ip.Completer

        s, matches = c.complete(None, "_foo_ce")
        self.assertIn("%%_foo_cellm", matches)
        s, matches = c.complete(None, "%%_foo_ce")
        self.assertIn("%%_foo_cellm", matches)

    def test_line_cell_magics(self):
        from IPython.core.magic import register_line_cell_magic

        @register_line_cell_magic
        def _bar_cellm(line, cell):
            pass

        ip = get_ipython()
        c = ip.Completer

        # The policy here is trickier, see comments in completion code.  The
        # returned values depend on whether the user passes %% or not explicitly,
        # and this will show a difference if the same name is both a line and cell
        # magic.
        s, matches = c.complete(None, "_bar_ce")
        self.assertIn("%_bar_cellm", matches)
        self.assertIn("%%_bar_cellm", matches)
        s, matches = c.complete(None, "%_bar_ce")
        self.assertIn("%_bar_cellm", matches)
        self.assertIn("%%_bar_cellm", matches)
        s, matches = c.complete(None, "%%_bar_ce")
        self.assertNotIn("%_bar_cellm", matches)
        self.assertIn("%%_bar_cellm", matches)

    def test_line_magics_with_code_argument(self):
        ip = get_ipython()
        c = ip.Completer
        c.use_jedi = False

        # attribute completion
        text, matches = c.complete("%timeit -n 2 -r 1 float.as_integer")
        self.assertEqual(matches, [".as_integer_ratio"])

        text, matches = c.complete("%debug --breakpoint test float.as_integer")
        self.assertEqual(matches, [".as_integer_ratio"])

        text, matches = c.complete("%time --no-raise-error float.as_integer")
        self.assertEqual(matches, [".as_integer_ratio"])

        text, matches = c.complete("%prun -l 0.5 -r float.as_integer")
        self.assertEqual(matches, [".as_integer_ratio"])

        # implicit magics
        text, matches = c.complete("timeit -n 2 -r 1 float.as_integer")
        self.assertEqual(matches, [".as_integer_ratio"])

        # built-ins completion
        text, matches = c.complete("%timeit -n 2 -r 1 flo")
        self.assertEqual(matches, ["float"])

        # dict completion
        text, matches = c.complete("%timeit -n 2 -r 1 {'my_key': 1}['my")
        self.assertEqual(matches, ["my_key"])

        # invalid arguments - should not throw
        text, matches = c.complete("%timeit -n 2 -r 1 -invalid float.as_integer")
        self.assertEqual(matches, [])

        text, matches = c.complete("%debug --invalid float.as_integer")
        self.assertEqual(matches, [])

    def test_line_magics_with_code_argument_shadowing(self):
        ip = get_ipython()
        c = ip.Completer
        c.use_jedi = False

        # shadow
        ip.run_cell("timeit = 1")

        # should not suggest on implict magic when shadowed
        text, matches = c.complete("timeit -n 2 -r 1 flo")
        self.assertEqual(matches, [])

        # should suggest on explicit magic
        text, matches = c.complete("%timeit -n 2 -r 1 flo")
        self.assertEqual(matches, ["float"])

        # remove shadow
        del ip.user_ns["timeit"]

        # should suggest on implicit magic after shadow removal
        text, matches = c.complete("timeit -n 2 -r 1 flo")
        self.assertEqual(matches, ["float"])

    def test_magic_completion_order(self):
        ip = get_ipython()
        c = ip.Completer

        # Test ordering of line and cell magics.
        text, matches = c.complete("timeit")
        self.assertEqual(matches, ["%timeit", "%%timeit"])

    def test_magic_completion_shadowing(self):
        ip = get_ipython()
        c = ip.Completer
        c.use_jedi = False

        # Before importing matplotlib, %matplotlib magic should be the only option.
        text, matches = c.complete("mat")
        self.assertEqual(matches, ["%matplotlib"])

        # The newly introduced name should shadow the magic.
        ip.run_cell("matplotlib = 1")
        text, matches = c.complete("mat")
        self.assertEqual(matches, ["matplotlib"])

        # After removing matplotlib from namespace, the magic should again be
        # the only option.
        del ip.user_ns["matplotlib"]
        text, matches = c.complete("mat")
        self.assertEqual(matches, ["%matplotlib"])

    def test_magic_completion_shadowing_explicit(self):
        """
        If the user try to complete a shadowed magic, and explicit % start should
        still return the completions.
        """
        ip = get_ipython()
        c = ip.Completer

        # Before importing matplotlib, %matplotlib magic should be the only option.
        text, matches = c.complete("%mat")
        self.assertEqual(matches, ["%matplotlib"])

        ip.run_cell("matplotlib = 1")

        # After removing matplotlib from namespace, the magic should still be
        # the only option.
        text, matches = c.complete("%mat")
        self.assertEqual(matches, ["%matplotlib"])

    def test_magic_config(self):
        ip = get_ipython()
        c = ip.Completer

        s, matches = c.complete(None, "conf")
        self.assertIn("%config", matches)
        s, matches = c.complete(None, "conf")
        self.assertNotIn("AliasManager", matches)
        s, matches = c.complete(None, "config ")
        self.assertIn("AliasManager", matches)
        s, matches = c.complete(None, "%config ")
        self.assertIn("AliasManager", matches)
        s, matches = c.complete(None, "config Ali")
        self.assertListEqual(["AliasManager"], matches)
        s, matches = c.complete(None, "%config Ali")
        self.assertListEqual(["AliasManager"], matches)
        s, matches = c.complete(None, "config AliasManager")
        self.assertListEqual(["AliasManager"], matches)
        s, matches = c.complete(None, "%config AliasManager")
        self.assertListEqual(["AliasManager"], matches)
        s, matches = c.complete(None, "config AliasManager.")
        self.assertIn("AliasManager.default_aliases", matches)
        s, matches = c.complete(None, "%config AliasManager.")
        self.assertIn("AliasManager.default_aliases", matches)
        s, matches = c.complete(None, "config AliasManager.de")
        self.assertListEqual(["AliasManager.default_aliases"], matches)
        s, matches = c.complete(None, "config AliasManager.de")
        self.assertListEqual(["AliasManager.default_aliases"], matches)

    def test_magic_color(self):
        ip = get_ipython()
        c = ip.Completer

        s, matches = c.complete(None, "colo")
        assert "%colors" in matches
        s, matches = c.complete(None, "colo")
        assert "nocolor" not in matches
        s, matches = c.complete(None, "%colors")  # No trailing space
        assert "nocolor" not in matches
        s, matches = c.complete(None, "colors ")
        assert "nocolor" in matches
        s, matches = c.complete(None, "%colors ")
        assert "nocolor" in matches
        s, matches = c.complete(None, "colors noco")
        assert ["nocolor"] == matches
        s, matches = c.complete(None, "%colors noco")
        assert ["nocolor"] == matches

    def test_match_dict_keys(self):
        """
        Test that match_dict_keys works on a couple of use case does return what
        expected, and does not crash
        """
        delims = " \t\n`!@#$^&*()=+[{]}\\|;:'\",<>?"

        def match(*args, **kwargs):
            quote, offset, matches = match_dict_keys(*args, delims=delims, **kwargs)
            return quote, offset, list(matches)

        keys = ["foo", b"far"]
        assert match(keys, "b'") == ("'", 2, ["far"])
        assert match(keys, "b'f") == ("'", 2, ["far"])
        assert match(keys, 'b"') == ('"', 2, ["far"])
        assert match(keys, 'b"f') == ('"', 2, ["far"])

        assert match(keys, "'") == ("'", 1, ["foo"])
        assert match(keys, "'f") == ("'", 1, ["foo"])
        assert match(keys, '"') == ('"', 1, ["foo"])
        assert match(keys, '"f') == ('"', 1, ["foo"])

        # Completion on first item of tuple
        keys = [("foo", 1111), ("foo", 2222), (3333, "bar"), (3333, "test")]
        assert match(keys, "'f") == ("'", 1, ["foo"])
        assert match(keys, "33") == ("", 0, ["3333"])

        # Completion on numbers
        keys = [
            0xDEADBEEF,
            1111,
            1234,
            "1999",
            0b10101,
            22,
        ]  # 0xDEADBEEF = 3735928559; 0b10101 = 21
        assert match(keys, "0xdead") == ("", 0, ["0xdeadbeef"])
        assert match(keys, "1") == ("", 0, ["1111", "1234"])
        assert match(keys, "2") == ("", 0, ["21", "22"])
        assert match(keys, "0b101") == ("", 0, ["0b10101", "0b10110"])

        # Should yield on variables
        assert match(keys, "a_variable") == ("", 0, [])

        # Should pass over invalid literals
        assert match(keys, "'' ''") == ("", 0, [])

    def test_match_dict_keys_tuple(self):
        """
        Test that match_dict_keys called with extra prefix works on a couple of use case,
        does return what expected, and does not crash.
        """
        delims = " \t\n`!@#$^&*()=+[{]}\\|;:'\",<>?"

        keys = [("foo", "bar"), ("foo", "oof"), ("foo", b"bar"), ("other", "test")]

        def match(*args, extra=None, **kwargs):
            quote, offset, matches = match_dict_keys(
                *args, delims=delims, extra_prefix=extra, **kwargs
            )
            return quote, offset, list(matches)

        # Completion on first key == "foo"
        assert match(keys, "'", extra=("foo",)) == ("'", 1, ["bar", "oof"])
        assert match(keys, '"', extra=("foo",)) == ('"', 1, ["bar", "oof"])
        assert match(keys, "'o", extra=("foo",)) == ("'", 1, ["oof"])
        assert match(keys, '"o', extra=("foo",)) == ('"', 1, ["oof"])
        assert match(keys, "b'", extra=("foo",)) == ("'", 2, ["bar"])
        assert match(keys, 'b"', extra=("foo",)) == ('"', 2, ["bar"])
        assert match(keys, "b'b", extra=("foo",)) == ("'", 2, ["bar"])
        assert match(keys, 'b"b', extra=("foo",)) == ('"', 2, ["bar"])

        # No Completion
        assert match(keys, "'", extra=("no_foo",)) == ("'", 1, [])
        assert match(keys, "'", extra=("fo",)) == ("'", 1, [])

        keys = [("foo1", "foo2", "foo3", "foo4"), ("foo1", "foo2", "bar", "foo4")]
        assert match(keys, "'foo", extra=("foo1",)) == ("'", 1, ["foo2"])
        assert match(keys, "'foo", extra=("foo1", "foo2")) == ("'", 1, ["foo3"])
        assert match(keys, "'foo", extra=("foo1", "foo2", "foo3")) == ("'", 1, ["foo4"])
        assert match(keys, "'foo", extra=("foo1", "foo2", "foo3", "foo4")) == (
            "'",
            1,
            [],
        )

        keys = [("foo", 1111), ("foo", "2222"), (3333, "bar"), (3333, 4444)]
        assert match(keys, "'", extra=("foo",)) == ("'", 1, ["2222"])
        assert match(keys, "", extra=("foo",)) == ("", 0, ["1111", "'2222'"])
        assert match(keys, "'", extra=(3333,)) == ("'", 1, ["bar"])
        assert match(keys, "", extra=(3333,)) == ("", 0, ["'bar'", "4444"])
        assert match(keys, "'", extra=("3333",)) == ("'", 1, [])
        assert match(keys, "33") == ("", 0, ["3333"])

    def test_dict_key_completion_closures(self):
        ip = get_ipython()
        complete = ip.Completer.complete
        ip.Completer.auto_close_dict_keys = True

        ip.user_ns["d"] = {
            # tuple only
            ("aa", 11): None,
            # tuple and non-tuple
            ("bb", 22): None,
            "bb": None,
            # non-tuple only
            "cc": None,
            # numeric tuple only
            (77, "x"): None,
            # numeric tuple and non-tuple
            (88, "y"): None,
            88: None,
            # numeric non-tuple only
            99: None,
        }

        _, matches = complete(line_buffer="d[")
        # should append `, ` if matches a tuple only
        self.assertIn("'aa', ", matches)
        # should not append anything if matches a tuple and an item
        self.assertIn("'bb'", matches)
        # should append `]` if matches and item only
        self.assertIn("'cc']", matches)

        # should append `, ` if matches a tuple only
        self.assertIn("77, ", matches)
        # should not append anything if matches a tuple and an item
        self.assertIn("88", matches)
        # should append `]` if matches and item only
        self.assertIn("99]", matches)

        _, matches = complete(line_buffer="d['aa', ")
        # should restrict matches to those matching tuple prefix
        self.assertIn("11]", matches)
        self.assertNotIn("'bb'", matches)
        self.assertNotIn("'bb', ", matches)
        self.assertNotIn("'bb']", matches)
        self.assertNotIn("'cc'", matches)
        self.assertNotIn("'cc', ", matches)
        self.assertNotIn("'cc']", matches)
        ip.Completer.auto_close_dict_keys = False

    def test_dict_key_completion_string(self):
        """Test dictionary key completion for string keys"""
        ip = get_ipython()
        complete = ip.Completer.complete

        ip.user_ns["d"] = {"abc": None}

        # check completion at different stages
        _, matches = complete(line_buffer="d[")
        self.assertIn("'abc'", matches)
        self.assertNotIn("'abc']", matches)

        _, matches = complete(line_buffer="d['")
        self.assertIn("abc", matches)
        self.assertNotIn("abc']", matches)

        _, matches = complete(line_buffer="d['a")
        self.assertIn("abc", matches)
        self.assertNotIn("abc']", matches)

        # check use of different quoting
        _, matches = complete(line_buffer='d["')
        self.assertIn("abc", matches)
        self.assertNotIn('abc"]', matches)

        _, matches = complete(line_buffer='d["a')
        self.assertIn("abc", matches)
        self.assertNotIn('abc"]', matches)

        # check sensitivity to following context
        _, matches = complete(line_buffer="d[]", cursor_pos=2)
        self.assertIn("'abc'", matches)

        _, matches = complete(line_buffer="d['']", cursor_pos=3)
        self.assertIn("abc", matches)
        self.assertNotIn("abc'", matches)
        self.assertNotIn("abc']", matches)

        # check multiple solutions are correctly returned and that noise is not
        ip.user_ns["d"] = {
            "abc": None,
            "abd": None,
            "bad": None,
            object(): None,
            5: None,
            ("abe", None): None,
            (None, "abf"): None,
        }

        _, matches = complete(line_buffer="d['a")
        self.assertIn("abc", matches)
        self.assertIn("abd", matches)
        self.assertNotIn("bad", matches)
        self.assertNotIn("abe", matches)
        self.assertNotIn("abf", matches)
        assert not any(m.endswith(("]", '"', "'")) for m in matches), matches

        # check escaping and whitespace
        ip.user_ns["d"] = {"a\nb": None, "a'b": None, 'a"b': None, "a word": None}
        _, matches = complete(line_buffer="d['a")
        self.assertIn("a\\nb", matches)
        self.assertIn("a\\'b", matches)
        self.assertIn('a"b', matches)
        self.assertIn("a word", matches)
        assert not any(m.endswith(("]", '"', "'")) for m in matches), matches

        # - can complete on non-initial word of the string
        _, matches = complete(line_buffer="d['a w")
        self.assertIn("word", matches)

        # - understands quote escaping
        _, matches = complete(line_buffer="d['a\\'")
        self.assertIn("b", matches)

        # - default quoting should work like repr
        _, matches = complete(line_buffer="d[")
        self.assertIn('"a\'b"', matches)

        # - when opening quote with ", possible to match with unescaped apostrophe
        _, matches = complete(line_buffer="d[\"a'")
        self.assertIn("b", matches)

        # need to not split at delims that readline won't split at
        if "-" not in ip.Completer.splitter.delims:
            ip.user_ns["d"] = {"before-after": None}
            _, matches = complete(line_buffer="d['before-af")
            self.assertIn("before-after", matches)

        # check completion on tuple-of-string keys at different stage - on first key
        ip.user_ns["d"] = {("foo", "bar"): None}
        _, matches = complete(line_buffer="d[")
        self.assertIn("'foo'", matches)
        self.assertNotIn("'foo']", matches)
        self.assertNotIn("'bar'", matches)
        self.assertNotIn("foo", matches)
        self.assertNotIn("bar", matches)

        # - match the prefix
        _, matches = complete(line_buffer="d['f")
        self.assertIn("foo", matches)
        self.assertNotIn("foo']", matches)
        self.assertNotIn('foo"]', matches)
        _, matches = complete(line_buffer="d['foo")
        self.assertIn("foo", matches)

        # - can complete on second key
        _, matches = complete(line_buffer="d['foo', ")
        self.assertIn("'bar'", matches)
        _, matches = complete(line_buffer="d['foo', 'b")
        self.assertIn("bar", matches)
        self.assertNotIn("foo", matches)

        # - does not propose missing keys
        _, matches = complete(line_buffer="d['foo', 'f")
        self.assertNotIn("bar", matches)
        self.assertNotIn("foo", matches)

        # check sensitivity to following context
        _, matches = complete(line_buffer="d['foo',]", cursor_pos=8)
        self.assertIn("'bar'", matches)
        self.assertNotIn("bar", matches)
        self.assertNotIn("'foo'", matches)
        self.assertNotIn("foo", matches)

        _, matches = complete(line_buffer="d['']", cursor_pos=3)
        self.assertIn("foo", matches)
        assert not any(m.endswith(("]", '"', "'")) for m in matches), matches

        _, matches = complete(line_buffer='d[""]', cursor_pos=3)
        self.assertIn("foo", matches)
        assert not any(m.endswith(("]", '"', "'")) for m in matches), matches

        _, matches = complete(line_buffer='d["foo","]', cursor_pos=9)
        self.assertIn("bar", matches)
        assert not any(m.endswith(("]", '"', "'")) for m in matches), matches

        _, matches = complete(line_buffer='d["foo",]', cursor_pos=8)
        self.assertIn("'bar'", matches)
        self.assertNotIn("bar", matches)

        # Can complete with longer tuple keys
        ip.user_ns["d"] = {("foo", "bar", "foobar"): None}

        # - can complete second key
        _, matches = complete(line_buffer="d['foo', 'b")
        self.assertIn("bar", matches)
        self.assertNotIn("foo", matches)
        self.assertNotIn("foobar", matches)

        # - can complete third key
        _, matches = complete(line_buffer="d['foo', 'bar', 'fo")
        self.assertIn("foobar", matches)
        self.assertNotIn("foo", matches)
        self.assertNotIn("bar", matches)

    def test_dict_key_completion_numbers(self):
        ip = get_ipython()
        complete = ip.Completer.complete

        ip.user_ns["d"] = {
            0xDEADBEEF: None,  # 3735928559
            1111: None,
            1234: None,
            "1999": None,
            0b10101: None,  # 21
            22: None,
        }
        _, matches = complete(line_buffer="d[1")
        self.assertIn("1111", matches)
        self.assertIn("1234", matches)
        self.assertNotIn("1999", matches)
        self.assertNotIn("'1999'", matches)

        _, matches = complete(line_buffer="d[0xdead")
        self.assertIn("0xdeadbeef", matches)

        _, matches = complete(line_buffer="d[2")
        self.assertIn("21", matches)
        self.assertIn("22", matches)

        _, matches = complete(line_buffer="d[0b101")
        self.assertIn("0b10101", matches)
        self.assertIn("0b10110", matches)

    def test_dict_key_completion_contexts(self):
        """Test expression contexts in which dict key completion occurs"""
        ip = get_ipython()
        complete = ip.Completer.complete
        d = {"abc": None}
        ip.user_ns["d"] = d

        class C:
            data = d

        ip.user_ns["C"] = C
        ip.user_ns["get"] = lambda: d
        ip.user_ns["nested"] = {"x": d}

        def assert_no_completion(**kwargs):
            _, matches = complete(**kwargs)
            self.assertNotIn("abc", matches)
            self.assertNotIn("abc'", matches)
            self.assertNotIn("abc']", matches)
            self.assertNotIn("'abc'", matches)
            self.assertNotIn("'abc']", matches)

        def assert_completion(**kwargs):
            _, matches = complete(**kwargs)
            self.assertIn("'abc'", matches)
            self.assertNotIn("'abc']", matches)

        # no completion after string closed, even if reopened
        assert_no_completion(line_buffer="d['a'")
        assert_no_completion(line_buffer='d["a"')
        assert_no_completion(line_buffer="d['a' + ")
        assert_no_completion(line_buffer="d['a' + '")

        # completion in non-trivial expressions
        assert_completion(line_buffer="+ d[")
        assert_completion(line_buffer="(d[")
        assert_completion(line_buffer="C.data[")

        # nested dict completion
        assert_completion(line_buffer="nested['x'][")

        with evaluation_policy("minimal"):
            with pytest.raises(AssertionError):
                assert_completion(line_buffer="nested['x'][")

        # greedy flag
        def assert_completion(**kwargs):
            _, matches = complete(**kwargs)
            self.assertIn("get()['abc']", matches)

        assert_no_completion(line_buffer="get()[")
        with greedy_completion():
            assert_completion(line_buffer="get()[")
            assert_completion(line_buffer="get()['")
            assert_completion(line_buffer="get()['a")
            assert_completion(line_buffer="get()['ab")
            assert_completion(line_buffer="get()['abc")

    def test_completion_autoimport(self):
        ip = get_ipython()
        complete = ip.Completer.complete
        with (
            evaluation_policy("limited", allow_auto_import=True),
            jedi_status(False),
        ):
            _, matches = complete(line_buffer="math.")
            self.assertIn(".pi", matches)

    def test_completion_no_autoimport(self):
        ip = get_ipython()
        complete = ip.Completer.complete
        with (
            evaluation_policy("limited", allow_auto_import=False),
            jedi_status(False),
        ):
            _, matches = complete(line_buffer="math.")
            self.assertNotIn(".pi", matches)

    def test_completion_allow_custom_getattr_per_module(self):
        factory_code = textwrap.dedent(
            """
        class ListFactory:
            def __getattr__(self, attr):
                return []
        """
        )

        safe_lib = types.ModuleType("my.safe.lib")
        sys.modules["my.safe.lib"] = safe_lib
        exec(factory_code, safe_lib.__dict__)

        unsafe_lib = types.ModuleType("my.unsafe.lib")
        sys.modules["my.unsafe.lib"] = unsafe_lib
        exec(factory_code, unsafe_lib.__dict__)

        fake_safe_lib = types.ModuleType("my_fake_lib")
        sys.modules["my_fake_lib"] = fake_safe_lib
        exec(factory_code, fake_safe_lib.__dict__)

        ip = get_ipython()
        ip.user_ns["safe_list_factory"] = safe_lib.ListFactory()
        ip.user_ns["unsafe_list_factory"] = unsafe_lib.ListFactory()
        ip.user_ns["fake_safe_factory"] = fake_safe_lib.ListFactory()
        complete = ip.Completer.complete
        with (
            evaluation_policy("limited", allowed_getattr_external={"my.safe.lib"}),
            jedi_status(False),
        ):
            _, matches = complete(line_buffer="safe_list_factory.example.")
            self.assertIn(".append", matches)
            # this also checks against https://github.com/ipython/ipython/issues/14916
            # because removing "un" would cause this test to incorrectly pass
            _, matches = complete(line_buffer="unsafe_list_factory.example.")
            self.assertNotIn(".append", matches)

        sys.modules["my"] = types.ModuleType("my")

        with (
            evaluation_policy("limited", allowed_getattr_external={"my"}),
            jedi_status(False),
        ):
            _, matches = complete(line_buffer="safe_list_factory.example.")
            self.assertIn(".append", matches)
            _, matches = complete(line_buffer="unsafe_list_factory.example.")
            self.assertIn(".append", matches)
            _, matches = complete(line_buffer="fake_safe_factory.example.")
            self.assertNotIn(".append", matches)

        with (
            evaluation_policy("limited"),
            jedi_status(False),
        ):
            _, matches = complete(line_buffer="safe_list_factory.example.")
            self.assertNotIn(".append", matches)
            _, matches = complete(line_buffer="unsafe_list_factory.example.")
            self.assertNotIn(".append", matches)

    def test_completion_allow_subclass_of_trusted_module(self):
        factory_code = textwrap.dedent(
            """
            class ListFactory:
                def __getattr__(self, attr):
                    return []
            """
        )
        trusted_lib = types.ModuleType("my.trusted.lib")
        sys.modules["my.trusted.lib"] = trusted_lib
        exec(factory_code, trusted_lib.__dict__)

        ip = get_ipython()
        # Create a subclass in __main__ (untrusted namespace)
        subclass_code = textwrap.dedent(
            """
            class SubclassFactory(trusted_lib.ListFactory):
                pass
            """
        )
        ip.user_ns["trusted_lib"] = trusted_lib
        exec(subclass_code, ip.user_ns)
        ip.user_ns["subclass_factory"] = ip.user_ns["SubclassFactory"]()
        complete = ip.Completer.complete
        with (
            evaluation_policy("limited", allowed_getattr_external={"my.trusted.lib"}),
            jedi_status(False),
        ):
            _, matches = complete(line_buffer="subclass_factory.example.")
            self.assertIn(".append", matches)

        # Test that overriding __getattr__ in subclass in untrusted namespace prevents completion
        overriding_subclass_code = textwrap.dedent(
            """
            class OverridingSubclass(trusted_lib.ListFactory):
                def __getattr__(self, attr):
                    return {}
            """
        )
        exec(overriding_subclass_code, ip.user_ns)
        ip.user_ns["overriding_factory"] = ip.user_ns["OverridingSubclass"]()

        with (
            evaluation_policy("limited", allowed_getattr_external={"my.trusted.lib"}),
            jedi_status(False),
        ):
            _, matches = complete(line_buffer="overriding_factory.example.")
            self.assertNotIn(".append", matches)
            self.assertNotIn(".keys", matches)

    def test_completion_fallback_to_annotation_for_attribute(self):
        code = textwrap.dedent(
            """
            class StringMethods:
                def a():
                    pass

            class Test:
                str: StringMethods
                def __init__(self):
                    self.str = StringMethods()
                def __getattr__(self, name):
                    raise AttributeError(f"{name} not found")
            """
        )

        repro = types.ModuleType("repro")
        sys.modules["repro"] = repro
        exec(code, repro.__dict__)

        ip = get_ipython()
        ip.user_ns["repro"] = repro
        exec("r = repro.Test()", ip.user_ns)

        complete = ip.Completer.complete
        try:
            with evaluation_policy("limited"), jedi_status(False):
                _, matches = complete(line_buffer="r.str.")
                self.assertIn(".a", matches)
        finally:
            sys.modules.pop("repro", None)
            ip.user_ns.pop("r", None)

    def test_policy_warnings(self):
        with self.assertWarns(
            UserWarning,
            msg="Override 'allowed_getattr_external' is not valid with 'unsafe' evaluation policy",
        ):
            with evaluation_policy("unsafe", allowed_getattr_external=[]):
                pass

        with self.assertWarns(
            UserWarning,
            msg="Override 'test' is not valid with 'limited' evaluation policy",
        ):
            with evaluation_policy("limited", test=[]):
                pass

    def test_dict_key_completion_bytes(self):
        """Test handling of bytes in dict key completion"""
        ip = get_ipython()
        complete = ip.Completer.complete

        ip.user_ns["d"] = {"abc": None, b"abd": None}

        _, matches = complete(line_buffer="d[")
        self.assertIn("'abc'", matches)
        self.assertIn("b'abd'", matches)

        if False:  # not currently implemented
            _, matches = complete(line_buffer="d[b")
            self.assertIn("b'abd'", matches)
            self.assertNotIn("b'abc'", matches)

            _, matches = complete(line_buffer="d[b'")
            self.assertIn("abd", matches)
            self.assertNotIn("abc", matches)

            _, matches = complete(line_buffer="d[B'")
            self.assertIn("abd", matches)
            self.assertNotIn("abc", matches)

            _, matches = complete(line_buffer="d['")
            self.assertIn("abc", matches)
            self.assertNotIn("abd", matches)

    def test_dict_key_completion_unicode_py3(self):
        """Test handling of unicode in dict key completion"""
        ip = get_ipython()
        complete = ip.Completer.complete

        ip.user_ns["d"] = {"a\u05d0": None}

        # query using escape
        if sys.platform != "win32":
            # Known failure on Windows
            _, matches = complete(line_buffer="d['a\\u05d0")
            self.assertIn("u05d0", matches)  # tokenized after \\

        # query using character
        _, matches = complete(line_buffer="d['a\u05d0")
        self.assertIn("a\u05d0", matches)

        with greedy_completion():
            # query using escape
            _, matches = complete(line_buffer="d['a\\u05d0")
            self.assertIn("d['a\\u05d0']", matches)  # tokenized after \\

            # query using character
            _, matches = complete(line_buffer="d['a\u05d0")
            self.assertIn("d['a\u05d0']", matches)

    @dec.skip_without("numpy")
    def test_struct_array_key_completion(self):
        """Test dict key completion applies to numpy struct arrays"""
        import numpy

        ip = get_ipython()
        complete = ip.Completer.complete
        ip.user_ns["d"] = numpy.array([], dtype=[("hello", "f"), ("world", "f")])
        _, matches = complete(line_buffer="d['")
        self.assertIn("hello", matches)
        self.assertIn("world", matches)
        # complete on the numpy struct itself
        dt = numpy.dtype(
            [("my_head", [("my_dt", ">u4"), ("my_df", ">u4")]), ("my_data", ">f4", 5)]
        )
        x = numpy.zeros(2, dtype=dt)
        ip.user_ns["d"] = x[1]
        _, matches = complete(line_buffer="d['")
        self.assertIn("my_head", matches)
        self.assertIn("my_data", matches)

        def completes_on_nested():
            ip.user_ns["d"] = numpy.zeros(2, dtype=dt)
            _, matches = complete(line_buffer="d[1]['my_head']['")
            self.assertTrue(any(["my_dt" in m for m in matches]))
            self.assertTrue(any(["my_df" in m for m in matches]))

        # complete on a nested level
        with greedy_completion():
            completes_on_nested()

        with evaluation_policy("limited"):
            completes_on_nested()

        with evaluation_policy("minimal"):
            with pytest.raises(AssertionError):
                completes_on_nested()

    @dec.skip_without("pandas")
    def test_dataframe_key_completion(self):
        """Test dict key completion applies to pandas DataFrames"""
        import pandas

        ip = get_ipython()
        complete = ip.Completer.complete
        ip.user_ns["d"] = pandas.DataFrame({"hello": [1], "world": [2]})
        _, matches = complete(line_buffer="d['")
        self.assertIn("hello", matches)
        self.assertIn("world", matches)
        _, matches = complete(line_buffer="d.loc[:, '")
        self.assertIn("hello", matches)
        self.assertIn("world", matches)
        _, matches = complete(line_buffer="d.loc[1:, '")
        self.assertIn("hello", matches)
        _, matches = complete(line_buffer="d.loc[1:1, '")
        self.assertIn("hello", matches)
        _, matches = complete(line_buffer="d.loc[1:1:-1, '")
        self.assertIn("hello", matches)
        _, matches = complete(line_buffer="d.loc[::, '")
        self.assertIn("hello", matches)

    def test_dict_key_completion_invalids(self):
        """Smoke test cases dict key completion can't handle"""
        ip = get_ipython()
        complete = ip.Completer.complete

        ip.user_ns["no_getitem"] = None
        ip.user_ns["no_keys"] = []
        ip.user_ns["cant_call_keys"] = dict
        ip.user_ns["empty"] = {}
        ip.user_ns["d"] = {"abc": 5}

        _, matches = complete(line_buffer="no_getitem['")
        _, matches = complete(line_buffer="no_keys['")
        _, matches = complete(line_buffer="cant_call_keys['")
        _, matches = complete(line_buffer="empty['")
        _, matches = complete(line_buffer="name_error['")
        _, matches = complete(line_buffer="d['\\")  # incomplete escape

    def test_object_key_completion(self):
        ip = get_ipython()
        ip.user_ns["key_completable"] = KeyCompletable(["qwerty", "qwick"])

        _, matches = ip.Completer.complete(line_buffer="key_completable['qw")
        self.assertIn("qwerty", matches)
        self.assertIn("qwick", matches)

    def test_class_key_completion(self):
        ip = get_ipython()
        NamedInstanceClass("qwerty")
        NamedInstanceClass("qwick")
        ip.user_ns["named_instance_class"] = NamedInstanceClass

        _, matches = ip.Completer.complete(line_buffer="named_instance_class['qw")
        self.assertIn("qwerty", matches)
        self.assertIn("qwick", matches)

    def test_tryimport(self):
        """
        Test that try-import don't crash on trailing dot, and import modules before
        """
        from IPython.core.completerlib import try_import

        assert try_import("IPython.")

    def test_aimport_module_completer(self):
        ip = get_ipython()
        _, matches = ip.complete("i", "%aimport i")
        self.assertIn("io", matches)
        self.assertNotIn("int", matches)

    def test_nested_import_module_completer(self):
        ip = get_ipython()
        _, matches = ip.complete(None, "import IPython.co", 17)
        self.assertIn("IPython.core", matches)
        self.assertNotIn("import IPython.core", matches)
        self.assertNotIn("IPython.display", matches)

    def test_import_module_completer(self):
        ip = get_ipython()
        _, matches = ip.complete("i", "import i")
        self.assertIn("io", matches)
        self.assertNotIn("int", matches)

    def test_from_module_completer(self):
        ip = get_ipython()
        _, matches = ip.complete("B", "from io import B", 16)
        self.assertIn("BytesIO", matches)
        self.assertNotIn("BaseException", matches)

    def test_snake_case_completion(self):
        ip = get_ipython()
        ip.Completer.use_jedi = False
        ip.user_ns["some_three"] = 3
        ip.user_ns["some_four"] = 4
        _, matches = ip.complete("s_", "print(s_f")
        self.assertIn("some_three", matches)
        self.assertIn("some_four", matches)

    def test_mix_terms(self):
        ip = get_ipython()
        from textwrap import dedent

        ip.Completer.use_jedi = False
        ip.ex(
            dedent(
                """
            class Test:
                def meth(self, meth_arg1):
                    print("meth")

                def meth_1(self, meth1_arg1, meth1_arg2):
                    print("meth1")

                def meth_2(self, meth2_arg1, meth2_arg2):
                    print("meth2")
            test = Test()
            """
            )
        )
        _, matches = ip.complete(None, "test.meth(")
        self.assertIn("meth_arg1=", matches)
        self.assertNotIn("meth2_arg1=", matches)

    def test_percent_symbol_restrict_to_magic_completions(self):
        ip = get_ipython()
        completer = ip.Completer
        text = "%a"

        with provisionalcompleter():
            completer.use_jedi = True
            completions = completer.completions(text, len(text))
            for c in completions:
                self.assertEqual(c.text[0], "%")

    def test_fwd_unicode_restricts(self):
        ip = get_ipython()
        completer = ip.Completer
        text = "\\ROMAN NUMERAL FIVE"

        with provisionalcompleter():
            completer.use_jedi = True
            completions = [
                completion.text for completion in completer.completions(text, len(text))
            ]
            self.assertEqual(completions, ["\u2164"])

    def test_dict_key_restrict_to_dicts(self):
        """Test that dict key suppresses non-dict completion items"""
        ip = get_ipython()
        c = ip.Completer
        d = {"abc": None}
        ip.user_ns["d"] = d

        text = 'd["a'

        def _():
            with provisionalcompleter():
                c.use_jedi = True
                return [
                    completion.text for completion in c.completions(text, len(text))
                ]

        completions = _()
        self.assertEqual(completions, ["abc"])

        # check that it can be disabled in granular manner:
        cfg = Config()
        cfg.IPCompleter.suppress_competing_matchers = {
            "IPCompleter.dict_key_matcher": False
        }
        c.update_config(cfg)

        completions = _()
        self.assertIn("abc", completions)
        self.assertGreater(len(completions), 1)

    def test_matcher_suppression(self):
        @completion_matcher(identifier="a_matcher")
        def a_matcher(text):
            return ["completion_a"]

        @completion_matcher(identifier="b_matcher", api_version=2)
        def b_matcher(context: CompletionContext):
            text = context.token
            result = {"completions": [SimpleCompletion("completion_b")]}

            if text == "suppress c":
                result["suppress"] = {"c_matcher"}

            if text.startswith("suppress all"):
                result["suppress"] = True
                if text == "suppress all but c":
                    result["do_not_suppress"] = {"c_matcher"}
                if text == "suppress all but a":
                    result["do_not_suppress"] = {"a_matcher"}

            return result

        @completion_matcher(identifier="c_matcher")
        def c_matcher(text):
            return ["completion_c"]

        with custom_matchers([a_matcher, b_matcher, c_matcher]):
            ip = get_ipython()
            c = ip.Completer

            def _(text, expected):
                c.use_jedi = False
                s, matches = c.complete(text)
                self.assertEqual(expected, matches)

            _("do not suppress", ["completion_a", "completion_b", "completion_c"])
            _("suppress all", ["completion_b"])
            _("suppress all but a", ["completion_a", "completion_b"])
            _("suppress all but c", ["completion_b", "completion_c"])

            def configure(suppression_config):
                cfg = Config()
                cfg.IPCompleter.suppress_competing_matchers = suppression_config
                c.update_config(cfg)

            # test that configuration takes priority over the run-time decisions

            configure(False)
            _("suppress all", ["completion_a", "completion_b", "completion_c"])

            configure({"b_matcher": False})
            _("suppress all", ["completion_a", "completion_b", "completion_c"])

            configure({"a_matcher": False})
            _("suppress all", ["completion_b"])

            configure({"b_matcher": True})
            _("do not suppress", ["completion_b"])

            configure(True)
            _("do not suppress", ["completion_a"])

    def test_matcher_suppression_with_iterator(self):
        @completion_matcher(identifier="matcher_returning_iterator")
        def matcher_returning_iterator(text):
            return iter(["completion_iter"])

        @completion_matcher(identifier="matcher_returning_list")
        def matcher_returning_list(text):
            return ["completion_list"]

        with custom_matchers([matcher_returning_iterator, matcher_returning_list]):
            ip = get_ipython()
            c = ip.Completer

            def _(text, expected):
                c.use_jedi = False
                s, matches = c.complete(text)
                self.assertEqual(expected, matches)

            def configure(suppression_config):
                cfg = Config()
                cfg.IPCompleter.suppress_competing_matchers = suppression_config
                c.update_config(cfg)

            configure(False)
            _("---", ["completion_iter", "completion_list"])

            configure(True)
            _("---", ["completion_iter"])

            configure(None)
            _("--", ["completion_iter", "completion_list"])

    @pytest.mark.xfail(
        sys.version_info.releaselevel in ("alpha",),
        reason="Parso does not yet parse 3.13",
    )
    def test_matcher_suppression_with_jedi(self):
        ip = get_ipython()
        c = ip.Completer
        c.use_jedi = True

        def configure(suppression_config):
            cfg = Config()
            cfg.IPCompleter.suppress_competing_matchers = suppression_config
            c.update_config(cfg)

        def _():
            with provisionalcompleter():
                matches = [completion.text for completion in c.completions("dict.", 5)]
                self.assertIn("keys", matches)

        configure(False)
        _()

        configure(True)
        _()

        configure(None)
        _()

    def test_matcher_disabling(self):
        @completion_matcher(identifier="a_matcher")
        def a_matcher(text):
            return ["completion_a"]

        @completion_matcher(identifier="b_matcher")
        def b_matcher(text):
            return ["completion_b"]

        def _(expected):
            s, matches = c.complete("completion_")
            self.assertEqual(expected, matches)

        with custom_matchers([a_matcher, b_matcher]):
            ip = get_ipython()
            c = ip.Completer

            _(["completion_a", "completion_b"])

            cfg = Config()
            cfg.IPCompleter.disable_matchers = ["b_matcher"]
            c.update_config(cfg)

            _(["completion_a"])

            cfg.IPCompleter.disable_matchers = []
            c.update_config(cfg)

    def test_matcher_priority(self):
        @completion_matcher(identifier="a_matcher", priority=0, api_version=2)
        def a_matcher(text):
            return {"completions": [SimpleCompletion("completion_a")], "suppress": True}

        @completion_matcher(identifier="b_matcher", priority=2, api_version=2)
        def b_matcher(text):
            return {"completions": [SimpleCompletion("completion_b")], "suppress": True}

        def _(expected):
            s, matches = c.complete("completion_")
            self.assertEqual(expected, matches)

        with custom_matchers([a_matcher, b_matcher]):
            ip = get_ipython()
            c = ip.Completer

            _(["completion_b"])
            a_matcher.matcher_priority = 3
            _(["completion_a"])


@pytest.mark.parametrize(
    "use_jedi,evaluation",
    [
        [True, "minimal"],
        [False, "limited"],
    ],
)
@pytest.mark.parametrize(
    "code,insert_text",
    [
        [
            "\n".join(
                [
                    "class NotYetDefined:",
                    "    def my_method(self) -> str:",
                    "        return 1",
                    "my_instance = NotYetDefined()",
                    "my_insta",
                ]
            ),
            "my_instance",
        ],
        [
            "\n".join(
                [
                    "class NotYetDefined:",
                    "    def my_method(self) -> str:",
                    "        return 1",
                    "instance = NotYetDefined()",
                    "instance.",
                ]
            ),
            "my_method",
        ],
        [
            "\n".join(
                [
                    "class NotYetDefined:",
                    "    def my_method(self) -> str:",
                    "        return 1",
                    "my_instance = NotYetDefined()",
                    "my_instance.my_method().",
                ]
            ),
            "capitalize",
        ],
        [
            "\n".join(
                [
                    "class NotYetDefined:",
                    "    def my_method(self):",
                    "        return []",
                    "my_instance = NotYetDefined()",
                    "my_instance.my_method().",
                ]
            ),
            "append",
        ],
        [
            "\n".join(
                [
                    "class NotYetDefined:",
                    "    @property",
                    "    def my_property(self):",
                    "        return 1.1",
                    "my_instance = NotYetDefined()",
                    "my_instance.my_property.",
                ]
            ),
            "as_integer_ratio",
        ],
        [
            "\n".join(
                [
                    "my_instance = 1.1",
                    "assert my_instance.",
                ]
            ),
            "as_integer_ratio",
        ],
        [
            "\n".join(
                [
                    "def my_test() -> float:",
                    "    pass",
                    "my_test().",
                ]
            ),
            "as_integer_ratio",
        ],
        [
            "\n".join(
                [
                    "def my_test():",
                    "    return {}",
                    "my_test().",
                ]
            ),
            "keys",
        ],
        [
            "\n".join(
                [
                    "l = []",
                    "def my_test():",
                    "    return l",
                    "my_test().",
                ]
            ),
            "append",
        ],
        [
            "\n".join(
                [
                    "num = {1: 'one'}",
                    "num[2] = 'two'",
                    "num.",
                ]
            ),
            "keys",
        ],
        [
            "\n".join(
                [
                    "num = {1: 'one'}",
                    "num[2] = ['two']",
                    "num[2].",
                ]
            ),
            "append",
        ],
        [
            "\n".join(
                [
                    "l = []",
                    "class NotYetDefined:",
                    "    def my_method(self):",
                    "        return l",
                    "my_instance = NotYetDefined()",
                    "my_instance.my_method().",
                ]
            ),
            "append",
        ],
        [
            "\n".join(
                [
                    "def string_or_int(flag):",
                    "    if flag:",
                    "        return 'test'",
                    "    return 1",
                    "string_or_int().",
                ]
            ),
            ["capitalize", "as_integer_ratio"],
        ],
        [
            "\n".join(
                [
                    "def foo():",
                    "    l = []",
                    "    return l",
                    "foo().",
                ]
            ),
            "append",
        ],
        [
            "\n".join(
                [
                    "class NotYetDefined:",
                    "    def __init__(self):",
                    "        self.test = []",
                    "instance = NotYetDefined()",
                    "instance.",
                ]
            ),
            "test",
        ],
        [
            "\n".join(
                [
                    "class NotYetDefined:",
                    "    def __init__(instance):",
                    "        instance.test = []",
                    "instance = NotYetDefined()",
                    "instance.test.",
                ]
            ),
            "append",
        ],
        [
            "\n".join(
                [
                    "class NotYetDefined:",
                    "    def __init__(this):",
                    "        this.test:str = []",
                    "instance = NotYetDefined()",
                    "instance.test.",
                ]
            ),
            "capitalize",
        ],
        [
            "\n".join(
                [
                    "l = []",
                    "class NotYetDefined:",
                    "    def __init__(me):",
                    "        me.test = l",
                    "instance = NotYetDefined()",
                    "instance.test.",
                ]
            ),
            "append",
        ],
        [
            "\n".join(
                [
                    "class NotYetDefined:",
                    "    def test(self):",
                    "        self.l = []",
                    "        return self.l",
                    "instance = NotYetDefined()",
                    "instance.test().",
                ]
            ),
            "append",
        ],
        [
            "\n".join(
                [
                    "class NotYetDefined:",
                    "    def test():",
                    "        return []",
                    "instance = NotYetDefined()",
                    "instance.test().",
                ]
            ),
            "append",
        ],
        [
            "\n".join(
                [
                    "def foo():",
                    "    if some_condition:",
                    "        return {'top':{'mid':{'leaf': 2}}}",
                    "    return {'top': {'mid':[]}}",
                    "foo()['top']['mid'].",
                ]
            ),
            ["keys", "append"],
        ],
        [
            "\n".join(
                [
                    "def foo():",
                    "    if some_condition:",
                    "        return {'top':{'mid':{'leaf': 2}}}",
                    "    return {'top': {'mid':[]}}",
                    "foo()['top']['mid']['leaf'].",
                ]
            ),
            "as_integer_ratio",
        ],
        [
            "\n".join(
                [
                    "async def async_func():",
                    "    return []",
                    "async_func().",
                ]
            ),
            "cr_await",
        ],
        [
            "\n".join(
                [
                    "async def async_func():",
                    "    return []",
                    "(await async_func()).",
                ]
            ),
            "append",
        ],
        [
            "\n".join(["t = []", "if some_condition:", "    t."]),
            "append",
        ],
        [
            "\n".join(
                [
                    "t = []",
                    "if some_condition:",
                    "    t = 'string'",
                    "t.",
                ]
            ),
            ["append", "capitalize"],
        ],
        [
            "\n".join(
                [
                    "t = []",
                    "if some_condition:",
                    "    t = 'string'",
                    "else:",
                    "    t.",
                ]
            ),
            "append",
        ],
        [
            "\n".join(
                [
                    "t = []",
                    "if some_condition:",
                    "    t = 'string'",
                    "else:",
                    "    t = 1",
                    "t.",
                ]
            ),
            ["append", "capitalize", "as_integer_ratio"],
        ],
        [
            "\n".join(
                [
                    "t = []",
                    "if condition_1:",
                    "    t = 'string'",
                    "elif condition_2:",
                    "    t = 1",
                    "elif condition_3:",
                    "    t.",
                ]
            ),
            "append",
        ],
        [
            "\n".join(
                [
                    "t = []",
                    "if condition_1:",
                    "    t = 'string'",
                    "elif condition_2:",
                    "    t = 1",
                    "elif condition_3:",
                    "    t = {}",
                    "t.",
                ]
            ),
            ["append", "capitalize", "as_integer_ratio", "keys"],
        ],
        [
            "\n".join(
                [
                    "t = []",
                    "if condition_1:",
                    "    if condition_2:",
                    "        t = 'nested'",
                    "t.",
                ]
            ),
            ["append", "capitalize"],
        ],
        [
            "\n".join(
                [
                    "a = []",
                    "while condition:",
                    "    a.",
                ]
            ),
            "append",
        ],
        [
            "\n".join(
                [
                    "t = []",
                    "while condition:",
                    "    t = 'str'",
                    "t.",
                ]
            ),
            ["append", "capitalize"],
        ],
        [
            "\n".join(
                [
                    "t = []",
                    "while condition_1:",
                    "    while condition_2:",
                    "        t = 'str'",
                    "t.",
                ]
            ),
            ["append", "capitalize"],
        ],
        [
            "\n".join(
                [
                    "for i in range(10):",
                    "    i.",
                ]
            ),
            "bit_length",
        ],
        [
            "\n".join(
                [
                    "for i in range(10):",
                    "    if i % 2 == 0:",
                    "        i.",
                ]
            ),
            "bit_length",
        ],
        [
            "\n".join(
                [
                    "for item in ['a', 'b', 'c']:",
                    "    item.",
                ]
            ),
            "capitalize",
        ],
        [
            "\n".join(
                [
                    "for key, value in {'a': 1, 'b': 2}.items():",
                    "    key.",
                ]
            ),
            "capitalize",
        ],
        [
            "\n".join(
                [
                    "for key, value in {'a': 1, 'b': 2}.items():",
                    "    value.",
                ]
            ),
            "bit_length",
        ],
        [
            "\n".join(
                [
                    "for sublist in [[1, 2], [3, 4]]:",
                    "    sublist.",
                ]
            ),
            "append",
        ],
        [
            "\n".join(
                [
                    "for sublist in [[1, 2], [3, 4]]:",
                    "    for item in sublist:",
                    "        item.",
                ]
            ),
            "bit_length",
        ],
        [
            "\n".join(
                [
                    "t: list[str]",
                    "t[0].",
                ]
            ),
            ["capitalize"],
        ],
    ],
)
def test_undefined_variables(use_jedi, evaluation, code, insert_text):
    offset = len(code)
    ip.Completer.use_jedi = use_jedi
    ip.Completer.evaluation = evaluation

    with provisionalcompleter():
        completions = list(ip.Completer.completions(text=code, offset=offset))
        insert_texts = insert_text if isinstance(insert_text, list) else [insert_text]
        for text in insert_texts:
            match = [c for c in completions if c.text.lstrip(".") == text]
            message_on_fail = f"{text} not found among {[c.text for c in completions]}"
            assert len(match) == 1, message_on_fail


@pytest.mark.parametrize(
    "code,insert_text",
    [
        [
            "\n".join(
                [
                    "t: dict = {'a': []}",
                    "t['a'].",
                ]
            ),
            ["append"],
        ],
        [
          "\n".join(
                [
                    "t: int | dict = {'a': []}",
                    "t.",
                ]
            ),
            ["keys", "bit_length"],
        ],
        [
            "\n".join(
                [
                    "t: int | dict = {'a': []}",
                    "t['a'].",
                ]
            ),
            "append",
        ],
        # Test union types
        [
            "\n".join(
                [
                    "t: int | str",
                    "t.",
                ]
            ),
            ["bit_length", "capitalize"],
        ],
        [
            "\n".join(
                [
                    "def func() -> int | str: pass",
                    "func().",
                ]
            ),
            ["bit_length", "capitalize"],
        ],
        [
            "\n".join(
                [
                    "t: list = ['test']",
                    "t[0].",
                ]
            ),
            ["capitalize"],
        ],
        [
            "\n".join(
                [
                    "class T:",
                    "   @property",
                    "   def p(self) -> int | str: pass",
                    "t = T()",
                    "t.p.",
                ]
            ),
            ["bit_length", "capitalize"],
        ],
    ],
)
def test_undefined_variables_without_jedi(code, insert_text):
    offset = len(code)
    ip.Completer.use_jedi = False
    ip.Completer.evaluation = "limited"

    with provisionalcompleter():
        completions = list(ip.Completer.completions(text=code, offset=offset))
        insert_texts = insert_text if isinstance(insert_text, list) else [insert_text]
        for text in insert_texts:
            match = [c for c in completions if c.text.lstrip(".") == text]
            message_on_fail = f"{text} not found among {[c.text for c in completions]}"
            assert len(match) == 1, message_on_fail


@pytest.mark.parametrize(
    "code",
    [
        "\n".join(
            [
                "def my_test() -> float:",
                "    return 1.1",
                "my_test().",
            ]
        ),
        "\n".join(
            [
                "class MyClass():",
                "    b: list[str]",
                "x = MyClass()",
                "x.b[0].",
            ]
        ),
        "\n".join(
            [
                "class MyClass():",
                "    b: list[str]",
                "x = MyClass()",
                "x.fake_attr().",
            ]
        ),
    ],
)
def test_no_file_completions_in_attr_access(code):
    """Test that files are not suggested during attribute/method completion."""
    with TemporaryWorkingDirectory():
        open(".hidden", "w", encoding="utf-8").close()
        offset = len(code)
        for use_jedi in (True, False):
            with provisionalcompleter(), jedi_status(use_jedi):
                completions = list(ip.Completer.completions(text=code, offset=offset))
                matches = [c for c in completions if c.text.lstrip(".") == "hidden"]
                assert (
                    len(matches) == 0
                ), f"File '.hidden' should not appear in attribute completion"


@pytest.mark.parametrize(
    "line,expected",
    [
        # Basic test cases
        ("np.", "attribute"),
        ("np.ran", "attribute"),
        ("np.random.rand(np.random.ran", "attribute"),
        ("np.random.rand(n", "global"),
        ("d['k.e.y.'](ran", "global"),
        ("d[0].k", "attribute"),
        ("a = { 'a': np.ran", "attribute"),
        ("n", "global"),
        ("", "global"),
        # Dots in string literals
        ('some_var = "this is a string with a dot.', "global"),
        ("text = 'another string with a dot.", "global"),
        ('f"greeting {user.na', "attribute"),  # Cursor in f-string expression
        ('t"welcome {guest.na', "attribute"),  # Cursor in t-string expression
        ('f"hello {name} worl', "global"),  # Cursor in f-string outside expression
        ('f"hello {{a.', "global"),
        ('f"hello {{{a.', "attribute"),
        # Backslash escapes in strings
        ('var = "string with \\"escaped quote and a dot.', "global"),
        ("escaped = 'single \\'quote\\' with a dot.", "global"),
        # Multi-line strings
        ('multi = """This is line one\nwith a dot.', "global"),
        ("multi_single = '''Another\nmulti-line\nwith a dot.", "global"),
        # Inline comments
        ("x = 5  # This is a comment", "global"),
        ("y = obj.method()  # Comment after dot.method", "global"),
        # Hash symbol within string literals should not be treated as comments
        ("d['#'] = np.", "attribute"),
        # Nested parentheses with dots
        ("complex_expr = (func((obj.method(param.attr", "attribute"),
        ("multiple_nesting = {key: [value.attr", "attribute"),
        # Numbers
        ("3.", "global"),
        ("3.14", "global"),
        ("-42.14", "global"),
        ("x = func(3.14", "global"),
        ("x = func(a3.", "attribute"),
        ("x = func(a3.12", "global"),
        ("3.1.", "attribute"),
        ("-3.1.", "attribute"),
        ("(3).", "attribute"),
        # Additional cases
        ("", "global"),
        ('str_with_code = "x.attr', "global"),
        ('f"formatted {obj.attr', "attribute"),
        ('f"formatted {obj.attr}', "global"),
        ("dict_with_dots = {'key.with.dots': value.attr", "attribute"),
        ("d[f'{a}']['{a.", "global"),
        ("ls .", "global"),
    ],
)
def test_completion_context(line, expected):
    """Test completion context"""
    ip = get_ipython()
    get_context = ip.Completer._determine_completion_context
    result = get_context(line)
    assert result.value == expected, f"Failed on input: '{line}'"


@pytest.mark.parametrize(
    "line,expected,expected_after_assignment",
    [
        ("test_alias file", True, False),  # overshadowed by variable
        ("test_alias .", True, False),
        ("test_alias file.", True, False),
        ("%test_alias .file.ext", True, True),  # magic, not affected by variable
        ("!test_alias file.", True, True),  # bang, not affected by variable
    ],
)
def test_completion_in_cli_context(line, expected, expected_after_assignment):
    """Test completion context with and without variable overshadowing"""
    ip = get_ipython()
    ip.run_cell("alias test_alias echo test_alias")
    get_context = ip.Completer._is_completing_in_cli_context

    # Normal case
    result = get_context(line)
    assert result == expected, f"Failed on input: '{line}'"

    # Test with alias assigned as a variable
    try:
        ip.user_ns["test_alias"] = "some_value"
        result_after_assignment = get_context(line)
        assert (
            result_after_assignment == expected_after_assignment
        ), f"Failed after assigning 'ls' as a variable for input: '{line}'"
    finally:
        ip.user_ns.pop("test_alias", None)


@pytest.mark.xfail(reason="Completion context not yet supported")
@pytest.mark.parametrize(
    "line, expected",
    [
        ("f'{f'a.", "global"),  # Nested f-string
        ("3a.", "global"),  # names starting with numbers or other symbols
        ("$).", "global"),  # random things with dot at end
    ],
)
def test_unsupported_completion_context(line, expected):
    """Test unsupported completion context"""
    ip = get_ipython()
    get_context = ip.Completer._determine_completion_context
    result = get_context(line)
    assert result.value == expected, f"Failed on input: '{line}'"


@pytest.mark.parametrize(
    "setup,code,expected,not_expected",
    [
        ('a="str"; b=1', "(a, b.", [".bit_count", ".conjugate"], [".count"]),
        ('a="str"; b=1', "(a, b).", [".count"], [".bit_count", ".capitalize"]),
        ('x="str"; y=1', "x = {1, y.", [".bit_count"], [".count"]),
        ('x="str"; y=1', "x = [1, y.", [".bit_count"], [".count"]),
        ('x="str"; y=1; fun=lambda x:x', "x = fun(1, y.", [".bit_count"], [".count"]),
    ],
)
def test_misc_no_jedi_completions(setup, code, expected, not_expected):
    ip = get_ipython()
    c = ip.Completer
    ip.ex(setup)
    with provisionalcompleter(), jedi_status(False):
        matches = c.all_completions(code)
        assert set(expected) - set(matches) == set(), set(matches)
        assert set(matches).intersection(set(not_expected)) == set()


@pytest.mark.parametrize(
    "code,expected",
    [
        (" (a, b", "b"),
        ("(a, b", "b"),
        ("(a, b)", ""),  # trim always start by trimming
        (" (a, b)", "(a, b)"),
        (" [a, b]", "[a, b]"),
        (" a, b", "b"),
        ("x = {1, y", "y"),
        ("x = [1, y", "y"),
        ("x = fun(1, y", "y"),
        (" assert a", "a"),
    ],
)
def test_trim_expr(code, expected):
    c = get_ipython().Completer
    assert c._trim_expr(code) == expected


@pytest.mark.parametrize(
    "input, expected",
    [
        ["1.234", "1.234"],
        # should match signed numbers
        ["+1", "+1"],
        ["-1", "-1"],
        ["-1.0", "-1.0"],
        ["-1.", "-1."],
        ["+1.", "+1."],
        [".1", ".1"],
        # should not match non-numbers
        ["1..", None],
        ["..", None],
        [".1.", None],
        # should match after comma
        [",1", "1"],
        [", 1", "1"],
        [", .1", ".1"],
        [", +.1", "+.1"],
        # should not match after trailing spaces
        [".1 ", None],
        # some complex cases
        ["0b_0011_1111_0100_1110", "0b_0011_1111_0100_1110"],
        ["0xdeadbeef", "0xdeadbeef"],
        ["0b_1110_0101", "0b_1110_0101"],
        # should not match if in an operation
        ["1 + 1", None],
        [", 1 + 1", None],
    ],
)
def test_match_numeric_literal_for_dict_key(input, expected):
    assert _match_number_in_dict_key_prefix(input) == expected