pytest-language-server 0.22.0

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
// E2E Integration Tests
// These tests verify the full system behavior including CLI commands,
// workspace scanning, and LSP functionality using the test_project.
//
// All tests have a 30-second timeout to prevent hangs from blocking CI.

#![allow(deprecated)]

use assert_cmd::Command;
use insta::assert_snapshot;
use ntest::timeout;
use predicates::prelude::*;
use pytest_language_server::FixtureDatabase;
use std::path::PathBuf;
use tempfile::tempdir;

// Helper function to normalize paths in output for cross-platform testing
fn normalize_path_in_output(output: &str) -> String {
    // Get the absolute path to tests/test_project
    let test_project_path = std::env::current_dir()
        .unwrap()
        .join("tests/test_project")
        .canonicalize()
        .unwrap();

    // Replace the absolute path with a placeholder
    output.replace(
        &test_project_path.to_string_lossy().to_string(),
        "<TEST_PROJECT_PATH>",
    )
}

// MARK: CLI E2E Tests

#[test]
#[timeout(30000)]
fn test_cli_fixtures_list_full_output() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("list")
        .arg("tests/test_project")
        .output()
        .expect("Failed to execute command");

    // Should succeed
    assert!(output.status.success());

    // Convert output to string and normalize for snapshot testing
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Normalize path for cross-platform snapshot testing
    let normalized = normalize_path_in_output(&stdout);

    // Snapshot the output (colors will be in the output)
    assert_snapshot!("cli_fixtures_list_full", normalized);
}

#[test]
#[timeout(30000)]
fn test_cli_fixtures_list_skip_unused() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("list")
        .arg("tests/test_project")
        .arg("--skip-unused")
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);
    let normalized = normalize_path_in_output(&stdout);
    assert_snapshot!("cli_fixtures_list_skip_unused", normalized);
}

#[test]
#[timeout(30000)]
fn test_cli_fixtures_list_only_unused() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("list")
        .arg("tests/test_project")
        .arg("--only-unused")
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);
    let normalized = normalize_path_in_output(&stdout);
    assert_snapshot!("cli_fixtures_list_only_unused", normalized);
}

#[test]
#[timeout(30000)]
fn test_cli_fixtures_list_nonexistent_path() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    cmd.arg("fixtures")
        .arg("list")
        .arg("/nonexistent/path/to/project")
        .assert()
        .failure();
}

#[test]
#[timeout(30000)]
fn test_cli_fixtures_list_empty_directory() {
    let temp_dir = std::env::temp_dir().join("empty_test_dir");
    std::fs::create_dir_all(&temp_dir).ok();

    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("list")
        .arg(&temp_dir)
        .output()
        .expect("Failed to execute command");

    // Should succeed but show no fixtures
    assert!(output.status.success());

    std::fs::remove_dir_all(&temp_dir).ok();
}

#[test]
#[timeout(30000)]
fn test_cli_help_message() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    cmd.arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("Language Server Protocol"))
        .stdout(predicate::str::contains("fixtures"))
        .stdout(predicate::str::contains("Fixture-related"));
}

#[test]
#[timeout(30000)]
fn test_cli_version() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    cmd.arg("--version")
        .assert()
        .success()
        .stdout(predicate::str::contains(env!("CARGO_PKG_VERSION")));
}

#[test]
#[timeout(30000)]
fn test_cli_fixtures_help() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    cmd.arg("fixtures")
        .arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("list"))
        .stdout(predicate::str::contains("List all fixtures"));
}

#[test]
#[timeout(30000)]
fn test_cli_invalid_subcommand() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    cmd.arg("invalid").assert().failure();
}

#[test]
#[timeout(30000)]
fn test_cli_conflicting_flags() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    cmd.arg("fixtures")
        .arg("list")
        .arg("tests/test_project")
        .arg("--skip-unused")
        .arg("--only-unused")
        .assert()
        .failure();
}

// MARK: CLI fixtures unused E2E Tests

#[test]
#[timeout(30000)]
fn test_cli_fixtures_unused_text_output() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("unused")
        .arg("tests/test_project")
        .output()
        .expect("Failed to execute command");

    // Should exit with code 1 when unused fixtures are found
    assert!(!output.status.success());
    assert_eq!(output.status.code(), Some(1));

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should contain the header
    assert!(stdout.contains("Found") && stdout.contains("unused fixture"));

    // Should contain known unused fixtures from test_project
    // (iterator_fixture, temp_dir, temp_file are unused; auto_cleanup is autouse, not unused)
    assert!(
        stdout.contains("iterator_fixture"),
        "iterator_fixture should be reported as unused"
    );
    assert!(
        !stdout.contains("auto_cleanup"),
        "autouse fixture auto_cleanup should NOT be reported as unused"
    );
}

