pytest-language-server 0.22.2

A blazingly fast Language Server Protocol implementation for pytest
Documentation
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
//! Tests for the LanguageServer trait implementation in language_server.rs.
//!
//! Exercises every method in the `LanguageServer for Backend` impl so that
//! the coverage report no longer shows the file at 0%.

#![allow(deprecated)] // For root_path / root_uri fields in InitializeParams

use std::path::PathBuf;
use std::sync::Arc;

use ntest::timeout;
use pytest_language_server::{Backend, FixtureDatabase};
use tower_lsp_server::ls_types::request::GotoImplementationParams;
use tower_lsp_server::ls_types::*;
use tower_lsp_server::{LanguageServer, LspService};

// ── Helpers ───────────────────────────────────────────────────────────────

/// Build a `Backend` backed by the given database and a dummy LSP service.
fn make_backend_with_db(db: Arc<FixtureDatabase>) -> Backend {
    let slot: Arc<std::sync::Mutex<Option<Backend>>> = Arc::new(std::sync::Mutex::new(None));
    let slot_clone = slot.clone();
    let (_svc, _sock) = LspService::new(move |client| {
        let b = Backend::new(client, db.clone());
        *slot_clone.lock().unwrap() = Some(Backend {
            client: b.client.clone(),
            fixture_db: b.fixture_db.clone(),
            workspace_root: b.workspace_root.clone(),
            original_workspace_root: b.original_workspace_root.clone(),
            scan_task: b.scan_task.clone(),
            uri_cache: b.uri_cache.clone(),
            config: b.config.clone(),
        });
        b
    });
    let backend = slot.lock().unwrap().take().expect("backend created");
    backend
}

fn make_backend() -> Backend {
    make_backend_with_db(Arc::new(FixtureDatabase::new()))
}

/// Return a platform-appropriate absolute `PathBuf` under the system temp
/// directory.  Using `std::env::temp_dir()` (rather than a hardcoded
/// `/tmp/…` string) ensures the path is truly absolute on Windows too
/// (Windows paths require a drive letter prefix for `is_absolute()` to
/// return `true`, which `Uri::from_file_path` requires).
fn tfile(subdir: &str, filename: &str) -> PathBuf {
    std::env::temp_dir().join(subdir).join(filename)
}

/// Build a `Uri` from a path under the system temp directory.
///
/// Panics if the path cannot be converted to a URI, which should never
/// happen for a path returned by `std::env::temp_dir().join(…)`.
fn turi(subdir: &str, filename: &str) -> Uri {
    let path = tfile(subdir, filename);
    Uri::from_file_path(&path)
        .unwrap_or_else(|| panic!("Uri::from_file_path failed for {:?}", path))
}

fn pos(line: u32, character: u32) -> Position {
    Position { line, character }
}

fn rng(sl: u32, sc: u32, el: u32, ec: u32) -> Range {
    Range {
        start: pos(sl, sc),
        end: pos(el, ec),
    }
}

fn tdp(uri: Uri, line: u32, character: u32) -> TextDocumentPositionParams {
    TextDocumentPositionParams {
        text_document: TextDocumentIdentifier { uri },
        position: pos(line, character),
    }
}

fn wdp() -> WorkDoneProgressParams {
    WorkDoneProgressParams {
        work_done_token: None,
    }
}

fn prp() -> PartialResultParams {
    PartialResultParams {
        partial_result_token: None,
    }
}

// ── initialize ────────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_initialize_no_workspace_root_returns_capabilities() {
    let backend = make_backend();
    let params = InitializeParams::default();

    let result = backend.initialize(params).await;
    assert!(result.is_ok(), "initialize should succeed");

    let init = result.unwrap();
    assert_eq!(
        init.server_info.as_ref().unwrap().name,
        "pytest-language-server"
    );

    // Workspace root must remain unset
    assert!(
        backend.workspace_root.read().await.is_none(),
        "workspace_root should stay None when no root URI given"
    );
}

#[tokio::test]
#[timeout(30000)]
async fn test_initialize_no_workspace_logs_warning() {
    // Same as above but also checks the warning branch is exercised.
    let backend = make_backend();
    let result = backend.initialize(InitializeParams::default()).await;
    assert!(result.is_ok());
    let caps = &result.unwrap().capabilities;
    assert!(caps.definition_provider.is_some());
    assert!(caps.hover_provider.is_some());
    assert!(caps.references_provider.is_some());
    assert!(caps.completion_provider.is_some());
}

#[tokio::test]
#[timeout(30000)]
async fn test_initialize_with_workspace_folders_sets_root() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let backend = make_backend();

    let root_uri = Uri::from_file_path(tmp.path()).expect("root URI");
    let params = InitializeParams {
        workspace_folders: Some(vec![WorkspaceFolder {
            uri: root_uri,
            name: "test_ws".to_string(),
        }]),
        ..Default::default()
    };

    let result = backend.initialize(params).await;
    assert!(
        result.is_ok(),
        "initialize with workspace_folders should succeed"
    );

    // Root should be stored
    assert!(
        backend.workspace_root.read().await.is_some(),
        "workspace_root should be set after initialize with workspace_folders"
    );

    // Give the background scan task a moment to run (empty dir, near-instant)
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}

#[tokio::test]
#[timeout(30000)]
async fn test_initialize_with_deprecated_root_uri_sets_root() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let backend = make_backend();

    let root_uri = Uri::from_file_path(tmp.path()).expect("root URI");
    let params = InitializeParams {
        root_uri: Some(root_uri),
        ..Default::default()
    };

    let result = backend.initialize(params).await;
    assert!(result.is_ok());
    assert!(
        backend.workspace_root.read().await.is_some(),
        "workspace_root should be set via deprecated root_uri"
    );
}

#[tokio::test]
#[timeout(30000)]
async fn test_initialize_workspace_folders_takes_priority_over_root_uri() {
    let tmp_wf = tempfile::tempdir().expect("workspace_folders dir");
    let tmp_ru = tempfile::tempdir().expect("root_uri dir");
    let backend = make_backend();

    let wf_uri = Uri::from_file_path(tmp_wf.path()).unwrap();
    let ru_uri = Uri::from_file_path(tmp_ru.path()).unwrap();

    let params = InitializeParams {
        workspace_folders: Some(vec![WorkspaceFolder {
            uri: wf_uri.clone(),
            name: "wf".to_string(),
        }]),
        root_uri: Some(ru_uri),
        ..Default::default()
    };

    let result = backend.initialize(params).await;
    assert!(result.is_ok());

    // workspace_folders wins: canonical root must match tmp_wf, not tmp_ru
    let root = backend.workspace_root.read().await;
    let stored = root.as_ref().expect("root should be set");
    let canonical_wf = tmp_wf.path().canonicalize().unwrap();
    assert_eq!(stored, &canonical_wf, "workspace_folders URI should win");
}

#[tokio::test]
#[timeout(30000)]
async fn test_initialize_capabilities_all_providers_present() {
    let backend = make_backend();
    let result = backend
        .initialize(InitializeParams::default())
        .await
        .unwrap();
    let caps = &result.capabilities;

    // All providers advertised in the impl
    assert!(caps.definition_provider.is_some());
    assert!(caps.hover_provider.is_some());
    assert!(caps.references_provider.is_some());
    assert!(caps.text_document_sync.is_some());
    assert!(caps.code_action_provider.is_some());
    assert!(caps.completion_provider.is_some());
    assert!(caps.document_symbol_provider.is_some());
    assert!(caps.workspace_symbol_provider.is_some());
    assert!(caps.code_lens_provider.is_some());
    assert!(caps.inlay_hint_provider.is_some());
    assert!(caps.implementation_provider.is_some());
    assert!(caps.call_hierarchy_provider.is_some());
}

#[tokio::test]
#[timeout(30000)]
async fn test_initialize_server_info_includes_version() {
    let backend = make_backend();
    let result = backend
        .initialize(InitializeParams::default())
        .await
        .unwrap();
    let info = result.server_info.expect("server_info should be present");
    assert!(!info.name.is_empty());
    assert!(info.version.is_some(), "server version should be reported");
}

#[tokio::test]
#[timeout(30000)]
async fn test_initialize_with_workspace_stores_original_root() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let backend = make_backend();

    let root_uri = Uri::from_file_path(tmp.path()).expect("root URI");
    let params = InitializeParams {
        workspace_folders: Some(vec![WorkspaceFolder {
            uri: root_uri,
            name: "ws".to_string(),
        }]),
        ..Default::default()
    };

    backend.initialize(params).await.unwrap();

    // Both the canonical root and the original root should be stored
    assert!(backend.workspace_root.read().await.is_some());
    assert!(backend.original_workspace_root.read().await.is_some());
}

#[tokio::test]
#[timeout(30000)]
async fn test_initialize_background_scan_handle_stored() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let backend = make_backend();

    let root_uri = Uri::from_file_path(tmp.path()).expect("root URI");
    let params = InitializeParams {
        workspace_folders: Some(vec![WorkspaceFolder {
            uri: root_uri,
            name: "ws".to_string(),
        }]),
        ..Default::default()
    };

    backend.initialize(params).await.unwrap();

    // A background scan task handle should have been stored
    let handle = backend.scan_task.lock().await;
    assert!(handle.is_some(), "scan task handle should be stored");
}

// ── initialized ───────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_initialized_does_not_panic() {
    let backend = make_backend();
    // register_capability will fail on the mock client, but must not panic
    backend.initialized(InitializedParams {}).await;
}

// ── did_open ──────────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_did_open_registers_fixture_in_db() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let file_uri = turi("test_ls_open", "conftest.py");
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: file_uri,
                language_id: "python".to_string(),
                version: 1,
                text: "import pytest\n\n@pytest.fixture\ndef open_fixture():\n    return 42\n"
                    .to_string(),
            },
        })
        .await;

    assert!(
        db.definitions.contains_key("open_fixture"),
        "fixture should be registered after did_open"
    );
}

#[tokio::test]
#[timeout(30000)]
async fn test_did_open_populates_uri_cache() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let file_uri = turi("test_ls_open_cache", "conftest.py");
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: file_uri,
                language_id: "python".to_string(),
                version: 1,
                text: "import pytest\n".to_string(),
            },
        })
        .await;

    assert!(
        !backend.uri_cache.is_empty(),
        "URI cache should have an entry after did_open"
    );
}

#[tokio::test]
#[timeout(30000)]
async fn test_did_open_with_diagnostics() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // A test that uses an undeclared fixture – should trigger diagnostic publishing
    let file_uri = turi("test_ls_open_diag", "test_example.py");
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: file_uri,
                language_id: "python".to_string(),
                version: 1,
                text: "def test_something():\n    result = missing_fixture\n".to_string(),
            },
        })
        .await;
    // Should not panic even when diagnostics are published via a mock client
}

// ── did_change ────────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_did_change_updates_fixture_db() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let file_uri = turi("test_ls_change", "conftest.py");

    // Open with first fixture
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: file_uri.clone(),
                language_id: "python".to_string(),
                version: 1,
                text: "import pytest\n\n@pytest.fixture\ndef old_fixture():\n    return 1\n"
                    .to_string(),
            },
        })
        .await;
    assert!(db.definitions.contains_key("old_fixture"));

    // Change to a new fixture
    backend
        .did_change(DidChangeTextDocumentParams {
            text_document: VersionedTextDocumentIdentifier {
                uri: file_uri.clone(),
                version: 2,
            },
            content_changes: vec![TextDocumentContentChangeEvent {
                range: None,
                range_length: None,
                text: "import pytest\n\n@pytest.fixture\ndef new_fixture():\n    return 2\n"
                    .to_string(),
            }],
        })
        .await;

    assert!(
        db.definitions.contains_key("new_fixture"),
        "new_fixture should be registered after did_change"
    );
}

#[tokio::test]
#[timeout(30000)]
async fn test_did_change_with_empty_content_changes_is_noop() {
    let backend = make_backend();
    let file_uri = turi("test_ls_change_empty", "conftest.py");

    // Should not panic with no content changes
    backend
        .did_change(DidChangeTextDocumentParams {
            text_document: VersionedTextDocumentIdentifier {
                uri: file_uri,
                version: 1,
            },
            content_changes: vec![],
        })
        .await;
}

#[tokio::test]
#[timeout(30000)]
async fn test_did_change_triggers_inlay_hint_refresh() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let file_uri = turi("test_ls_change_hint", "conftest.py");

    // Open first
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: file_uri.clone(),
                language_id: "python".to_string(),
                version: 1,
                text: "import pytest\n\n@pytest.fixture\ndef hint_fixture():\n    return 1\n"
                    .to_string(),
            },
        })
        .await;

    // Then change – this also calls inlay_hint_refresh on the mock client
    backend
        .did_change(DidChangeTextDocumentParams {
            text_document: VersionedTextDocumentIdentifier {
                uri: file_uri,
                version: 2,
            },
            content_changes: vec![TextDocumentContentChangeEvent {
                range: None,
                range_length: None,
                text: "import pytest\n\n@pytest.fixture\ndef hint_fixture_v2():\n    return 2\n"
                    .to_string(),
            }],
        })
        .await;
    // Mock client absorbs inlay_hint_refresh error silently – just must not panic
}

// ── did_change_watched_files ──────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_did_change_watched_files_created_init_py_triggers_reanalysis() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Put a fixture file under the directory where __init__.py will be created.
    // Both paths are built from the same temp subdir so starts_with() works.
    let fixture_path = tfile("test_ls_wf_created", "conftest.py");
    db.analyze_file(
        fixture_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef wf_fixture():\n    return 42\n",
    );
    assert!(db.definitions.contains_key("wf_fixture"));

    let init_uri = turi("test_ls_wf_created", "__init__.py");
    backend
        .did_change_watched_files(DidChangeWatchedFilesParams {
            changes: vec![FileEvent {
                uri: init_uri,
                typ: FileChangeType::CREATED,
            }],
        })
        .await;
    // Should not panic; fixture is re-analysed from cache
}

#[tokio::test]
#[timeout(30000)]
async fn test_did_change_watched_files_deleted_init_py_triggers_reanalysis() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let fixture_path = tfile("test_ls_wf_deleted", "conftest.py");
    db.analyze_file(
        fixture_path,
        "import pytest\n\n@pytest.fixture\ndef del_fixture():\n    return 1\n",
    );

    let init_uri = turi("test_ls_wf_deleted", "__init__.py");
    backend
        .did_change_watched_files(DidChangeWatchedFilesParams {
            changes: vec![FileEvent {
                uri: init_uri,
                typ: FileChangeType::DELETED,
            }],
        })
        .await;
}

#[tokio::test]
#[timeout(30000)]
async fn test_did_change_watched_files_skips_changed_events() {
    let backend = make_backend();

    // FileChangeType::CHANGED should be skipped – no re-analysis
    let init_uri = turi("test_ls_wf_changed", "__init__.py");
    backend
        .did_change_watched_files(DidChangeWatchedFilesParams {
            changes: vec![FileEvent {
                uri: init_uri,
                typ: FileChangeType::CHANGED,
            }],
        })
        .await;
}

#[tokio::test]
#[timeout(30000)]
async fn test_did_change_watched_files_empty_changes_no_refresh() {
    let backend = make_backend();

    // Empty changes → inlay_hint_refresh must NOT be called (would error on mock)
    backend
        .did_change_watched_files(DidChangeWatchedFilesParams { changes: vec![] })
        .await;
}