#[test]
#[timeout(30000)]
fn test_cli_fixtures_unused_json_output() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("unused")
        .arg("tests/test_project")
        .arg("--format")
        .arg("json")
        .output()
        .expect("Failed to execute command");

    // Should exit with code 1 when unused fixtures are found
    assert!(!output.status.success());
    assert_eq!(output.status.code(), Some(1));

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should be valid JSON
    let parsed: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
    assert!(parsed.is_ok(), "Output should be valid JSON: {}", stdout);

    let json = parsed.unwrap();
    assert!(json.is_array(), "JSON output should be an array");

    let arr = json.as_array().unwrap();
    assert!(!arr.is_empty(), "Should have at least one unused fixture");

    // Each item should have "file" and "fixture" keys
    for item in arr {
        assert!(
            item.get("file").is_some(),
            "Each item should have 'file' key"
        );
        assert!(
            item.get("fixture").is_some(),
            "Each item should have 'fixture' key"
        );
    }
}

#[test]
#[timeout(30000)]
fn test_cli_fixtures_unused_exit_code_zero_when_all_used() {
    // Create a temp directory with all fixtures used
    let temp_dir = std::env::temp_dir().join("test_all_used");
    std::fs::create_dir_all(&temp_dir).ok();

    std::fs::write(
        temp_dir.join("conftest.py"),
        r#"
import pytest

@pytest.fixture
def my_fixture():
    return "value"
"#,
    )
    .ok();

    std::fs::write(
        temp_dir.join("test_example.py"),
        r#"
def test_something(my_fixture):
    assert my_fixture == "value"
"#,
    )
    .ok();

    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("unused")
        .arg(&temp_dir)
        .output()
        .expect("Failed to execute command");

    // Should exit with code 0 when all fixtures are used
    assert!(output.status.success());
    assert_eq!(output.status.code(), Some(0));

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("No unused fixtures found"));

    std::fs::remove_dir_all(&temp_dir).ok();
}

#[test]
#[timeout(30000)]
fn test_cli_fixtures_unused_nonexistent_path() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    cmd.arg("fixtures")
        .arg("unused")
        .arg("/nonexistent/path/to/project")
        .assert()
        .failure();
}

#[test]
#[timeout(30000)]
fn test_cli_fixtures_unused_help() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    cmd.arg("fixtures")
        .arg("unused")
        .arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("unused fixtures"))
        .stdout(predicate::str::contains("--format"));
}

// MARK: Autouse fixtures in `fixtures list` E2E Tests

#[test]
#[timeout(30000)]
fn test_cli_fixtures_list_only_unused_excludes_autouse() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("list")
        .arg("tests/test_project")
        .arg("--only-unused")
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(
        !stdout.contains("auto_cleanup"),
        "autouse fixture auto_cleanup should NOT appear in --only-unused output"
    );
    // Regular unused fixtures should still appear
    assert!(
        stdout.contains("iterator_fixture"),
        "non-autouse unused fixture should appear"
    );
}

#[test]
#[timeout(30000)]
fn test_cli_fixtures_list_skip_unused_includes_autouse() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("list")
        .arg("tests/test_project")
        .arg("--skip-unused")
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(
        stdout.contains("auto_cleanup"),
        "autouse fixture auto_cleanup should appear in --skip-unused output"
    );
    // Regular unused fixtures should NOT appear
    assert!(
        !stdout.contains("iterator_fixture"),
        "non-autouse unused fixture should NOT appear in --skip-unused output"
    );
}

#[test]
#[timeout(30000)]
fn test_cli_fixtures_list_shows_autouse_label() {
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("list")
        .arg("tests/test_project")
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(
        stdout.contains("autouse=True"),
        "full list should show 'autouse=True' label for autouse fixtures"
    );
    assert!(
        !stdout.contains("auto_cleanup") || !stdout.contains("auto_cleanup (unused)"),
        "auto_cleanup should not be shown as 'unused'"
    );
}

// MARK: Workspace Scanning E2E Tests

#[test]
#[timeout(30000)]
fn test_e2e_scan_expanded_test_project() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Verify fixtures from root conftest
    assert!(db.definitions.get("sample_fixture").is_some());

    // Verify fixtures from api/conftest.py
    assert!(db.definitions.get("api_client").is_some());
    assert!(db.definitions.get("api_token").is_some());
    assert!(db.definitions.get("mock_response").is_some());

    // Verify fixtures from database/conftest.py
    assert!(db.definitions.get("db_connection").is_some());
    assert!(db.definitions.get("db_cursor").is_some());
    assert!(db.definitions.get("transaction").is_some());

    // Verify fixtures from utils/conftest.py
    assert!(db.definitions.get("temp_file").is_some());
    assert!(db.definitions.get("temp_dir").is_some());
    assert!(db.definitions.get("auto_cleanup").is_some());

    // Verify fixtures from integration/test_scopes.py
    assert!(db.definitions.get("session_fixture").is_some());
    assert!(db.definitions.get("module_fixture").is_some());

    // Verify fixture from api/test_endpoints.py
    assert!(db.definitions.get("local_fixture").is_some());
}