#[tokio::test]
#[timeout(30000)]
async fn test_did_change_watched_files_republishes_diagnostics_for_cached_uri() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Analyse a fixture file using a temp-dir path so the directory structure
    // is consistent across platforms.
    let fixture_path = tfile("test_ls_wf_diag", "conftest.py");
    db.analyze_file(
        fixture_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef diag_fixture():\n    return 99\n",
    );

    // Pre-populate URI cache so the diagnostic re-publish branch is exercised.
    let fixture_uri = turi("test_ls_wf_diag", "conftest.py");
    backend.uri_cache.insert(fixture_path, fixture_uri);

    let init_uri = turi("test_ls_wf_diag", "__init__.py");
    backend
        .did_change_watched_files(DidChangeWatchedFilesParams {
            changes: vec![FileEvent {
                uri: init_uri,
                typ: FileChangeType::CREATED,
            }],
        })
        .await;
}

#[tokio::test]
#[timeout(30000)]
async fn test_did_change_watched_files_multiple_events() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Two independent subdirectories, each with a fixture file and a
    // corresponding __init__.py event.
    let path_a = tfile("test_ls_wf_multi_a", "conftest.py");
    let path_b = tfile("test_ls_wf_multi_b", "conftest.py");
    db.analyze_file(
        path_a,
        "import pytest\n\n@pytest.fixture\ndef fixture_a():\n    pass\n",
    );
    db.analyze_file(
        path_b,
        "import pytest\n\n@pytest.fixture\ndef fixture_b():\n    pass\n",
    );

    let params = DidChangeWatchedFilesParams {
        changes: vec![
            FileEvent {
                uri: turi("test_ls_wf_multi_a", "__init__.py"),
                typ: FileChangeType::CREATED,
            },
            FileEvent {
                uri: turi("test_ls_wf_multi_b", "__init__.py"),
                typ: FileChangeType::DELETED,
            },
        ],
    };
    backend.did_change_watched_files(params).await;
}

// ── did_close ─────────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_did_close_clears_uri_cache() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let file_uri = turi("test_ls_close", "conftest.py");

    // Open to populate caches
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: file_uri.clone(),
                language_id: "python".to_string(),
                version: 1,
                text: "import pytest\n".to_string(),
            },
        })
        .await;
    assert!(
        !backend.uri_cache.is_empty(),
        "URI cache should be populated"
    );

    backend
        .did_close(DidCloseTextDocumentParams {
            text_document: TextDocumentIdentifier { uri: file_uri },
        })
        .await;

    assert!(
        backend.uri_cache.is_empty(),
        "URI cache should be cleared after did_close"
    );
}

#[tokio::test]
#[timeout(30000)]
async fn test_did_close_unknown_file_does_not_panic() {
    let backend = make_backend();

    // Closing a file that was never opened must be safe
    backend
        .did_close(DidCloseTextDocumentParams {
            text_document: TextDocumentIdentifier {
                uri: turi("test_ls_close_unknown", "never_opened.py"),
            },
        })
        .await;
}

// ── goto_definition ───────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_goto_definition_returns_ok_on_empty_db() {
    let backend = make_backend();
    let result = backend
        .goto_definition(GotoDefinitionParams {
            text_document_position_params: tdp(turi("test_ls_gotodef", "test_file.py"), 0, 0),
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;
    assert!(result.is_ok());
    assert!(result.unwrap().is_none());
}

#[tokio::test]
#[timeout(30000)]
async fn test_goto_definition_resolves_fixture() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let conftest_path = tfile("test_ls_gotodef2", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef my_fixture():\n    return 1\n",
    );

    let test_path = tfile("test_ls_gotodef2", "test_example.py");
    db.analyze_file(
        test_path.clone(),
        "def test_it(my_fixture):\n    assert my_fixture == 1\n",
    );
    // Pre-register URI cache so path_to_uri works
    let conftest_uri = turi("test_ls_gotodef2", "conftest.py");
    backend.uri_cache.insert(conftest_path, conftest_uri);

    let result = backend
        .goto_definition(GotoDefinitionParams {
            text_document_position_params: tdp(
                turi("test_ls_gotodef2", "test_example.py"),
                0,  // line 0 (LSP) = line 1 (1-indexed): "def test_it(my_fixture):"
                12, // character inside "my_fixture"
            ),
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;
    assert!(result.is_ok());
}

// ── goto_implementation ───────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_goto_implementation_returns_ok_on_empty_db() {
    let backend = make_backend();
    let result = backend
        .goto_implementation(GotoImplementationParams {
            text_document_position_params: tdp(turi("test_ls_impl", "test_file.py"), 0, 0),
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;
    assert!(result.is_ok());
    assert!(result.unwrap().is_none());
}

/// Helper: unwrap a `GotoImplementationResponse::Scalar` to a `Location`.
fn scalar_location(
    resp: tower_lsp_server::ls_types::request::GotoImplementationResponse,
) -> Location {
    use tower_lsp_server::ls_types::request::GotoImplementationResponse;
    match resp {
        GotoImplementationResponse::Scalar(loc) => loc,
        _ => panic!(
            "expected GotoImplementationResponse::Scalar, got {:?}",
            resp
        ),
    }
}

#[tokio::test]
#[timeout(30000)]
async fn test_goto_implementation_generator_fixture_returns_yield_line() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Generator fixture with `yield value` on line 6 (1-indexed),
    // which is LSP line 5 (0-indexed).
    let conftest_path = tfile("test_ls_impl_yield", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef gen_fixture():\n    value = 1\n    yield value\n",
    );
    let conftest_uri = turi("test_ls_impl_yield", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path, conftest_uri.clone());

    // Click on the fixture name (line 3).
    let result = backend
        .goto_implementation(GotoImplementationParams {
            text_document_position_params: tdp(conftest_uri.clone(), 3, 6),
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await
        .unwrap()
        .expect("should resolve");

    let loc = scalar_location(result);
    assert_eq!(loc.uri, conftest_uri);
    // `yield value` is on line index 5 (0-indexed).
    assert_eq!(loc.range.start.line, 5);
}

#[tokio::test]
#[timeout(30000)]
async fn test_goto_implementation_non_generator_falls_back_to_definition() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let conftest_path = tfile("test_ls_impl_return", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef ret_fixture():\n    return 1\n",
    );
    let conftest_uri = turi("test_ls_impl_return", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path, conftest_uri.clone());

    let result = backend
        .goto_implementation(GotoImplementationParams {
            text_document_position_params: tdp(conftest_uri.clone(), 3, 6),
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await
        .unwrap()
        .expect("should resolve");
    let loc = scalar_location(result);
    assert_eq!(loc.uri, conftest_uri);
    // Returns the definition line (line 3 0-indexed).
    assert_eq!(loc.range.start.line, 3);
}

#[tokio::test]
#[timeout(30000)]
async fn test_goto_implementation_from_usage_resolves_to_yield() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let conftest_path = tfile("test_ls_impl_from_usage", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef gen_fixture():\n    yield 42\n",
    );
    let conftest_uri = turi("test_ls_impl_from_usage", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path, conftest_uri.clone());

    let test_path = tfile("test_ls_impl_from_usage", "test_example.py");
    db.analyze_file(test_path.clone(), "def test_one(gen_fixture):\n    pass\n");
    let test_uri = turi("test_ls_impl_from_usage", "test_example.py");
    backend.uri_cache.insert(test_path, test_uri.clone());

    let result = backend
        .goto_implementation(GotoImplementationParams {
            text_document_position_params: tdp(test_uri, 0, 13),
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await
        .unwrap()
        .expect("should resolve");
    let loc = scalar_location(result);
    assert_eq!(loc.uri, conftest_uri);
    // yield 42 is on line 4 (0-indexed).
    assert_eq!(loc.range.start.line, 4);
}

// ── hover ─────────────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_hover_returns_none_on_empty_file() {
    let backend = make_backend();
    let result = backend
        .hover(HoverParams {
            text_document_position_params: tdp(turi("test_ls_hover", "test.py"), 0, 0),
            work_done_progress_params: wdp(),
        })
        .await;
    assert!(result.is_ok());
    assert!(result.unwrap().is_none(), "no hover for unknown position");
}

#[tokio::test]
#[timeout(30000)]
async fn test_hover_returns_content_for_known_fixture() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let conftest_path = tfile("test_ls_hover2", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef hover_fixture():\n    \"\"\"Hover docstring.\"\"\"\n    return 1\n",
    );
    let conftest_uri = turi("test_ls_hover2", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path.clone(), conftest_uri.clone());

    let test_path = tfile("test_ls_hover2", "test_example.py");
    db.analyze_file(test_path, "def test_it(hover_fixture):\n    pass\n");

    let result = backend
        .hover(HoverParams {
            text_document_position_params: tdp(turi("test_ls_hover2", "test_example.py"), 0, 12),
            work_done_progress_params: wdp(),
        })
        .await;
    assert!(result.is_ok());
}

// ── references ────────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_references_returns_ok_on_empty_db() {
    let backend = make_backend();
    let result = backend
        .references(ReferenceParams {
            text_document_position: tdp(turi("test_ls_refs", "test.py"), 0, 0),
            context: ReferenceContext {
                include_declaration: true,
            },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;
    assert!(result.is_ok());
}

/// Helper: call references and unwrap the double-Option into Vec<Location>.
async fn get_refs(backend: &Backend, uri: Uri, line: u32, character: u32) -> Vec<Location> {
    let result = backend
        .references(ReferenceParams {
            text_document_position: tdp(uri, line, character),
            context: ReferenceContext {
                include_declaration: true,
            },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;
    assert!(result.is_ok(), "references must not return error");
    result.unwrap().unwrap_or_default()
}

#[tokio::test]
#[timeout(30000)]
async fn test_references_returns_definition_and_usages() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Seed conftest with a fixture definition
    let conftest_path = tfile("test_ls_refs_happy", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef my_fixture():\n    return 1\n",
    );
    let conftest_uri = turi("test_ls_refs_happy", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path.clone(), conftest_uri.clone());

    // Seed a test file with two usages
    let test_path = tfile("test_ls_refs_happy", "test_example.py");
    db.analyze_file(
        test_path.clone(),
        "def test_one(my_fixture):\n    pass\n\ndef test_two(my_fixture):\n    pass\n",
    );
    let test_uri = turi("test_ls_refs_happy", "test_example.py");
    backend.uri_cache.insert(test_path, test_uri.clone());

    // Click on the fixture name in test_one (line 0, char 13)
    let locations = get_refs(&backend, test_uri.clone(), 0, 13).await;

    // Should include the definition + both usages
    assert_eq!(
        locations.len(),
        3,
        "expected definition + 2 usages, got {:?}",
        locations
    );
    // First location is the definition, in the conftest file
    assert_eq!(locations[0].uri, conftest_uri);
    // The remaining locations are the usages in the test file
    let usage_uris: Vec<&Uri> = locations.iter().skip(1).map(|l| &l.uri).collect();
    assert!(usage_uris.iter().all(|u| **u == test_uri));
}

#[tokio::test]
#[timeout(30000)]
async fn test_references_from_definition_line() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let conftest_path = tfile("test_ls_refs_def_line", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef my_fixture():\n    return 1\n",
    );
    let conftest_uri = turi("test_ls_refs_def_line", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path.clone(), conftest_uri.clone());

    let test_path = tfile("test_ls_refs_def_line", "test_example.py");
    db.analyze_file(test_path.clone(), "def test_one(my_fixture):\n    pass\n");
    let test_uri = turi("test_ls_refs_def_line", "test_example.py");
    backend.uri_cache.insert(test_path, test_uri.clone());

    // Click directly on the `def my_fixture` line (line 3 in conftest, 0-indexed)
    // exercises the `get_definition_at_line` fallback branch.
    let locations = get_refs(&backend, conftest_uri.clone(), 3, 6).await;

    assert!(
        !locations.is_empty(),
        "should return references when clicking on definition line"
    );
    // The first location is the definition itself (from conftest).
    assert_eq!(locations[0].uri, conftest_uri);
    // The remaining locations should include the usage in the test file.
    assert!(
        locations.iter().any(|l| l.uri == test_uri),
        "should include usage in test file"
    );
}

#[tokio::test]
#[timeout(30000)]
async fn test_references_self_referencing_fixture_skips_def_line() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Parent conftest defines `cli_runner`
    let parent_path = tfile("test_ls_refs_self", "conftest.py");
    db.analyze_file(
        parent_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef cli_runner():\n    return \"parent\"\n",
    );
    let parent_uri = turi("test_ls_refs_self", "conftest.py");
    backend
        .uri_cache
        .insert(parent_path.clone(), parent_uri.clone());

    // Child conftest overrides with self-referencing fixture
    let child_path = tfile("test_ls_refs_self/tests", "conftest.py");
    db.analyze_file(
        child_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef cli_runner(cli_runner):\n    return cli_runner\n",
    );
    let child_uri = turi("test_ls_refs_self/tests", "conftest.py");
    backend
        .uri_cache
        .insert(child_path.clone(), child_uri.clone());

    // Click on the child `cli_runner` definition (line 3 in child conftest).
    // The child's own parameter `cli_runner` sits on that same line, so the
    // returned locations must not contain a duplicate entry for the def line.
    let locations = get_refs(&backend, child_uri.clone(), 3, 6).await;

    // Should return at least the definition; the parameter reference on the
    // same line as the child definition should be filtered out to avoid
    // a duplicate with the definition entry.
    assert!(!locations.is_empty());
    assert_eq!(locations[0].uri, child_uri);
    // No duplicate: only one location should have the same uri+line as the def.
    let def_line = locations[0].range.start.line;
    let same_line_count = locations
        .iter()
        .filter(|l| l.uri == child_uri && l.range.start.line == def_line)
        .count();
    assert_eq!(
        same_line_count, 1,
        "def-line duplicate should be filtered; got {:?}",
        locations
    );
}

#[tokio::test]
#[timeout(30000)]
async fn test_references_no_fixture_at_position_returns_none() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let test_path = tfile("test_ls_refs_no_fixture", "test_example.py");
    db.analyze_file(test_path.clone(), "def test_one():\n    pass\n");
    let test_uri = turi("test_ls_refs_no_fixture", "test_example.py");
    backend.uri_cache.insert(test_path, test_uri.clone());

    // Click on the `def` keyword - no fixture there.
    let result = backend
        .references(ReferenceParams {
            text_document_position: tdp(test_uri, 0, 1),
            context: ReferenceContext {
                include_declaration: true,
            },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;
    assert!(result.is_ok());
    assert!(
        result.unwrap().is_none(),
        "no fixture at cursor should return None"
    );
}

// ── completion ────────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_completion_returns_ok() {
    let backend = make_backend();
    let result = backend
        .completion(CompletionParams {
            text_document_position: tdp(turi("test_ls_compl", "test.py"), 0, 0),
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
            context: None,
        })
        .await;
    assert!(result.is_ok());
}

// ── code_action ───────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_code_action_returns_ok_no_diagnostics() {
    let backend = make_backend();
    let result = backend
        .code_action(CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: turi("test_ls_ca", "test.py"),
            },
            range: rng(0, 0, 0, 0),
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;
    assert!(result.is_ok());
}

// ── document_symbol ───────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_document_symbol_returns_ok_for_unknown_file() {
    let backend = make_backend();
    let result = backend
        .document_symbol(DocumentSymbolParams {
            text_document: TextDocumentIdentifier {
                uri: turi("test_ls_docsym", "test.py"),
            },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;
    assert!(result.is_ok());
}

#[tokio::test]
#[timeout(30000)]
async fn test_document_symbol_returns_symbols_for_known_file() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let file_path = tfile("test_ls_docsym2", "conftest.py");
    db.analyze_file(
        file_path,
        "import pytest\n\n@pytest.fixture\ndef doc_fixture():\n    return 1\n",
    );

    let result = backend
        .document_symbol(DocumentSymbolParams {
            text_document: TextDocumentIdentifier {
                uri: turi("test_ls_docsym2", "conftest.py"),
            },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;
    assert!(result.is_ok());
}

// ── symbol (workspace symbol) ─────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_symbol_wraps_result_in_flat_response() {
    let db = Arc::new(FixtureDatabase::new());
    let fixture_path = tfile("test_ls_wssym", "conftest.py");
    db.analyze_file(
        fixture_path,
        "import pytest\n\n@pytest.fixture\ndef ws_sym_fixture():\n    return 1\n",
    );
    let backend = make_backend_with_db(db);

    let result = backend
        .symbol(WorkspaceSymbolParams {
            query: "ws_sym".to_string(),
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;

    assert!(result.is_ok());
    // When results exist, the response must be wrapped in Flat
    if let Ok(Some(WorkspaceSymbolResponse::Flat(symbols))) = result {
        assert!(!symbols.is_empty(), "should find ws_sym_fixture");
    }
}

#[tokio::test]
#[timeout(30000)]
async fn test_symbol_no_results_returns_none_wrapped() {
    let backend = make_backend();
    let result = backend
        .symbol(WorkspaceSymbolParams {
            query: "definitely_does_not_exist_xyzzy".to_string(),
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;
    assert!(result.is_ok());
}

// ── code_lens ─────────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_code_lens_returns_ok() {
    let backend = make_backend();
    let result = backend
        .code_lens(CodeLensParams {
            text_document: TextDocumentIdentifier {
                uri: turi("test_ls_lens", "conftest.py"),
            },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;
    assert!(result.is_ok());
}

#[tokio::test]
#[timeout(30000)]
async fn test_code_lens_returns_usage_count_per_fixture() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Two fixtures in conftest.
    let conftest_path = tfile("test_ls_lens_count", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef fixture_a():\n    return 1\n\n@pytest.fixture\ndef fixture_b():\n    return 2\n",
    );
    let conftest_uri = turi("test_ls_lens_count", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path, conftest_uri.clone());

    // Three usages of fixture_a and one of fixture_b.
    let test_path = tfile("test_ls_lens_count", "test_example.py");
    db.analyze_file(
        test_path.clone(),
        "def test_one(fixture_a):\n    pass\n\ndef test_two(fixture_a):\n    pass\n\ndef test_three(fixture_a):\n    pass\n\ndef test_four(fixture_b):\n    pass\n",
    );
    let test_uri = turi("test_ls_lens_count", "test_example.py");
    backend.uri_cache.insert(test_path, test_uri);

    let lenses = backend
        .code_lens(CodeLensParams {
            text_document: TextDocumentIdentifier { uri: conftest_uri },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await
        .unwrap()
        .expect("should return lenses");

    assert_eq!(lenses.len(), 2);
    let titles: Vec<String> = lenses
        .iter()
        .filter_map(|l| l.command.as_ref().map(|c| c.title.clone()))
        .collect();
    assert!(titles.iter().any(|t| t == "3 usages"));
    assert!(titles.iter().any(|t| t == "1 usage"));
}

#[tokio::test]
#[timeout(30000)]
async fn test_code_lens_skips_fixtures_from_other_files() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Fixture in one conftest
    let other_path = tfile("test_ls_lens_other", "other_conftest.py");
    db.analyze_file(
        other_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef only_here():\n    return 1\n",
    );
    backend
        .uri_cache
        .insert(other_path, turi("test_ls_lens_other", "other_conftest.py"));

    // Request code lenses on a different file — should return none.
    let empty_path = tfile("test_ls_lens_other", "empty_conftest.py");
    db.analyze_file(empty_path.clone(), "import pytest\n");
    let empty_uri = turi("test_ls_lens_other", "empty_conftest.py");
    backend.uri_cache.insert(empty_path, empty_uri.clone());

    let result = backend
        .code_lens(CodeLensParams {
            text_document: TextDocumentIdentifier { uri: empty_uri },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await
        .unwrap();
    assert!(result.is_none(), "no fixtures in this file → None");
}

#[tokio::test]
#[timeout(30000)]
async fn test_code_lens_skips_third_party_fixtures() {
    use pytest_language_server::FixtureDefinition;

    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let conftest_path = tfile("test_ls_lens_3p", "conftest.py");
    // Manually insert a third-party fixture definition so we can assert it is skipped.
    db.definitions.insert(
        "third_party_fx".to_string(),
        vec![FixtureDefinition {
            name: "third_party_fx".to_string(),
            file_path: conftest_path.clone(),
            line: 4,
            end_line: 5,
            start_char: 4,
            end_char: 18,
            is_third_party: true,
            ..Default::default()
        }],
    );
    let conftest_uri = turi("test_ls_lens_3p", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path, conftest_uri.clone());

    let result = backend
        .code_lens(CodeLensParams {
            text_document: TextDocumentIdentifier { uri: conftest_uri },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await
        .unwrap();
    assert!(
        result.is_none(),
        "third-party fixtures should be filtered out, got {:?}",
        result
    );
}

// ── inlay_hint ────────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_inlay_hint_returns_ok() {
    let backend = make_backend();
    let result = backend
        .inlay_hint(InlayHintParams {
            text_document: TextDocumentIdentifier {
                uri: turi("test_ls_inlay", "test.py"),
            },
            range: rng(0, 0, 100, 0),
            work_done_progress_params: wdp(),
        })
        .await;
    assert!(result.is_ok());
}

// Helper: open a file through the LSP did_open notification so that both
// `file_cache` and `usages` are populated for `handle_inlay_hint`.
async fn open_file(backend: &Backend, uri: Uri, text: &str) {
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "python".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;
}

/// Call `backend.inlay_hint` and unwrap the double-`Option` result,
/// returning an empty `Vec` when the inner `Option` is `None`.
async fn get_hints(backend: &Backend, uri: Uri, range: Range) -> Vec<InlayHint> {
    let result = backend
        .inlay_hint(InlayHintParams {
            text_document: TextDocumentIdentifier { uri },
            range,
            work_done_progress_params: wdp(),
        })
        .await;
    assert!(result.is_ok(), "inlay_hint must not return an error");
    result.unwrap().unwrap_or_default()
}

// ── Happy path: one hint generated ────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_inlay_hint_generates_hint_for_fixture_with_return_type() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Conftest: typed fixture
    open_file(
        &backend,
        turi("test_ih_gen", "conftest.py"),
        "import pytest\n\n@pytest.fixture\ndef my_fixture() -> int:\n    return 42\n",
    )
    .await;

    // Test file: one unannotated parameter
    open_file(
        &backend,
        turi("test_ih_gen", "test_foo.py"),
        "def test_foo(my_fixture):\n    pass\n",
    )
    .await;

    let hints = get_hints(
        &backend,
        turi("test_ih_gen", "test_foo.py"),
        rng(0, 0, 10, 0),
    )
    .await;

    assert_eq!(hints.len(), 1, "Should return exactly one hint");
    match &hints[0].label {
        InlayHintLabel::String(label) => assert_eq!(label, ": int"),
        _ => panic!("Expected String label"),
    }
    assert_eq!(hints[0].kind, Some(InlayHintKind::TYPE));
    // Tooltip should mention the fixture name and the type
    if let Some(InlayHintTooltip::String(tooltip)) = &hints[0].tooltip {
        assert!(tooltip.contains("my_fixture"));
        assert!(tooltip.contains("int"));
    } else {
        panic!("Expected String tooltip");
    }
    assert_eq!(hints[0].padding_left, Some(false));
    assert_eq!(hints[0].padding_right, Some(false));
}

// ── Early return when fixture_map is empty ────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_inlay_hint_empty_when_no_fixtures_have_return_type() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Conftest: fixture WITHOUT a return-type annotation
    open_file(
        &backend,
        turi("test_ih_no_rt", "conftest.py"),
        "import pytest\n\n@pytest.fixture\ndef my_fixture():\n    return 42\n",
    )
    .await;

    open_file(
        &backend,
        turi("test_ih_no_rt", "test_foo.py"),
        "def test_foo(my_fixture):\n    pass\n",
    )
    .await;

    let hints = get_hints(
        &backend,
        turi("test_ih_no_rt", "test_foo.py"),
        rng(0, 0, 10, 0),
    )
    .await;

    assert!(
        hints.is_empty(),
        "Should return no hints when no fixture has a return type"
    );
}

// ── Usage outside the requested range is filtered ─────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_inlay_hint_filters_usage_outside_range() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    open_file(
        &backend,
        turi("test_ih_range", "conftest.py"),
        "import pytest\n\n@pytest.fixture\ndef my_fixture() -> int:\n    return 42\n",
    )
    .await;

    // Test function is on LSP line 2 (1-based internal line 3)
    open_file(
        &backend,
        turi("test_ih_range", "test_foo.py"),
        "\n\ndef test_foo(my_fixture):\n    pass\n",
    )
    .await;

    // Request a range that ends before the test function (lines 0-1 only)
    let hints = get_hints(
        &backend,
        turi("test_ih_range", "test_foo.py"),
        rng(0, 0, 1, 0),
    )
    .await;

    assert!(
        hints.is_empty(),
        "Should return no hints when the range does not cover the test function"
    );
}

// ── Already-annotated parameter is skipped ────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_inlay_hint_skips_already_annotated_param() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    open_file(
        &backend,
        turi("test_ih_ann", "conftest.py"),
        "import pytest\n\n@pytest.fixture\ndef my_fixture() -> int:\n    return 42\n",
    )
    .await;

    // Parameter already has a type annotation — hint must be suppressed
    open_file(
        &backend,
        turi("test_ih_ann", "test_foo.py"),
        "def test_foo(my_fixture: int):\n    pass\n",
    )
    .await;

    let hints = get_hints(
        &backend,
        turi("test_ih_ann", "test_foo.py"),
        rng(0, 0, 10, 0),
    )
    .await;

    assert!(
        hints.is_empty(),
        "Should skip parameters that already carry a type annotation"
    );
}

// ── Type is adapted to the consumer's import style ────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_inlay_hint_adapts_dotted_type_to_consumer_from_import() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Fixture returns `pathlib.Path` (dotted form used in conftest)
    open_file(
        &backend,
        turi("test_ih_adapt", "conftest.py"),
        "import pytest\nimport pathlib\n\n@pytest.fixture\ndef pth() -> pathlib.Path:\n    return pathlib.Path('.')\n",
    )
    .await;

    // Consumer already has `from pathlib import Path` → hint should show `: Path`
    open_file(
        &backend,
        turi("test_ih_adapt", "test_foo.py"),
        "from pathlib import Path\n\ndef test_foo(pth):\n    pass\n",
    )
    .await;

    let hints = get_hints(
        &backend,
        turi("test_ih_adapt", "test_foo.py"),
        rng(0, 0, 10, 0),
    )
    .await;

    assert_eq!(hints.len(), 1, "Should return one hint");
    match &hints[0].label {
        InlayHintLabel::String(label) => assert_eq!(
            label, ": Path",
            "Dotted type should be shortened to match consumer's from-import"
        ),
        _ => panic!("Expected String label"),
    }
}

// ── Multiple fixtures: only typed ones get hints ──────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_inlay_hint_multiple_fixtures_only_typed_get_hints() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    open_file(
        &backend,
        turi("test_ih_multi", "conftest.py"),
        "import pytest\n\n@pytest.fixture\ndef typed_fix() -> str:\n    return 'hi'\n\n@pytest.fixture\ndef untyped_fix():\n    return 42\n",
    )
    .await;

    open_file(
        &backend,
        turi("test_ih_multi", "test_foo.py"),
        "def test_foo(typed_fix, untyped_fix):\n    pass\n",
    )
    .await;

    let hints = get_hints(
        &backend,
        turi("test_ih_multi", "test_foo.py"),
        rng(0, 0, 5, 0),
    )
    .await;

    assert_eq!(
        hints.len(),
        1,
        "Should return a hint only for the typed fixture"
    );
    match &hints[0].label {
        InlayHintLabel::String(label) => assert_eq!(label, ": str"),
        _ => panic!("Expected String label"),
    }
}

// ── File known to the backend but not yet in the usages map ───────────────

#[tokio::test]
#[timeout(30000)]
async fn test_inlay_hint_returns_none_when_file_has_no_usages() {
    // A file URI that resolves to a path but has never been analysed →
    // `usages.get` returns None and `handle_inlay_hint` returns Ok(None).
    let backend = make_backend();
    let result = backend
        .inlay_hint(InlayHintParams {
            text_document: TextDocumentIdentifier {
                uri: turi("test_ih_no_usages", "test_unknown.py"),
            },
            range: rng(0, 0, 100, 0),
            work_done_progress_params: wdp(),
        })
        .await;
    assert!(result.is_ok());
    // Either None or Some(empty) is acceptable — the key check is no panic/error
    let inner = result.unwrap();
    assert!(
        inner.is_none() || inner.unwrap().is_empty(),
        "Un-analysed file should produce no hints"
    );
}

// ── Hint position is at the end of the parameter name ─────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_inlay_hint_position_is_at_end_of_param_name() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    open_file(
        &backend,
        turi("test_ih_pos", "conftest.py"),
        "import pytest\n\n@pytest.fixture\ndef db_fix() -> bool:\n    return True\n",
    )
    .await;

    // `db_fix` starts at column 13 (after `def test_foo(`), length 6
    open_file(
        &backend,
        turi("test_ih_pos", "test_foo.py"),
        "def test_foo(db_fix):\n    pass\n",
    )
    .await;

    let hints = get_hints(
        &backend,
        turi("test_ih_pos", "test_foo.py"),
        rng(0, 0, 5, 0),
    )
    .await;

    assert_eq!(hints.len(), 1);
    // Hint must be on LSP line 0 (first line of the file)
    assert_eq!(hints[0].position.line, 0);
    // Character position must be past the end of `db_fix` (13 + 6 = 19)
    assert_eq!(
        hints[0].position.character, 19,
        "Hint should be placed right after the parameter name"
    );
}

// ── prepare_call_hierarchy ────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_prepare_call_hierarchy_returns_none_on_unknown_position() {
    let backend = make_backend();
    let result = backend
        .prepare_call_hierarchy(CallHierarchyPrepareParams {
            text_document_position_params: tdp(turi("test_ls_callh", "conftest.py"), 0, 0),
            work_done_progress_params: wdp(),
        })
        .await;
    assert!(result.is_ok());
    assert!(result.unwrap().is_none());
}