#[test]
#[timeout(30000)]
fn test_e2e_fixture_hierarchy_resolution() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Test file in api/ should see fixtures from api/conftest.py and root conftest.py
    let test_file = project_path.join("api/test_endpoints.py");
    let test_file_canonical = test_file.canonicalize().unwrap();
    let available = db.get_available_fixtures(&test_file_canonical);

    let names: Vec<&str> = available.iter().map(|f| f.name.as_str()).collect();

    // Should have access to api fixtures
    assert!(names.contains(&"api_client"));
    assert!(names.contains(&"api_token"));

    // Should have access to root fixtures
    assert!(names.contains(&"sample_fixture"));

    // Should NOT have access to database fixtures (different branch)
    assert!(!names.contains(&"db_connection"));
}

#[test]
#[timeout(30000)]
fn test_e2e_fixture_dependency_chain() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Verify 3-level dependency chain: transaction -> db_cursor -> db_connection
    let transaction = db.definitions.get("transaction").unwrap();
    assert_eq!(transaction.len(), 1);

    let db_cursor = db.definitions.get("db_cursor").unwrap();
    assert_eq!(db_cursor.len(), 1);

    let db_connection = db.definitions.get("db_connection").unwrap();
    assert_eq!(db_connection.len(), 1);
}

#[test]
#[timeout(30000)]
fn test_e2e_autouse_fixture_detection() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Should detect the autouse fixture
    let autouse = db.definitions.get("auto_cleanup");
    assert!(autouse.is_some());

    // Verify the autouse field is set
    let auto_cleanup = &autouse.unwrap()[0];
    assert!(
        auto_cleanup.autouse,
        "auto_cleanup should have autouse=true"
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_autouse_fixture_not_reported_unused() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    let unused = db.get_unused_fixtures();
    let unused_names: Vec<&str> = unused.iter().map(|(_, name)| name.as_str()).collect();

    assert!(
        !unused_names.contains(&"auto_cleanup"),
        "autouse fixture auto_cleanup should NOT be reported as unused"
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_scoped_fixtures() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Should detect session and module scoped fixtures
    assert!(db.definitions.get("session_fixture").is_some());
    assert!(db.definitions.get("module_fixture").is_some());
}

#[test]
#[timeout(30000)]
fn test_e2e_fixture_usage_in_test_file() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Check usages in api/test_endpoints.py (path will be canonicalized)
    let test_file = project_path.join("api/test_endpoints.py");
    let test_file_canonical = test_file.canonicalize().unwrap();
    let usages = db.usages.get(&test_file_canonical);

    assert!(
        usages.is_some(),
        "No usages found for {:?}",
        test_file_canonical
    );
    let usages = usages.unwrap();

    // Should have multiple fixture usages
    assert!(
        usages.len() >= 3,
        "Expected at least 3 usages, found {}",
        usages.len()
    ); // api_client, api_token, mock_response, local_fixture

    let usage_names: Vec<&str> = usages.iter().map(|u| u.name.as_str()).collect();
    assert!(usage_names.contains(&"api_client"));
    assert!(usage_names.contains(&"api_token"));
}

#[test]
#[timeout(30000)]
fn test_e2e_find_references_across_project() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Find all references to api_client
    let references = db.find_fixture_references("api_client");

    // Should find usages in test files
    assert!(!references.is_empty());
}

#[test]
#[timeout(30000)]
fn test_e2e_fixture_override_in_subdirectory() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Check if override fixture exists (from existing test_project structure)
    let test_file = project_path.join("subdir/test_override.py");

    if test_file.exists() {
        let test_file_canonical = test_file.canonicalize().unwrap();
        let available = db.get_available_fixtures(&test_file_canonical);

        // Should have fixtures from both root and subdir conftest
        let names: Vec<&str> = available.iter().map(|f| f.name.as_str()).collect();
        assert!(!names.is_empty());
    }
}

// MARK: Performance E2E Tests