// ── incoming_calls ────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_incoming_calls_returns_none_for_unknown_fixture() {
    let backend = make_backend();
    let dummy_uri = turi("test_ls_inc", "conftest.py");
    let result = backend
        .incoming_calls(CallHierarchyIncomingCallsParams {
            item: CallHierarchyItem {
                name: "nonexistent_fixture".to_string(),
                kind: SymbolKind::FUNCTION,
                tags: None,
                detail: None,
                uri: dummy_uri,
                range: rng(0, 0, 0, 0),
                selection_range: rng(0, 0, 0, 0),
                data: None,
            },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;
    assert!(result.is_ok());
}

// ── outgoing_calls ────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_outgoing_calls_returns_none_for_unknown_fixture() {
    let backend = make_backend();
    let dummy_uri = turi("test_ls_out", "conftest.py");
    let result = backend
        .outgoing_calls(CallHierarchyOutgoingCallsParams {
            item: CallHierarchyItem {
                name: "nonexistent_fixture".to_string(),
                kind: SymbolKind::FUNCTION,
                tags: None,
                detail: None,
                uri: dummy_uri,
                range: rng(0, 0, 0, 0),
                selection_range: rng(0, 0, 0, 0),
                data: None,
            },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await;
    assert!(result.is_ok());
}

// ── call_hierarchy: real data ─────────────────────────────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_prepare_call_hierarchy_returns_item_for_fixture() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let conftest_path = tfile("test_ls_callh_item", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef my_fixture():\n    return 1\n",
    );
    let conftest_uri = turi("test_ls_callh_item", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path, conftest_uri.clone());

    // Cursor on the fixture name on line 3 (0-indexed).
    let result = backend
        .prepare_call_hierarchy(CallHierarchyPrepareParams {
            text_document_position_params: tdp(conftest_uri.clone(), 3, 6),
            work_done_progress_params: wdp(),
        })
        .await;

    let items = result.unwrap().expect("should return items");
    assert_eq!(items.len(), 1);
    let item = &items[0];
    assert_eq!(item.name, "my_fixture");
    assert_eq!(item.kind, SymbolKind::FUNCTION);
    assert_eq!(item.uri, conftest_uri);
    // Function-scoped fixture → detail is bare "@pytest.fixture".
    assert_eq!(item.detail.as_deref(), Some("@pytest.fixture"));
}

#[tokio::test]
#[timeout(30000)]
async fn test_prepare_call_hierarchy_scoped_fixture_detail() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let conftest_path = tfile("test_ls_callh_scope", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture(scope=\"session\")\ndef my_fixture():\n    return 1\n",
    );
    let conftest_uri = turi("test_ls_callh_scope", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path, conftest_uri.clone());

    let items = backend
        .prepare_call_hierarchy(CallHierarchyPrepareParams {
            text_document_position_params: tdp(conftest_uri, 3, 6),
            work_done_progress_params: wdp(),
        })
        .await
        .unwrap()
        .expect("items");
    assert!(items[0]
        .detail
        .as_deref()
        .unwrap_or_default()
        .contains("scope=\"session\""));
}

#[tokio::test]
#[timeout(30000)]
async fn test_prepare_call_hierarchy_from_usage_resolves_to_definition() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let conftest_path = tfile("test_ls_callh_usage", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef my_fixture():\n    return 1\n",
    );
    let conftest_uri = turi("test_ls_callh_usage", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path.clone(), conftest_uri.clone());

    let test_path = tfile("test_ls_callh_usage", "test_example.py");
    db.analyze_file(test_path.clone(), "def test_one(my_fixture):\n    pass\n");
    let test_uri = turi("test_ls_callh_usage", "test_example.py");
    backend.uri_cache.insert(test_path, test_uri.clone());

    // Cursor on the fixture parameter in test file (line 0, char 13).
    let items = backend
        .prepare_call_hierarchy(CallHierarchyPrepareParams {
            text_document_position_params: tdp(test_uri, 0, 13),
            work_done_progress_params: wdp(),
        })
        .await
        .unwrap()
        .expect("items");
    // The item should point at the conftest definition.
    assert_eq!(items[0].uri, conftest_uri);
    assert_eq!(items[0].name, "my_fixture");
}