#[test]
#[timeout(30000)]
fn test_e2e_scan_performance() {
    use std::time::Instant;

    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    let start = Instant::now();
    db.scan_workspace(&project_path);
    let duration = start.elapsed();

    // Scanning should be fast (less than 1 second for small project)
    assert!(
        duration.as_secs() < 1,
        "Scanning took too long: {:?}",
        duration
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_repeated_analysis() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    // Scan twice - second scan should be fast due to caching
    db.scan_workspace(&project_path);

    use std::time::Instant;
    let start = Instant::now();
    db.scan_workspace(&project_path);
    let duration = start.elapsed();

    assert!(duration.as_millis() < 500, "Re-scanning took too long");
}

// MARK: Error Handling E2E Tests

#[test]
#[timeout(30000)]
fn test_e2e_malformed_python_file() {
    let db = FixtureDatabase::new();

    // Create a temp file with invalid Python
    let temp_dir = std::env::temp_dir().join("test_malformed");
    std::fs::create_dir_all(&temp_dir).ok();

    let bad_file = temp_dir.join("test_bad.py");
    std::fs::write(
        &bad_file,
        "def test_something(\n    this is not valid python",
    )
    .ok();

    // Should not crash
    db.scan_workspace(&temp_dir);

    std::fs::remove_dir_all(&temp_dir).ok();
}

#[test]
#[timeout(30000)]
fn test_e2e_mixed_valid_and_invalid_files() {
    let db = FixtureDatabase::new();

    let temp_dir = std::env::temp_dir().join("test_mixed");
    std::fs::create_dir_all(&temp_dir).ok();

    // Valid file
    std::fs::write(
        temp_dir.join("test_valid.py"),
        r#"
import pytest

@pytest.fixture
def valid_fixture():
    return "valid"

def test_something(valid_fixture):
    pass
"#,
    )
    .ok();

    // Invalid file
    std::fs::write(
        temp_dir.join("test_invalid.py"),
        "def test_broken(\n    invalid syntax here",
    )
    .ok();

    db.scan_workspace(&temp_dir);

    // Should still find the valid fixture
    assert!(db.definitions.get("valid_fixture").is_some());

    std::fs::remove_dir_all(&temp_dir).ok();
}

// MARK: - Renamed Fixtures E2E Tests

#[test]
#[timeout(30000)]
fn test_e2e_renamed_fixtures_in_test_project() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // The test_renamed_fixtures.py file has fixtures with name= parameter
    // Fixtures should be registered by their alias, not function name
    assert!(
        db.definitions.contains_key("renamed_db"),
        "Should find fixture by alias 'renamed_db'"
    );
    assert!(
        db.definitions.contains_key("user"),
        "Should find fixture by alias 'user'"
    );
    assert!(
        db.definitions.contains_key("normal_fixture"),
        "Should find normal fixture by function name"
    );

    // Internal function names should NOT be registered
    assert!(
        !db.definitions.contains_key("internal_database_fixture"),
        "Internal function name should not be registered"
    );
    assert!(
        !db.definitions.contains_key("create_user_fixture"),
        "Internal function name should not be registered"
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_renamed_fixture_references() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Get the renamed_db fixture definition
    let renamed_db_defs = db.definitions.get("renamed_db");
    assert!(renamed_db_defs.is_some());

    let def = &renamed_db_defs.unwrap()[0];
    let refs = db.find_references_for_definition(def);

    // Should have references from:
    // 1. create_user_fixture (depends on renamed_db)
    // 2. test_with_renamed_fixture
    // 3. test_mixed_fixtures
    assert!(
        refs.len() >= 3,
        "Should have at least 3 references to renamed_db, got {}",
        refs.len()
    );

    // All references should use the alias name
    assert!(
        refs.iter().all(|r| r.name == "renamed_db"),
        "All references should use alias name"
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_renamed_fixture_goto_definition() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    let test_file = project_path
        .join("test_renamed_fixtures.py")
        .canonicalize()
        .unwrap();

    // Find "renamed_db" in test_with_renamed_fixture (line 24, 0-indexed: 23)
    // def test_with_renamed_fixture(renamed_db):
    let fixture_name = db.find_fixture_at_position(&test_file, 23, 30);
    assert_eq!(
        fixture_name,
        Some("renamed_db".to_string()),
        "Should find fixture name at position"
    );

    let definition = db.find_fixture_definition(&test_file, 23, 30);
    assert!(definition.is_some(), "Should find fixture definition");

    let def = definition.unwrap();
    assert_eq!(def.name, "renamed_db", "Definition should have alias name");
}

#[test]
#[timeout(30000)]
fn test_e2e_cli_fixtures_list_with_renamed() {
    // Run CLI and verify renamed fixtures appear correctly
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("list")
        .arg("tests/test_project")
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should show renamed fixtures by their alias
    assert!(
        stdout.contains("renamed_db"),
        "Output should contain 'renamed_db'"
    );
    assert!(stdout.contains("user"), "Output should contain 'user'");
    assert!(
        stdout.contains("normal_fixture"),
        "Output should contain 'normal_fixture'"
    );

    // Should NOT show internal function names
    assert!(
        !stdout.contains("internal_database_fixture"),
        "Should not show internal function name"
    );
    assert!(
        !stdout.contains("create_user_fixture"),
        "Should not show internal function name"
    );
}

// MARK: - Class-based Tests E2E Tests (issue #19)

#[test]
#[timeout(30000)]
fn test_e2e_class_based_tests_fixture_usage() {
    // Test case from https://github.com/bellini666/pytest-language-server/issues/19
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Fixtures defined in test_class_based.py should be found
    assert!(
        db.definitions.contains_key("shared_fixture"),
        "Should find shared_fixture"
    );
    assert!(
        db.definitions.contains_key("another_fixture"),
        "Should find another_fixture"
    );

    // Get the test file and check usages
    let test_file = project_path
        .join("test_class_based.py")
        .canonicalize()
        .unwrap();

    let usages = db.usages.get(&test_file);
    assert!(
        usages.is_some(),
        "Should have usages in test_class_based.py"
    );

    let usages = usages.unwrap();

    // Count usages of shared_fixture (should be used by multiple test methods in classes)
    let shared_usages: Vec<_> = usages
        .iter()
        .filter(|u| u.name == "shared_fixture")
        .collect();
    assert!(
        shared_usages.len() >= 4,
        "shared_fixture should be used at least 4 times (by test methods in classes), got {}",
        shared_usages.len()
    );

    // Count usages of another_fixture
    let another_usages: Vec<_> = usages
        .iter()
        .filter(|u| u.name == "another_fixture")
        .collect();
    assert!(
        another_usages.len() >= 2,
        "another_fixture should be used at least 2 times, got {}",
        another_usages.len()
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_class_based_fixture_references() {
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Get the shared_fixture definition
    let shared_defs = db.definitions.get("shared_fixture");
    assert!(shared_defs.is_some());

    let def = &shared_defs.unwrap()[0];
    let refs = db.find_references_for_definition(def);

    // Should have references from test methods in classes
    assert!(
        refs.len() >= 4,
        "shared_fixture should have at least 4 references from class test methods, got {}",
        refs.len()
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_cli_class_based_fixtures_shown_as_used() {
    // Run CLI and verify fixtures used by class-based tests are marked as used
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("list")
        .arg("tests/test_project")
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);

    // shared_fixture and another_fixture should be shown as used (not "unused")
    // They are used by test methods inside TestClassBased and TestNestedClasses
    assert!(
        stdout.contains("shared_fixture") && !stdout.contains("shared_fixture (unused)"),
        "shared_fixture should be marked as used"
    );
    assert!(
        stdout.contains("another_fixture") && !stdout.contains("another_fixture (unused)"),
        "another_fixture should be marked as used"
    );
}

// MARK: Keyword-only and Positional-only Fixtures E2E Tests

#[test]
#[timeout(30000)]
fn test_e2e_keyword_only_fixture_detection() {
    // Test that fixtures used as keyword-only arguments are properly detected
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");
    db.scan_workspace(&project_path);

    // Get the test file path
    let test_file = project_path
        .join("test_kwonly_fixtures.py")
        .canonicalize()
        .unwrap();

    // Check that usages were detected for keyword-only fixtures
    let usages = db.usages.get(&test_file);
    assert!(
        usages.is_some(),
        "Usages should be detected for test_kwonly_fixtures.py"
    );

    let usages = usages.unwrap();

    // Verify sample_fixture usage (used in keyword-only and positional-only tests)
    assert!(
        usages.iter().any(|u| u.name == "sample_fixture"),
        "sample_fixture should be detected as used"
    );

    // Verify another_fixture usage (used in keyword-only tests)
    assert!(
        usages.iter().any(|u| u.name == "another_fixture"),
        "another_fixture should be detected as used"
    );

    // Verify shared_resource usage (used in keyword-only tests)
    assert!(
        usages.iter().any(|u| u.name == "shared_resource"),
        "shared_resource should be detected as used"
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_keyword_only_no_undeclared_fixtures() {
    // Verify that keyword-only fixtures are not flagged as undeclared
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");
    db.scan_workspace(&project_path);

    // Get the test file path
    let test_file = project_path
        .join("test_kwonly_fixtures.py")
        .canonicalize()
        .unwrap();

    // There should be no undeclared fixtures in this file
    let undeclared = db.get_undeclared_fixtures(&test_file);
    assert_eq!(
        undeclared.len(),
        0,
        "Keyword-only fixtures should not be flagged as undeclared. Found: {:?}",
        undeclared.iter().map(|u| &u.name).collect::<Vec<_>>()
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_keyword_only_go_to_definition() {
    // Test that go-to-definition works for keyword-only fixtures
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");
    db.scan_workspace(&project_path);

    let test_file = project_path
        .join("test_kwonly_fixtures.py")
        .canonicalize()
        .unwrap();
    let conftest_file = project_path.join("conftest.py").canonicalize().unwrap();

    // Get the usages for the test file
    let usages = db.usages.get(&test_file);
    assert!(usages.is_some());

    let usages = usages.unwrap();

    // Find the sample_fixture usage
    let sample_usage = usages.iter().find(|u| u.name == "sample_fixture");
    assert!(
        sample_usage.is_some(),
        "sample_fixture usage should be found"
    );
    let sample_usage = sample_usage.unwrap();

    // Try to find the definition using the usage position
    // usage.line is 1-based, but find_fixture_definition expects 0-based LSP coordinates
    let definition = db.find_fixture_definition(
        &test_file,
        (sample_usage.line - 1) as u32,
        sample_usage.start_char as u32,
    );

    assert!(
        definition.is_some(),
        "Definition should be found for keyword-only fixture"
    );
    let def = definition.unwrap();
    assert_eq!(def.name, "sample_fixture");
    assert_eq!(def.file_path, conftest_file);
}

// MARK: Imported Fixtures E2E Tests

#[test]
#[timeout(30000)]
fn test_e2e_imported_fixtures_are_detected() {
    // Tests that fixtures imported via star import in conftest.py are properly detected
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Fixtures from fixture_module.py should be available
    let imported = db.definitions.get("imported_fixture");
    assert!(
        imported.is_some(),
        "imported_fixture should be detected from fixture_module.py"
    );

    let another_imported = db.definitions.get("another_imported_fixture");
    assert!(
        another_imported.is_some(),
        "another_imported_fixture should be detected from fixture_module.py"
    );

    // The explicitly_imported fixture should also be detected
    let explicit = db.definitions.get("explicitly_imported");
    assert!(
        explicit.is_some(),
        "explicitly_imported should be detected from fixture_module.py"
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_imported_fixtures_available_in_test_file() {
    // Tests that imported fixtures are available for tests in the same directory
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    let test_file = project_path.join("imported_fixtures/test_uses_imported.py");
    let test_file_canonical = test_file.canonicalize().unwrap();

    let available = db.get_available_fixtures(&test_file_canonical);
    let names: Vec<&str> = available.iter().map(|f| f.name.as_str()).collect();

    // Should have access to imported fixtures via conftest.py star import
    assert!(
        names.contains(&"imported_fixture"),
        "imported_fixture should be available in test file"
    );
    assert!(
        names.contains(&"another_imported_fixture"),
        "another_imported_fixture should be available in test file"
    );
    assert!(
        names.contains(&"explicitly_imported"),
        "explicitly_imported should be available in test file"
    );

    // Should also have access to the local fixture defined in conftest
    assert!(
        names.contains(&"local_fixture"),
        "local_fixture should be available in test file"
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_imported_fixtures_go_to_definition() {
    // Tests that go-to-definition works for imported fixtures
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    let test_file = project_path.join("imported_fixtures/test_uses_imported.py");
    let test_file_canonical = test_file.canonicalize().unwrap();
    let fixture_module = project_path.join("imported_fixtures/fixture_module.py");
    let fixture_module_canonical = fixture_module.canonicalize().unwrap();

    // Find the usage of imported_fixture in the test file
    let usages = db.usages.get(&test_file_canonical);
    assert!(usages.is_some(), "Test file should have fixture usages");

    let usages = usages.unwrap();
    let imported_usage = usages
        .iter()
        .find(|u| u.name == "imported_fixture")
        .expect("Should find imported_fixture usage");

    // Go-to-definition should find the fixture in fixture_module.py
    let definition = db.find_fixture_definition(
        &test_file_canonical,
        (imported_usage.line - 1) as u32,
        imported_usage.start_char as u32,
    );

    assert!(
        definition.is_some(),
        "Should find definition for imported_fixture"
    );
    let def = definition.unwrap();
    assert_eq!(def.name, "imported_fixture");
    assert_eq!(
        def.file_path, fixture_module_canonical,
        "Definition should be in fixture_module.py"
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_imported_fixtures_find_references() {
    // Tests that find-references works for imported fixtures
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Get the definition of imported_fixture
    let definitions = db.definitions.get("imported_fixture");
    assert!(definitions.is_some());
    let def = definitions.unwrap().first().unwrap().clone();

    // Find all references to this fixture
    let references = db.find_references_for_definition(&def);

    // Should find at least the usage in test_uses_imported.py
    assert!(
        !references.is_empty(),
        "Should find references to imported_fixture"
    );

    // Verify at least one reference is in the test file
    let test_file = project_path.join("imported_fixtures/test_uses_imported.py");
    let test_file_canonical = test_file.canonicalize().unwrap();
    let has_test_ref = references
        .iter()
        .any(|r| r.file_path == test_file_canonical);
    assert!(
        has_test_ref,
        "Should have a reference in test_uses_imported.py"
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_imported_fixtures_no_undeclared_warning() {
    // Tests that imported fixtures are not flagged as undeclared
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    let test_file = project_path.join("imported_fixtures/test_uses_imported.py");
    let test_file_canonical = test_file.canonicalize().unwrap();

    let undeclared = db.get_undeclared_fixtures(&test_file_canonical);
    let undeclared_names: Vec<&str> = undeclared.iter().map(|u| u.name.as_str()).collect();

    // Imported fixtures should NOT be in undeclared
    assert!(
        !undeclared_names.contains(&"imported_fixture"),
        "imported_fixture should not be flagged as undeclared"
    );
    assert!(
        !undeclared_names.contains(&"another_imported_fixture"),
        "another_imported_fixture should not be flagged as undeclared"
    );
    assert!(
        !undeclared_names.contains(&"local_fixture"),
        "local_fixture should not be flagged as undeclared"
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_imported_fixtures_cache_performance() {
    // Tests that the imported fixtures cache provides performance benefit
    use std::time::Instant;

    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    let conftest_file = project_path.join("imported_fixtures/conftest.py");
    let conftest_canonical = conftest_file.canonicalize().unwrap();

    // First call - populates the cache
    let start = Instant::now();
    let mut visited = std::collections::HashSet::new();
    let first_result = db.get_imported_fixtures(&conftest_canonical, &mut visited);
    let first_duration = start.elapsed();

    // Second call - should hit the cache
    let start = Instant::now();
    let mut visited = std::collections::HashSet::new();
    let second_result = db.get_imported_fixtures(&conftest_canonical, &mut visited);
    let second_duration = start.elapsed();

    // Results should be the same
    assert_eq!(first_result, second_result);

    // Cache hit should be faster (allow some variance for system noise)
    // We just verify the cache works by checking results are identical
    // In CI, timing can be unreliable, so we just log for diagnostics
    eprintln!(
        "Import cache: first call {:?}, second call {:?}",
        first_duration, second_duration
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_imported_fixtures_cli_shows_them() {
    // Tests that the CLI shows imported fixtures as used (not unused)
    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("list")
        .arg("tests/test_project/imported_fixtures")
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);

    // imported_fixture and another_imported_fixture should appear in the output
    // They are used in test_uses_imported.py
    assert!(
        stdout.contains("imported_fixture"),
        "CLI output should list imported_fixture"
    );
    assert!(
        stdout.contains("another_imported_fixture"),
        "CLI output should list another_imported_fixture"
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_transitive_imported_fixtures() {
    // Tests that fixtures imported transitively (A imports from B, B imports from C) are detected
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    // Fixtures from nested/deep_fixtures.py should be available via transitive import:
    // conftest.py -> fixture_module.py -> nested/deep_fixtures.py
    let deep_fixture = db.definitions.get("deep_nested_fixture");
    assert!(
        deep_fixture.is_some(),
        "deep_nested_fixture should be detected from nested/deep_fixtures.py"
    );

    let another_deep = db.definitions.get("another_deep_fixture");
    assert!(
        another_deep.is_some(),
        "another_deep_fixture should be detected from nested/deep_fixtures.py"
    );

    // These fixtures should be available in test_uses_imported.py
    let test_file = project_path.join("imported_fixtures/test_uses_imported.py");
    let test_file_canonical = test_file.canonicalize().unwrap();

    let available = db.get_available_fixtures(&test_file_canonical);
    let names: Vec<&str> = available.iter().map(|f| f.name.as_str()).collect();

    assert!(
        names.contains(&"deep_nested_fixture"),
        "deep_nested_fixture should be available via transitive import"
    );
    assert!(
        names.contains(&"another_deep_fixture"),
        "another_deep_fixture should be available via transitive import"
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_transitive_imports_go_to_definition() {
    // Tests that go-to-definition works for transitively imported fixtures
    let db = FixtureDatabase::new();
    let project_path = PathBuf::from("tests/test_project");

    db.scan_workspace(&project_path);

    let test_file = project_path.join("imported_fixtures/test_uses_imported.py");
    let test_file_canonical = test_file.canonicalize().unwrap();
    let deep_fixtures_file = project_path.join("imported_fixtures/nested/deep_fixtures.py");
    let deep_fixtures_canonical = deep_fixtures_file.canonicalize().unwrap();

    // Find the usage of deep_nested_fixture in the test file
    let usages = db.usages.get(&test_file_canonical);
    assert!(usages.is_some(), "Test file should have fixture usages");

    let usages = usages.unwrap();
    let deep_usage = usages
        .iter()
        .find(|u| u.name == "deep_nested_fixture")
        .expect("Should find deep_nested_fixture usage");

    // Go-to-definition should find the fixture in nested/deep_fixtures.py
    let definition = db.find_fixture_definition(
        &test_file_canonical,
        (deep_usage.line - 1) as u32,
        deep_usage.start_char as u32,
    );

    assert!(
        definition.is_some(),
        "Should find definition for deep_nested_fixture"
    );
    let def = definition.unwrap();
    assert_eq!(def.name, "deep_nested_fixture");
    assert_eq!(
        def.file_path, deep_fixtures_canonical,
        "Definition should be in nested/deep_fixtures.py"
    );
}

// MARK: Editable Install CLI Tests

/// Helper: set up a workspace with `.venv` containing an editable install whose
/// source root lives in a *separate* temp directory (outside the workspace).
/// Returns (workspace_tempdir, source_tempdir) so both stay alive for the test.
fn setup_editable_install_workspace() -> (tempfile::TempDir, tempfile::TempDir) {
    use std::fs;

    let workspace = tempdir().unwrap();
    let external_src = tempdir().unwrap();

    // ── workspace files ──────────────────────────────────────────────────
    let conftest = r#"
import pytest

@pytest.fixture
def local_fixture():
    """A fixture defined in the workspace."""
    return "local"
"#;
    fs::write(workspace.path().join("conftest.py"), conftest).unwrap();

    let test_file = r#"
def test_uses_both(local_fixture, editable_plugin_fixture):
    pass
"#;
    fs::write(workspace.path().join("test_example.py"), test_file).unwrap();

    // ── external editable source root ────────────────────────────────────
    let pkg_dir = external_src.path().join("myplugin");
    fs::create_dir_all(&pkg_dir).unwrap();
    fs::write(pkg_dir.join("__init__.py"), "").unwrap();

    let plugin_content = r#"
import pytest

@pytest.fixture
def editable_plugin_fixture():
    """Fixture from an external editable install."""
    return "editable"
"#;
    fs::write(pkg_dir.join("plugin.py"), plugin_content).unwrap();

    // ── fake venv with site-packages ─────────────────────────────────────
    let site_packages = workspace.path().join(".venv/lib/python3.12/site-packages");
    fs::create_dir_all(&site_packages).unwrap();

    // dist-info with direct_url.json marking it as editable
    let dist_info = site_packages.join("myplugin-0.1.0.dist-info");
    fs::create_dir_all(&dist_info).unwrap();

    let direct_url = serde_json::json!({
        "url": format!("file://{}", external_src.path().display()),
        "dir_info": { "editable": true }
    });
    fs::write(
        dist_info.join("direct_url.json"),
        serde_json::to_string(&direct_url).unwrap(),
    )
    .unwrap();

    // entry_points.txt so the scanner discovers the plugin module
    let entry_points = "[pytest11]\nmyplugin = myplugin.plugin\n";
    fs::write(dist_info.join("entry_points.txt"), entry_points).unwrap();

    // .pth file pointing to the external source root
    let pth_content = format!("{}\n", external_src.path().display());
    fs::write(
        site_packages.join("__editable__.myplugin-0.1.0.pth"),
        &pth_content,
    )
    .unwrap();

    (workspace, external_src)
}

#[test]
#[timeout(30000)]
fn test_e2e_editable_install_fixtures_in_tree() {
    // Verifies that fixtures from an external editable install appear in the
    // `fixtures list` output.  Before the fix, `print_tree_node` used
    // `path.is_file()` which returned false for the remapped virtual path,
    // so the fixture was silently dropped from the tree.
    let (workspace, _src) = setup_editable_install_workspace();

    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("list")
        .arg(workspace.path())
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success(), "CLI should exit successfully");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // The editable install fixture must appear in the tree output.
    assert!(
        stdout.contains("editable_plugin_fixture"),
        "Editable install fixture should appear in `fixtures list` output.\nGot:\n{}",
        stdout
    );

    // The local fixture should still be there too.
    assert!(
        stdout.contains("local_fixture"),
        "Local fixture should still appear in output.\nGot:\n{}",
        stdout
    );

    // The editable install directory label should be annotated.
    assert!(
        stdout.contains("(editable install)"),
        "Editable install directory should be labelled.\nGot:\n{}",
        stdout
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_editable_install_fixtures_skip_unused() {
    // With --skip-unused the editable fixture (which IS used by test_example.py)
    // should still appear, and unused local fixtures should be hidden.
    let (workspace, _src) = setup_editable_install_workspace();

    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("list")
        .arg("--skip-unused")
        .arg(workspace.path())
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);

    // editable_plugin_fixture is used by test_example.py → should be visible
    assert!(
        stdout.contains("editable_plugin_fixture"),
        "Used editable fixture should appear with --skip-unused.\nGot:\n{}",
        stdout
    );

    // local_fixture is also used → visible
    assert!(
        stdout.contains("local_fixture"),
        "Used local fixture should appear with --skip-unused.\nGot:\n{}",
        stdout
    );
}

#[test]
#[timeout(30000)]
fn test_e2e_editable_install_fixtures_only_unused() {
    // With --only-unused, the editable fixture (which IS used) should be hidden.
    let (workspace, _src) = setup_editable_install_workspace();

    let mut cmd = Command::cargo_bin("pytest-language-server").unwrap();
    let output = cmd
        .arg("fixtures")
        .arg("list")
        .arg("--only-unused")
        .arg(workspace.path())
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Both fixtures are used → neither should appear in only-unused output
    assert!(
        !stdout.contains("editable_plugin_fixture"),
        "Used editable fixture should NOT appear with --only-unused.\nGot:\n{}",
        stdout
    );
    assert!(
        !stdout.contains("local_fixture"),
        "Used local fixture should NOT appear with --only-unused.\nGot:\n{}",
        stdout
    );
}