#[tokio::test]
#[timeout(30000)]
async fn test_incoming_calls_returns_callers() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Fixture `db` used by a test
    let conftest_path = tfile("test_ls_callh_in", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef db_fixture():\n    return 1\n",
    );
    let conftest_uri = turi("test_ls_callh_in", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path.clone(), conftest_uri.clone());

    let test_path = tfile("test_ls_callh_in", "test_example.py");
    db.analyze_file(test_path.clone(), "def test_one(db_fixture):\n    pass\n");
    let test_uri = turi("test_ls_callh_in", "test_example.py");
    backend.uri_cache.insert(test_path, test_uri.clone());

    // Ask for incoming calls to db_fixture defined in conftest.
    let calls = backend
        .incoming_calls(CallHierarchyIncomingCallsParams {
            item: CallHierarchyItem {
                name: "db_fixture".to_string(),
                kind: SymbolKind::FUNCTION,
                tags: None,
                detail: None,
                uri: conftest_uri,
                range: rng(3, 0, 3, 0),
                selection_range: rng(3, 4, 3, 14),
                data: None,
            },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await
        .unwrap()
        .expect("some calls");

    assert!(!calls.is_empty(), "expected at least one incoming call");
    // The caller should be the test function `test_one`.
    assert!(calls.iter().any(|c| c.from.name == "test_one"));
    assert!(calls.iter().any(|c| c.from.uri == test_uri));
}

#[tokio::test]
#[timeout(30000)]
async fn test_outgoing_calls_returns_dependencies() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // A fixture `consumer` that depends on `db_fixture`
    let conftest_path = tfile("test_ls_callh_out", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef db_fixture():\n    return 1\n\n@pytest.fixture\ndef consumer(db_fixture):\n    return db_fixture\n",
    );
    let conftest_uri = turi("test_ls_callh_out", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path.clone(), conftest_uri.clone());

    let calls = backend
        .outgoing_calls(CallHierarchyOutgoingCallsParams {
            item: CallHierarchyItem {
                name: "consumer".to_string(),
                kind: SymbolKind::FUNCTION,
                tags: None,
                detail: None,
                uri: conftest_uri.clone(),
                range: rng(7, 0, 7, 0),
                selection_range: rng(7, 4, 7, 12),
                data: None,
            },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await
        .unwrap()
        .expect("some calls");

    assert_eq!(calls.len(), 1);
    assert_eq!(calls[0].to.name, "db_fixture");
    assert_eq!(calls[0].to.uri, conftest_uri);
    // from_ranges should point at the parameter in the signature of `consumer`.
    assert!(!calls[0].from_ranges.is_empty());
}

#[tokio::test]
#[timeout(30000)]
async fn test_outgoing_calls_skips_unresolvable_dependency() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Fixture depending on a name that has no definition
    let conftest_path = tfile("test_ls_callh_out_missing", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef consumer(unknown_dep):\n    return unknown_dep\n",
    );
    let conftest_uri = turi("test_ls_callh_out_missing", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path, conftest_uri.clone());

    let calls = backend
        .outgoing_calls(CallHierarchyOutgoingCallsParams {
            item: CallHierarchyItem {
                name: "consumer".to_string(),
                kind: SymbolKind::FUNCTION,
                tags: None,
                detail: None,
                uri: conftest_uri,
                range: rng(3, 0, 3, 0),
                selection_range: rng(3, 4, 3, 12),
                data: None,
            },
            work_done_progress_params: wdp(),
            partial_result_params: prp(),
        })
        .await
        .unwrap()
        .expect("Some");
    assert!(calls.is_empty(), "unresolved deps should be filtered out");
}

// ── shutdown ──────────────────────────────────────────────────────────────

#[tokio::test]
#[timeout(10000)]
async fn test_shutdown_without_scan_task_returns_ok() {
    let backend = make_backend();
    // No active scan task – should return immediately
    let result = backend.shutdown().await;
    assert!(result.is_ok(), "shutdown should return Ok(())");
    // The spawned exit-after-100ms task is abandoned when the #[tokio::test]
    // runtime drops (current_thread executor never polls it again).
}

#[tokio::test]
#[timeout(10000)]
async fn test_shutdown_with_active_scan_task_aborts_it() {
    let backend = make_backend();

    // Simulate a long-running scan
    let handle = tokio::spawn(async {
        tokio::time::sleep(std::time::Duration::from_secs(60)).await;
    });
    *backend.scan_task.lock().await = Some(handle);

    let result = backend.shutdown().await;
    assert!(
        result.is_ok(),
        "shutdown with active scan should return Ok(())"
    );

    // After shutdown the scan_task slot must be empty
    assert!(
        backend.scan_task.lock().await.is_none(),
        "scan_task handle should be consumed by shutdown"
    );
}

#[tokio::test]
#[timeout(10000)]
async fn test_shutdown_with_already_completed_scan_task() {
    let backend = make_backend();

    // A task that finishes immediately
    let handle = tokio::spawn(async {});
    // Give it a moment to complete
    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    *backend.scan_task.lock().await = Some(handle);

    let result = backend.shutdown().await;
    assert!(result.is_ok());
}

// ── integration: full open → change → close lifecycle ────────────────────

#[tokio::test]
#[timeout(30000)]
async fn test_full_file_lifecycle_open_change_close() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let file_uri = turi("test_ls_lifecycle", "conftest.py");

    // 1. Open
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: file_uri.clone(),
                language_id: "python".to_string(),
                version: 1,
                text: "import pytest\n\n@pytest.fixture\ndef lc_fixture():\n    return 1\n"
                    .to_string(),
            },
        })
        .await;
    assert!(db.definitions.contains_key("lc_fixture"));

    // 2. Change
    backend
        .did_change(DidChangeTextDocumentParams {
            text_document: VersionedTextDocumentIdentifier {
                uri: file_uri.clone(),
                version: 2,
            },
            content_changes: vec![TextDocumentContentChangeEvent {
                range: None,
                range_length: None,
                text: "import pytest\n\n@pytest.fixture\ndef lc_fixture_v2():\n    return 2\n"
                    .to_string(),
            }],
        })
        .await;
    assert!(db.definitions.contains_key("lc_fixture_v2"));

    // 3. Close
    backend
        .did_close(DidCloseTextDocumentParams {
            text_document: TextDocumentIdentifier { uri: file_uri },
        })
        .await;
    assert!(
        backend.uri_cache.is_empty(),
        "URI cache should be empty after close"
    );
}

// ── publish_diagnostics_for_file ─────────────────────────────────────────
//
// `publish_diagnostics_for_file` pushes diagnostics to the LSP client. With
// the dummy client we can't intercept the wire call, but we can exercise the
// *construction* paths (lines 17–96 in `providers/diagnostics.rs`) and assert
// they don't panic + that the underlying detection methods agree about
// whether a diagnostic would have been produced.

#[tokio::test]
#[timeout(30000)]
async fn test_publish_diagnostics_reports_undeclared_fixture() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // Define `parent_fixture` in conftest.py so it is an *available* fixture
    // for the sibling test file. Using it in a test body without declaring
    // it as a parameter is an "undeclared fixture" usage.
    let conftest_path = tfile("test_ls_diag_undecl", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef parent_fixture():\n    return 1\n",
    );
    let conftest_uri = turi("test_ls_diag_undecl", "conftest.py");
    backend.uri_cache.insert(conftest_path, conftest_uri);

    let test_path = tfile("test_ls_diag_undecl", "test_example.py");
    db.analyze_file(
        test_path.clone(),
        "def test_something():\n    result = parent_fixture\n",
    );
    let test_uri = turi("test_ls_diag_undecl", "test_example.py");
    backend
        .uri_cache
        .insert(test_path.clone(), test_uri.clone());

    let undeclared = db.get_undeclared_fixtures(&test_path);
    assert!(
        !undeclared.is_empty(),
        "detection should find 'parent_fixture' as undeclared"
    );

    backend
        .publish_diagnostics_for_file(&test_uri, &test_path)
        .await;
}

#[tokio::test]
#[timeout(30000)]
async fn test_publish_diagnostics_reports_circular_dependency() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let conftest_path = tfile("test_ls_diag_cycle", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef a(b):\n    return b\n\n@pytest.fixture\ndef b(a):\n    return a\n",
    );
    let conftest_uri = turi("test_ls_diag_cycle", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path.clone(), conftest_uri.clone());

    // Detection method agrees there's a cycle in this file.
    let cycles = db.detect_fixture_cycles_in_file(&conftest_path);
    assert!(!cycles.is_empty(), "should detect a-b cycle");

    backend
        .publish_diagnostics_for_file(&conftest_uri, &conftest_path)
        .await;
}

#[tokio::test]
#[timeout(30000)]
async fn test_publish_diagnostics_reports_scope_mismatch() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // session-scoped fixture that depends on a function-scoped fixture
    let conftest_path = tfile("test_ls_diag_scope", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef narrow():\n    return 1\n\n@pytest.fixture(scope=\"session\")\ndef broad(narrow):\n    return narrow\n",
    );
    let conftest_uri = turi("test_ls_diag_scope", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path.clone(), conftest_uri.clone());

    let mismatches = db.detect_scope_mismatches_in_file(&conftest_path);
    assert!(
        !mismatches.is_empty(),
        "should detect session-depends-on-function mismatch"
    );

    backend
        .publish_diagnostics_for_file(&conftest_uri, &conftest_path)
        .await;
}

#[tokio::test]
#[timeout(30000)]
async fn test_publish_diagnostics_respects_disabled_diagnostics() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    // All three diagnostic sources present in one file.
    let conftest_path = tfile("test_ls_diag_disabled", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef narrow():\n    return 1\n\n@pytest.fixture(scope=\"session\")\ndef broad(narrow):\n    return narrow\n\n@pytest.fixture\ndef a(b):\n    return b\n\n@pytest.fixture\ndef b(a):\n    return a\n\ndef test_something():\n    missing_fx\n",
    );
    let conftest_uri = turi("test_ls_diag_disabled", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path.clone(), conftest_uri.clone());

    // Disable all three diagnostic kinds.
    {
        let mut config = backend.config.write().await;
        config.disabled_diagnostics = vec![
            "undeclared-fixture".to_string(),
            "circular-dependency".to_string(),
            "scope-mismatch".to_string(),
        ];
    }

    // Must still run cleanly (exercises the three `is_diagnostic_disabled` branches).
    backend
        .publish_diagnostics_for_file(&conftest_uri, &conftest_path)
        .await;
}

#[tokio::test]
#[timeout(30000)]
async fn test_publish_diagnostics_clean_file_publishes_nothing() {
    let db = Arc::new(FixtureDatabase::new());
    let backend = make_backend_with_db(Arc::clone(&db));

    let conftest_path = tfile("test_ls_diag_clean", "conftest.py");
    db.analyze_file(
        conftest_path.clone(),
        "import pytest\n\n@pytest.fixture\ndef clean_fixture():\n    return 1\n",
    );
    let conftest_uri = turi("test_ls_diag_clean", "conftest.py");
    backend
        .uri_cache
        .insert(conftest_path.clone(), conftest_uri.clone());

    // No undeclared/cycle/mismatch.
    assert!(db.get_undeclared_fixtures(&conftest_path).is_empty());
    assert!(db.detect_fixture_cycles_in_file(&conftest_path).is_empty());
    assert!(db
        .detect_scope_mismatches_in_file(&conftest_path)
        .is_empty());

    backend
        .publish_diagnostics_for_file(&conftest_uri, &conftest_path)
        .await;
}