deps-core 2.0.0

Core abstractions for deps-lsp: caching, errors, and traits
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
// `unwrap_used` only fires inside this module's own `#[cfg(all(test, feature = "test-util"))]
// mod tests`, which isn't compiled in a plain `--lib` build, so `#[expect]` would be
// unfulfilled there; kept as a plain `#[allow]`.
#![allow(clippy::unwrap_used)]
#![expect(
    clippy::expect_used,
    reason = "this entire module is test-only fixture/helper infrastructure (most of it gated \
              behind the test-util feature); every .expect() here is on a fixture Mutex/UTF-8 \
              conversion that cannot fail in a single-threaded test harness"
)]

//! Test fixtures and helpers shared across ecosystem crates.
//!
//! Test fixtures throughout the workspace write absolute paths in Unix
//! style (e.g. `/project/Cargo.toml`) for readability. `Url::from_file_path`
//! requires a platform-absolute path, and a Unix-style path is not
//! recognized as absolute on Windows (no drive letter), so calling it
//! directly with such a literal panics on Windows only. [`test_uri`]
//! normalizes the path per host platform before constructing the [`url::Url`].
//!
//! [`assert_dot_segment_gated_or_contained`]/[`assert_dot_segment_gated_or_contained_transformed`]
//! guard the recurring dot-segment / unvalidated-URL-sink defect class (#337, #341, #349,
//! #357, #361, #365, #371) against further recurrence.
//!
//! [`capture_tracing_output`]/[`capture_tracing_output_async`] let a test assert a
//! `tracing` call actually fired (originally added standalone in `deps-swift` for #357,
//! then duplicated per-crate for #380/#378's `warn_rejected_value` coverage before being
//! consolidated here). Backed by one process-wide subscriber rather than a fresh one per
//! call, to avoid an untraced sibling test permanently poisoning a shared callsite's
//! `tracing-core` `Interest` cache before the capturing test's own subscriber was installed
//! (#1006).
//!
//! [`github_token_configured`]/[`unwrap_or_skip_github_rate_limit`] let a live,
//! GitHub-API-backed `#[ignore]`d test distinguish "the unauthenticated 60 req/h rate limit
//! was hit because no `GITHUB_TOKEN` is configured" (expected in CI/local runs without a
//! token — skip) from "the live API genuinely changed or broke" (a real failure, even with
//! a token present) (#1283). [`should_skip_on_empty_result`] builds on the same primitive
//! for a test whose production call swallows the underlying error to an empty/missing
//! result rather than surfacing a `Result` directly.

mod stub_formatter;
#[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
pub use stub_formatter::StubFormatter;

/// Builds a [`url::Url`] from a Unix-style absolute test path.
///
/// On Windows, a synthetic `C:` drive is prefixed so the path is
/// recognized as absolute; on other platforms the path is used as-is.
///
/// # Panics
///
/// Panics if the resulting path is not a valid file URL. This is a test
/// helper: fixture paths are expected to always be well-formed.
///
/// # Examples
///
/// ```
/// use deps_core::test_util::test_uri;
///
/// let uri = test_uri("/project/Cargo.toml");
/// assert!(uri.path().ends_with("Cargo.toml"));
/// ```
#[must_use]
pub fn test_uri(unix_path: &str) -> url::Url {
    #[cfg(windows)]
    let owned;
    #[cfg(windows)]
    let path: &str = {
        owned = format!("C:{unix_path}");
        &owned
    };
    #[cfg(not(windows))]
    let path: &str = unix_path;

    url::Url::from_file_path(path).expect("test_uri: fixture path must be a valid file URL")
}

/// Runs [`crate::lsp_helpers::fallback_edit_excludes_newer`] end to end against a real ecosystem.
///
/// Parses `content`, locates the dependency named `dep_name`, renders the edit for `fallback`
/// via `formatter`, and re-parses through `ecosystem` (spec 076 T005).
///
/// Extracted from ~14 near-identical per-ecosystem-crate test helpers (spec 076 fix-cycle
/// finding #8/DRY) into one shared implementation — every ecosystem crate's own
/// `fallback_edit_outcome` test helper should build its `content`/`uri` fixture, then delegate
/// here instead of duplicating the parse/render/reparse/verdict plumbing.
///
/// # Panics
///
/// Panics if `content` fails to parse, `dep_name` is not found among its dependencies, or the
/// fallback edit cannot be rendered — this is a test helper, not production code, so a
/// malformed fixture should fail loudly rather than degrade to a misleading verdict.
///
/// # Examples
///
/// `Ecosystem` is sealed (only implementable inside this crate), and every concrete
/// implementation lives in a downstream `deps-<ecosystem>` crate, so this cannot be exercised
/// from a `deps-core` doc-test without a circular dev-dependency — see any of the ~14
/// ecosystem crates' own `ecosystem.rs` test modules (e.g. `deps-cargo`) for a real call site.
///
/// ```ignore
/// let verdict = deps_core::test_util::fallback_edit_outcome(
///     &ecosystem, &formatter, &uri, &content, "pkg", "1.1.0", &["1.2.0", "1.1.0"],
/// )
/// .await;
/// assert_eq!(verdict, deps_core::lsp_helpers::FallbackEditVerdict::Writable);
/// ```
#[cfg(feature = "test-util")]
pub async fn fallback_edit_outcome(
    ecosystem: &dyn crate::Ecosystem,
    formatter: &dyn crate::lsp_helpers::EcosystemFormatter,
    uri: &url::Url,
    content: &str,
    dep_name: &str,
    fallback: &str,
    available: &[&str],
) -> crate::lsp_helpers::FallbackEditVerdict {
    let parsed = ecosystem
        .parse_manifest(content, uri)
        .await
        .expect("manifest must parse");
    let dep = parsed
        .dependencies()
        .into_iter()
        .find(|d| d.name().as_str() == dep_name)
        .expect("dependency present");
    let fallback = crate::ConcreteVersion::new(fallback);
    let new_text = crate::edit::replacement_text(
        formatter,
        dep,
        &fallback,
        dep.version_requirement()
            .expect("declared requirement")
            .as_str(),
    )
    .expect("replacement text");
    let candidate = crate::edit::ManifestEdit {
        range: dep.version_range().expect("version range"),
        new_text,
    };
    let reparse = crate::edit::EcosystemReparse { ecosystem, uri };
    let available: Vec<crate::ConcreteVersion> = available
        .iter()
        .map(|v| crate::ConcreteVersion::new(*v))
        .collect();

    crate::lsp_helpers::fallback_edit_excludes_newer(
        formatter, &reparse, content, dep, &candidate, &fallback, &available,
    )
}

/// Builds a [`crate::osv::VulnKey`] from a plain name, for [`crate::osv::VulnerabilityMap`]
/// test fixtures.
///
/// Fixture-only: production code must derive a key via [`crate::osv::vuln_key_for`] or
/// [`crate::osv::vulnerability_keys`], never construct one directly. Unlike [`crate::osv::vuln_key_for`],
/// this does **not** normalize `name` — it yields the same key `vuln_key_for` would for a
/// unique, non-synthetic-range dependency whose already-normalized name is `name`.
///
/// # Examples
///
/// ```
/// use deps_core::test_util::vuln_key;
///
/// let key = vuln_key("time");
/// assert_eq!(key.as_str(), "time");
/// ```
#[must_use]
pub fn vuln_key(name: &str) -> crate::osv::VulnKey {
    crate::osv::VulnKey::from_name(name.to_string())
}

/// Minimal [`crate::Metadata`] fixture for tests that only care about a package's name and
/// latest version — e.g. exercising [`crate::Ecosystem::completion_insert_text`].
///
/// Intended to replace the ~25-line `impl Metadata for MockMetadata` block hand-copied
/// inside individual test bodies (`deps-go`, `deps-gitlab-ci`) — those two crates are not
/// yet migrated to this fixture, tracked as follow-up work (#758). Every [`crate::Metadata`]
/// field beyond [`Self::new`]'s two arguments is `None`.
///
/// # Examples
///
/// ```
/// use deps_core::Metadata;
/// use deps_core::test_util::MockMetadata;
///
/// let meta = MockMetadata::new("serde", "1.0.214");
/// assert_eq!(meta.name().as_str(), "serde");
/// assert_eq!(meta.latest_version().as_str(), "1.0.214");
/// assert_eq!(meta.description(), None);
/// ```
#[derive(Clone)]
pub struct MockMetadata {
    name: crate::PackageName,
    latest_version: crate::ConcreteVersion,
}

impl MockMetadata {
    /// Builds a fixture reporting `name` and `latest_version`; every other
    /// [`crate::Metadata`] field defaults to `None`.
    #[must_use]
    pub fn new(
        name: impl Into<crate::PackageName>,
        latest_version: impl Into<crate::ConcreteVersion>,
    ) -> Self {
        Self {
            name: name.into(),
            latest_version: latest_version.into(),
        }
    }
}

impl crate::Metadata for MockMetadata {
    fn name(&self) -> &crate::PackageName {
        &self.name
    }

    fn description(&self) -> Option<&str> {
        None
    }

    fn repository(&self) -> Option<&str> {
        None
    }

    fn documentation(&self) -> Option<&str> {
        None
    }

    fn latest_version(&self) -> &crate::ConcreteVersion {
        &self.latest_version
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// [`MockVersion`]'s `is_prerelease` behavior — see [`MockVersion::with_prerelease`].
///
/// Defaults to [`Self::MarkerDefault`] rather than hardcoding `false`: [`crate::Version`]'s
/// own provided `is_prerelease` method delegates to
/// [`crate::has_default_prerelease_marker`] against the version string, and a `MockVersion`
/// that silently returned `false` for e.g. `"1.0.0-rc.1"` would diverge from every real
/// `Version` implementor that doesn't override this method — the exact defect class this
/// fixture exists to prevent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Prerelease {
    /// Delegates to [`crate::has_default_prerelease_marker`] against the version string,
    /// matching [`crate::Version::is_prerelease`]'s own provided-method default.
    MarkerDefault,
    /// Hardcoded, ignoring the version string.
    Forced(bool),
}

/// A configurable [`crate::Version`] fixture (issue #1559).
///
/// Replaces the ~15-line `impl Version for MockVersion`/`SomeNameVersion` blocks hand-copied
/// per test file across `deps-engine`, `deps-lsp`, and `deps-maven`. Every field beyond
/// [`Self::new`]'s version defaults to the same value the trait's own provided methods
/// return, so a fixture that only cares about the version string needs no builder call at
/// all.
///
/// # Examples
///
/// ```
/// use deps_core::Version;
/// use deps_core::RemovalStatus;
/// use deps_core::test_util::MockVersion;
///
/// let v = MockVersion::new("1.2.3").yanked(true);
/// assert_eq!(v.version_string().as_str(), "1.2.3");
/// assert_eq!(v.removal_status(), RemovalStatus::Yanked);
/// ```
#[derive(Debug, Clone)]
pub struct MockVersion {
    version: crate::ConcreteVersion,
    published_at: Option<crate::freshness::PublishTime>,
    removal_status: crate::RemovalStatus,
    prerelease: Prerelease,
    license: Vec<String>,
}

impl MockVersion {
    /// Builds a fixture reporting `version`; every other [`crate::Version`] field defaults
    /// to that trait's own provided-method default (not yanked/deprecated, marker-based
    /// prerelease detection, no publish time, no license).
    #[must_use]
    pub fn new(version: impl Into<crate::ConcreteVersion>) -> Self {
        Self {
            version: version.into(),
            published_at: None,
            removal_status: crate::RemovalStatus::Available,
            prerelease: Prerelease::MarkerDefault,
            license: Vec::new(),
        }
    }

    /// Sets [`crate::Version::published_at`]'s return value.
    #[must_use]
    pub const fn with_published_at(mut self, published_at: crate::freshness::PublishTime) -> Self {
        self.published_at = Some(published_at);
        self
    }

    /// Sets [`crate::Version::removal_status`]'s return value directly.
    #[must_use]
    pub const fn with_removal_status(mut self, removal_status: crate::RemovalStatus) -> Self {
        self.removal_status = removal_status;
        self
    }

    /// Convenience over [`Self::with_removal_status`] for the common yanked/not-yanked case.
    #[must_use]
    pub fn yanked(mut self, yanked: bool) -> Self {
        self.removal_status = crate::RemovalStatus::from_yanked(yanked);
        self
    }

    /// Forces [`crate::Version::is_prerelease`]'s return value, overriding the default
    /// marker-based detection against the version string.
    #[must_use]
    pub const fn with_prerelease(mut self, prerelease: bool) -> Self {
        self.prerelease = Prerelease::Forced(prerelease);
        self
    }

    /// Sets [`crate::Version::license`]'s return value.
    #[must_use]
    pub fn with_license(mut self, license: Vec<String>) -> Self {
        self.license = license;
        self
    }
}

impl crate::Version for MockVersion {
    fn version_string(&self) -> &crate::ConcreteVersion {
        &self.version
    }

    fn removal_status(&self) -> crate::RemovalStatus {
        self.removal_status
    }

    fn is_prerelease(&self) -> bool {
        match self.prerelease {
            Prerelease::MarkerDefault => {
                crate::has_default_prerelease_marker(self.version.as_str())
            }
            Prerelease::Forced(forced) => forced,
        }
    }

    fn published_at(&self) -> Option<crate::freshness::PublishTime> {
        self.published_at
    }

    fn license(&self) -> &[String] {
        &self.license
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// What [`MockRegistry`]'s `search_raw` does when called — see [`MockRegistry::with_search`].
pub enum SearchBehavior {
    /// Returns an empty result list — the common case for a fixture whose test never
    /// exercises search.
    Empty,
    /// Returns these fixed results.
    Results(Vec<MockMetadata>),
    /// Panics with this message, synchronously, before any future is even constructed — for
    /// asserting a caller's guard short-circuits before ever reaching the registry (e.g. a
    /// prefix-length gate that must reject before calling `search`).
    Panic(&'static str),
}

/// A configurable [`crate::Registry`] fixture (issue #1559).
///
/// Replaces the ~30-40 line `impl Registry for ...` doubles duplicated across
/// `deps-engine`'s, `deps-lsp`'s, and `deps-maven`'s test modules for the common "fixed
/// version list plus fixed/empty/panicking search" shape.
///
/// `get_latest_matching`/`select_latest_matching` both pick the first
/// version in [`Self::with_versions`]'s list whose [`crate::Version::removal_status`]
/// doesn't [`crate::RemovalStatus::blocks_resolution`] — the same "versions sorted
/// newest-first" convention every real registry documents, so a test controls which
/// version is "latest" purely through list order.
///
/// Keep a bespoke `impl Registry` where a test genuinely needs custom selection or
/// error-injection logic this fixture doesn't model (a registry that times out, fails, or
/// diverges between `get_versions` and `get_latest_matching` per package) — e.g.
/// `deps-engine`'s `NoListPickRegistry`, which reproduces Go's `/@v/list` divergence.
///
/// # Examples
///
/// ```
/// use deps_core::Registry;
/// use deps_core::PackageName;
/// use deps_core::SelectionContext;
/// use deps_core::VersionReq;
/// use deps_core::test_util::{MockRegistry, MockVersion};
///
/// #[tokio::main]
/// async fn main() {
///     let registry = MockRegistry::new().with_versions(vec![MockVersion::new("1.2.3")]);
///     let versions = registry.get_versions(&PackageName::new("pkg")).await.unwrap();
///     assert_eq!(versions.len(), 1);
/// }
/// ```
#[derive(Default)]
pub struct MockRegistry {
    versions: Vec<MockVersion>,
    search: Option<SearchBehavior>,
}

impl MockRegistry {
    /// A registry with no versions and an empty search result — the `NoopRegistry`/
    /// `StubRegistry` shape most tests that never exercise a registry at all reach for.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the fixed version list `get_versions`/`get_latest_matching`/
    /// `select_latest_matching` serve — sorted newest-first, per
    /// [`crate::Registry::get_versions`]'s own contract.
    #[must_use]
    pub fn with_versions(mut self, versions: Vec<MockVersion>) -> Self {
        self.versions = versions;
        self
    }

    /// Sets what `search_raw` does when called — see [`SearchBehavior`].
    #[must_use]
    pub fn with_search(mut self, search: SearchBehavior) -> Self {
        self.search = Some(search);
        self
    }
}

impl crate::Registry for MockRegistry {
    fn get_versions<'a>(
        &'a self,
        _name: &'a crate::PackageName,
    ) -> crate::ecosystem::BoxFuture<'a, crate::Result<Vec<Box<dyn crate::Version>>>> {
        let versions: Vec<Box<dyn crate::Version>> = self
            .versions
            .iter()
            .cloned()
            .map(|v| Box::new(v) as Box<dyn crate::Version>)
            .collect();
        Box::pin(async move { Ok(versions) })
    }

    fn get_latest_matching<'a>(
        &'a self,
        _name: &'a crate::PackageName,
        _req: &'a crate::VersionReq,
        _selection_context: &'a crate::SelectionContext,
    ) -> crate::ecosystem::BoxFuture<'a, crate::Result<Option<Box<dyn crate::Version>>>> {
        let picked: Option<Box<dyn crate::Version>> = self
            .versions
            .iter()
            .find(|v| !v.removal_status.blocks_resolution())
            .cloned()
            .map(|v| Box::new(v) as Box<dyn crate::Version>);
        Box::pin(async move { Ok(picked) })
    }

    fn search_raw<'a>(
        &'a self,
        _query: &'a str,
        _limit: usize,
    ) -> crate::ecosystem::BoxFuture<'a, crate::Result<Vec<Box<dyn crate::Metadata>>>> {
        match self.search.as_ref().unwrap_or(&SearchBehavior::Empty) {
            SearchBehavior::Empty => Box::pin(async move { Ok(vec![]) }),
            SearchBehavior::Results(results) => {
                let results: Vec<Box<dyn crate::Metadata>> = results
                    .iter()
                    .cloned()
                    .map(|m| Box::new(m) as Box<dyn crate::Metadata>)
                    .collect();
                Box::pin(async move { Ok(results) })
            }
            SearchBehavior::Panic(msg) => panic!("{msg}"),
        }
    }

    fn select_latest_matching(
        &self,
        versions: &[Box<dyn crate::Version>],
        _req: &crate::VersionReq,
        _selection_context: &crate::SelectionContext,
    ) -> Option<usize> {
        versions
            .iter()
            .position(|v| !v.removal_status().blocks_resolution())
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Canonical adversarial identifier values for the recurring dot-segment /
/// unvalidated-URL-sink defect class (#337, #341, #349, #357, #361).
///
/// A manifest-declared package name, scope, or coordinate segment spliced into a
/// registry/API URL via `format!`/string interpolation without validation. A bare `.`/`..`
/// survives naive percent-encoding unchanged (`.` is an RFC 3986 unreserved character) and
/// is silently removed by a URL parser's dot-segment normalization once the string is
/// assembled and parsed, letting the request escape the intended host or path prefix; the
/// remaining entries cover a would-be traversal attempt, whitespace, and query/fragment
/// injection.
pub const ADVERSARIAL_URL_SEGMENTS: &[&str] = &[
    ".",
    "..",
    "../../etc/passwd",
    "a b",
    "a?b=1",
    "a#frag",
    "%2e%2e",
];

/// Exercises one ecosystem's identifier-to-URL sink against every
/// [`ADVERSARIAL_URL_SEGMENTS`] entry.
///
/// `resolve` should mirror the real request path: apply whatever validation gate
/// (`is_dot_segment`, `is_safe_package_name`, `is_safe_maven_coordinate_segment`, ...) the
/// production code runs before building the request, returning `None` when the gate would
/// reject the identifier (the request is never built, so there is nothing to check), or
/// `Some(url)` with the URL the identifier resolves to when it reaches the real
/// fetch-URL-builder function directly.
///
/// For every input that reaches `Some(url)`, asserts `url` parses, stays under
/// `expected_host`/`expected_path_prefix`, and that `segment` itself survives the round
/// trip. That last check is the one that actually catches a missing/deleted gate: for an
/// ecosystem whose identifier is the *first* path component (no fixed sub-path to nest
/// under, e.g. `deps-cargo`'s sparse-index path or `deps-npm`'s bare
/// `registry.npmjs.org/{name}`), `expected_path_prefix` can only ever be `"/"` — trivially
/// satisfied by any path — so the prefix check alone is a tautology there. Deleting the
/// real gate collapses `..`/`.` via dot-segment normalization, which removes it from the
/// path entirely; the survival check catches that regardless of how trivial
/// `expected_path_prefix` is, so passing `"/"` is fine as long as this check is also in
/// effect.
///
/// The survival check itself takes one of two forms depending on `segment`:
/// - For a bare `.`/`..` (the only values `url`'s dot-segment normalization treats
///   specially): some path segment, once percent-decoded, must *start with* that value.
///   A whole-path substring search would be too weak here — a coincidental `.` baked into
///   a static suffix the sink always appends (e.g. `.json`) would satisfy `contains` even
///   if the real `.`/`..` segment was silently removed, leaving no trace of it anywhere.
///   `starts_with` (not exact equality) still accommodates a sink that glues the
///   identifier directly onto a static suffix with no separator (e.g. `deps-bundler`'s
///   `versions_url`, which decodes a `..` identifier to the segment `"..json"`).
/// - For every other adversarial entry: the percent-decoded *whole path* must contain
///   `segment` (or `transform(segment)`) as a substring — safe here since none of those
///   entries collides with a static suffix the way a bare `.` does.
///
/// # Panics
///
/// Panics if a returned URL fails to parse, escapes `expected_host` or
/// `expected_path_prefix`, if the (possibly transformed) segment is empty despite
/// `resolve` returning `Some`, or if the segment does not survive per the rules above.
///
/// # Examples
///
/// ```
/// use deps_core::test_util::assert_dot_segment_gated_or_contained;
///
/// fn build(name: &str) -> String {
///     format!("https://example.com/api/{}", urlencoding::encode(name))
/// }
///
/// fn resolve(name: &str) -> Option<String> {
///     (name != "." && name != "..").then(|| build(name))
/// }
///
/// assert_dot_segment_gated_or_contained(resolve, "example.com", "/api/");
/// ```
pub fn assert_dot_segment_gated_or_contained(
    resolve: impl Fn(&str) -> Option<String>,
    expected_host: &str,
    expected_path_prefix: &str,
) {
    assert_dot_segment_gated_or_contained_transformed(
        resolve,
        str::to_string,
        expected_host,
        expected_path_prefix,
    );
}

/// As [`assert_dot_segment_gated_or_contained`], but for a `resolve` whose production gate
/// legitimately transforms the identifier before it reaches the URL builder.
///
/// E.g. PyPI's PEP 503 `name::normalize`, which collapses `.`/`_`/`-` runs, rather than
/// passing the identifier through unchanged. `transform` computes what the identifier looks
/// like once it reaches the sink, so the survival check compares the decoded path against
/// that instead of the raw adversarial `segment` (which would otherwise never appear
/// literally, producing a false-positive failure with no real bug behind it).
///
/// # Panics
///
/// Same conditions as [`assert_dot_segment_gated_or_contained`], with `transform(segment)`
/// in place of `segment` for the survival check.
pub fn assert_dot_segment_gated_or_contained_transformed(
    resolve: impl Fn(&str) -> Option<String>,
    transform: impl Fn(&str) -> String,
    expected_host: &str,
    expected_path_prefix: &str,
) {
    for segment in ADVERSARIAL_URL_SEGMENTS {
        let Some(built) = resolve(segment) else {
            continue;
        };
        let parsed = url::Url::parse(&built).unwrap_or_else(|e| {
            panic!("adversarial segment {segment:?} produced an unparsable URL {built:?}: {e}")
        });
        assert_eq!(
            parsed.host_str(),
            Some(expected_host),
            "adversarial segment {segment:?} escaped host: {built}"
        );
        assert!(
            parsed.path().starts_with(expected_path_prefix),
            "adversarial segment {segment:?} escaped path prefix {expected_path_prefix:?}: {built}"
        );
        let expected_fragment = transform(segment);
        assert!(
            !expected_fragment.is_empty(),
            "adversarial segment {segment:?} transformed to an empty fragment but `resolve` \
             still returned Some(url) — an empty identifier must be rejected (return `None`) \
             before reaching the sink, since an empty survival check would trivially pass \
             (\"\".contains(\"\") is always true) and hide a real gate deletion"
        );
        if expected_fragment == "." || expected_fragment == ".." {
            // A whole-path substring search is too weak: a coincidental `.` in a static
            // suffix (e.g. `.json`) would satisfy `contains` even if the real `.`/`..`
            // segment was silently removed by dot-segment normalization. Require a
            // per-segment match instead — `starts_with`, not exact equality, accommodates a
            // sink gluing the identifier onto a static suffix with no separator (e.g.
            // deps-bundler's `versions_url` decoding `..` to `"..json"`).
            let matched = parsed.path_segments().is_some_and(|mut segs| {
                segs.any(|seg| {
                    urlencoding::decode(seg)
                        .is_ok_and(|decoded| decoded.starts_with(expected_fragment.as_str()))
                })
            });
            assert!(
                matched,
                "adversarial segment {segment:?} (expected to survive as {expected_fragment:?}) \
                 did not survive as its own path segment (silently dropped/collapsed by \
                 dot-segment normalization?): built url {built}"
            );
        } else {
            let decoded_path = urlencoding::decode(parsed.path()).unwrap_or_else(|e| {
                panic!(
                    "adversarial segment {segment:?}'s URL path failed to percent-decode: {built:?}: {e}"
                )
            });
            assert!(
                decoded_path.contains(&expected_fragment),
                "adversarial segment {segment:?} (expected to survive as {expected_fragment:?}) \
                 did not survive intact in the decoded path (silently dropped/collapsed by \
                 dot-segment normalization?): decoded path {decoded_path:?}, built url {built}"
            );
        }
    }
}

// Gated separately from the rest of this module (which also compiles under plain `cfg(test)`):
// `tracing-subscriber` is optional, enabled only by `test-util`, so bare `cfg(test)` alone
// would fail to resolve it.
//
// Installs exactly one process-wide subscriber (guarded by `Once`) rather than a fresh scoped
// one per call. `tracing-core` caches a callsite's `Interest` for the process lifetime on
// first hit; with the old per-call design, an untraced sibling test's dispatcher could
// contribute `Interest::never()` before the capturing subscriber installed, permanently
// poisoning the callsite (#1006), making the bug intermittent. A single global subscriber
// removes the multiple-dispatcher scenario; its filter always reports `Interest::sometimes()`
// (see `ThreadLocalLevelFilter` below) so the cached verdict never finalizes to a terminal
// `never`/`always`.
#[cfg(feature = "test-util")]
mod tracing_capture {
    use std::cell::{Cell, RefCell};
    use std::sync::Once;

    use tracing_subscriber::Layer;
    use tracing_subscriber::layer::{Context, Filter, SubscriberExt};

    thread_local! {
        /// This thread's own capture buffer. Never shared across threads, so tests running
        /// concurrently on different threads never see each other's captured output.
        static BUFFER: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
        /// `Some(max_level)` while this thread is inside a `capture_tracing_output*` call,
        /// `None` otherwise — gates capture so untraced code sharing this OS thread (a sibling
        /// test, or code outside the `f`/`fut` under capture) is never written to `BUFFER`.
        static MAX_LEVEL: Cell<Option<tracing::Level>> = const { Cell::new(None) };
    }

    #[derive(Clone, Default)]
    struct ThreadLocalWriter;

    impl std::io::Write for ThreadLocalWriter {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            BUFFER.with(|b| b.borrow_mut().extend_from_slice(buf));
            Ok(buf.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for ThreadLocalWriter {
        type Writer = Self;

        fn make_writer(&'a self) -> Self::Writer {
            self.clone()
        }
    }

    /// Per-thread level gate that never lets `tracing-core` cache a callsite verdict.
    ///
    /// The global subscriber must accept `TRACE` (the most permissive level any caller here
    /// needs) so it can serve every `capture_tracing_output*` caller from one process-wide
    /// instance, so per-call level filtering (`capture_tracing_output` vs `_at`) happens here
    /// instead, dynamically, per thread. Returning `false`/`true` from [`Filter::enabled`]
    /// without overriding `callsite_enabled` keeps the default `Interest::sometimes()` for
    /// every callsite this subscriber sees — the load-bearing property that stops any callsite
    /// from ever being cached `never`/`always` based on whichever thread happens to touch it
    /// first (the root cause of #1006).
    ///
    /// This filter provides no `max_level_hint`, so once any capture helper installs the global
    /// subscriber, tracing's process-wide max-level filter rises to `TRACE` for the rest of the
    /// test binary — negligible in a test process, but a real side effect the old per-call
    /// scoped subscribers didn't have.
    struct ThreadLocalLevelFilter;

    impl<S> Filter<S> for ThreadLocalLevelFilter {
        fn enabled(&self, meta: &tracing::Metadata<'_>, _cx: &Context<'_, S>) -> bool {
            MAX_LEVEL.with(|cell| cell.get().is_some_and(|max| *meta.level() <= max))
        }
    }

    static INIT: Once = Once::new();

    /// Installs the single process-wide capturing subscriber the first time any
    /// `capture_tracing_output*` call runs; a no-op on every later call.
    fn ensure_installed() {
        INIT.call_once(|| {
            let fmt_layer = tracing_subscriber::fmt::layer()
                .with_writer(ThreadLocalWriter)
                .without_time()
                .with_target(false)
                .with_filter(ThreadLocalLevelFilter);
            let subscriber = tracing_subscriber::registry().with(fmt_layer);
            tracing::subscriber::set_global_default(subscriber)
                .expect("test-capture tracing subscriber must install exactly once per process");
            // `set_global_default` already rebuilds the interest cache as a side effect, so
            // this explicit call is defense-in-depth insurance, kept in case that internal
            // behavior ever changes.
            tracing::callsite::rebuild_interest_cache();
        });
    }

    /// Resets this thread's capture level on drop, including on unwind out of `f`/`fut`.
    ///
    /// Without this, a panicking capture would leave `MAX_LEVEL` stuck `Some` for whatever
    /// test next reuses this OS thread — e.g. plain `cargo test`'s shared thread pool (unlike
    /// `cargo nextest`, which runs each test in its own process).
    struct CaptureGuard;

    impl Drop for CaptureGuard {
        fn drop(&mut self) {
            MAX_LEVEL.with(|cell| cell.set(None));
        }
    }

    fn begin_capture(max_level: tracing::Level) -> CaptureGuard {
        ensure_installed();
        // Unconditional `assert!`, not `debug_assert!`: this is test-only utility code with no
        // perf-sensitive hot path (it only runs when a test calls a capture helper), so there is
        // no cost to catching a nested call in every build profile rather than compiling the
        // check out of release-profile test runs and silently corrupting output instead.
        assert!(
            MAX_LEVEL.with(Cell::get).is_none(),
            "nested capture_tracing_output* is not supported: the inner call's buffer/level \
             would silently clobber the outer call's"
        );
        BUFFER.with(|b| b.borrow_mut().clear());
        MAX_LEVEL.with(|cell| cell.set(Some(max_level)));
        CaptureGuard
    }

    fn take_captured() -> String {
        BUFFER.with(|b| {
            String::from_utf8(std::mem::take(&mut *b.borrow_mut()))
                .expect("tracing output is valid utf8")
        })
    }

    pub(super) fn capture_at(max_level: tracing::Level, f: impl FnOnce()) -> String {
        let _guard = begin_capture(max_level);
        f();
        take_captured()
    }

    pub(super) async fn capture_async_at(
        max_level: tracing::Level,
        fut: impl std::future::Future<Output = ()>,
    ) -> String {
        let _guard = begin_capture(max_level);
        fut.await;
        take_captured()
    }
}

/// Captures `tracing` output emitted synchronously during `f` into a `String`.
///
/// Lets a test assert a `tracing::warn!`/`info!` call actually fired — e.g.
/// [`crate::lsp_helpers::warn_rejected_value`] — without a real logging sink or a
/// network-dependent end-to-end path. Defaults to `INFO`, not `WARN`: some call sites emit
/// `tracing::info!` (e.g. deps-swift's release-dates token-gate skip) that a WARN-only filter
/// would silently drop, alongside every `warn_rejected_value`/other WARN-level emission this
/// helper exists to assert on. Filters below `INFO`, so a `tracing::debug!`/`trace!` emission
/// never appears here — use [`capture_tracing_output_at`] for those.
///
/// Backed by one process-wide subscriber (installed lazily, once) writing into a per-thread
/// buffer, rather than a fresh scoped subscriber per call — a fresh-per-call subscriber let an
/// untraced sibling test permanently poison a shared callsite's `tracing-core` interest cache
/// before this call's own subscriber was ever installed (#1006).
///
/// # Examples
///
/// ```
/// use deps_core::test_util::capture_tracing_output;
///
/// let output = capture_tracing_output(|| tracing::warn!("something rejected"));
/// assert!(output.contains("something rejected"));
/// ```
#[cfg(feature = "test-util")]
#[must_use]
pub fn capture_tracing_output(f: impl FnOnce()) -> String {
    tracing_capture::capture_at(tracing::Level::INFO, f)
}

/// Like [`capture_tracing_output`], but capturing every level up to and including `max_level`
/// (e.g. `tracing::Level::DEBUG`).
///
/// Needed to positively assert a `tracing::debug!` line fired, or that a `tracing::warn!`
/// specifically (as opposed to any level) did not — [`capture_tracing_output`]'s fixed `INFO`
/// filter makes both assertions vacuous, since a `debug!` call is invisible there regardless of
/// whether the code under test emits it correctly.
///
/// # Examples
///
/// ```
/// use deps_core::test_util::capture_tracing_output_at;
///
/// let output =
///     capture_tracing_output_at(tracing::Level::DEBUG, || tracing::debug!("quiet detail"));
/// assert!(output.contains("quiet detail"));
/// ```
#[cfg(feature = "test-util")]
#[must_use]
pub fn capture_tracing_output_at(max_level: tracing::Level, f: impl FnOnce()) -> String {
    tracing_capture::capture_at(max_level, f)
}

/// Async counterpart of [`capture_tracing_output`], for a `tracing` emission inside an
/// `async fn`/`.await`ed future.
///
/// Requires `fut` to stay on one OS thread for its whole lifetime — true of a `#[tokio::test]`
/// using the default current-thread runtime flavor (every existing caller), but not of a
/// `flavor = "multi_thread"` test, where an awaited future can resume on a different worker
/// thread and would then read/write a different thread's capture buffer.
///
/// # Examples
///
/// ```
/// use deps_core::test_util::capture_tracing_output_async;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// let output = capture_tracing_output_async(async {
///     tracing::warn!("something rejected");
/// })
/// .await;
/// assert!(output.contains("something rejected"));
/// # }
/// ```
#[cfg(feature = "test-util")]
pub async fn capture_tracing_output_async(fut: impl std::future::Future<Output = ()>) -> String {
    tracing_capture::capture_async_at(tracing::Level::INFO, fut).await
}

/// Like [`capture_tracing_output_async`], but capturing every level up to and including
/// `max_level`.
///
/// The async counterpart of [`capture_tracing_output_at`], needed to assert a
/// `tracing::debug!` emission inside an `async fn`/`.await`ed future. Same single-OS-thread
/// requirement as [`capture_tracing_output_async`].
///
/// # Examples
///
/// ```
/// use deps_core::test_util::capture_tracing_output_async_at;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// let output = capture_tracing_output_async_at(tracing::Level::DEBUG, async {
///     tracing::debug!("quiet detail");
/// })
/// .await;
/// assert!(output.contains("quiet detail"));
/// # }
/// ```
#[cfg(feature = "test-util")]
pub async fn capture_tracing_output_async_at(
    max_level: tracing::Level,
    fut: impl std::future::Future<Output = ()>,
) -> String {
    tracing_capture::capture_async_at(max_level, fut).await
}

/// Captures a `#[tracing::instrument]` span's recorded field values during `fut`, via
/// `FmtSpan::NEW` on a scoped subscriber installed only for the call's duration.
///
/// Unlike [`capture_tracing_output_async`]/[`capture_tracing_output_async_at`], which share
/// one process-wide subscriber specifically to dodge #1006's `Interest`-caching flake, this
/// installs a fresh `tracing::subscriber::set_default` per call — a separate helper, not
/// `FmtSpan::NEW` turned on for that shared subscriber, which would make every *other*
/// `capture_tracing_output*` caller in the process newly see every entered span's field
/// values too, risking an unrelated, pre-existing secret-in-span-field leak surfacing as a
/// spurious failure elsewhere instead of being caught by that span's own test.
///
/// **Requires `cargo nextest`** (`.claude/rules/testing.md`), which gives each test its own
/// process. A per-call scoped subscriber like this one reintroduces #1006's exact flake under
/// a shared-process runner (plain `cargo test`, or any harness that runs multiple tests on one
/// process/thread pool): an untraced sibling test's dispatcher can contribute
/// `Interest::never()` for this span's callsite before this call's own subscriber installs,
/// permanently poisoning it for the rest of that process. Do not call this from a test binary
/// or harness that is not guaranteed to run under nextest's per-test-process isolation.
///
/// Same single-OS-thread requirement as [`capture_tracing_output_async`].
///
/// # Examples
///
/// ```
/// use deps_core::test_util::capture_tracing_span_fields_async;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// #[tracing::instrument(fields(value = 42))]
/// async fn traced() {}
///
/// let output = capture_tracing_span_fields_async(traced()).await;
/// assert!(output.contains("traced"));
/// assert!(output.contains("42"));
/// # }
/// ```
#[cfg(feature = "test-util")]
pub async fn capture_tracing_span_fields_async(
    fut: impl std::future::Future<Output = ()>,
) -> String {
    use tracing_subscriber::fmt::format::FmtSpan;

    #[derive(Clone)]
    struct BufWriter(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);

    impl std::io::Write for BufWriter {
        fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(data);
            Ok(data.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for BufWriter {
        type Writer = Self;

        fn make_writer(&'a self) -> Self::Writer {
            self.clone()
        }
    }

    let buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
    let subscriber = tracing_subscriber::fmt()
        .with_writer(BufWriter(std::sync::Arc::clone(&buf)))
        .with_span_events(FmtSpan::NEW)
        .without_time()
        .with_target(false)
        .finish();

    let guard = tracing::subscriber::set_default(subscriber);
    fut.await;
    drop(guard);

    let captured = buf.lock().unwrap().clone();
    String::from_utf8(captured).expect("tracing output is valid utf8")
}

/// Minimal [`crate::Dependency`] fixture used by [`stub_parse_result_with_dependencies`] —
/// only carries a name, since dependency-count-ceiling tests (#796) don't need version
/// requirements, ranges, or a real source.
struct StubDependency {
    name: crate::PackageName,
}

impl crate::Dependency for StubDependency {
    fn name(&self) -> &crate::PackageName {
        &self.name
    }

    fn name_range(&self) -> crate::position::Range {
        crate::position::Range::default()
    }

    fn version_requirement(&self) -> Option<&crate::VersionReq> {
        None
    }

    fn version_range(&self) -> Option<crate::position::Range> {
        None
    }

    fn source(&self) -> crate::parser::DependencySource {
        crate::parser::DependencySource::Registry
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Minimal [`crate::ParseResult`] fixture built by [`stub_parse_result_with_dependencies`].
struct StubParseResult {
    dependencies: Vec<StubDependency>,
    uri: url::Url,
}

impl crate::ParseResult for StubParseResult {
    fn dependencies(&self) -> Vec<&dyn crate::Dependency> {
        self.dependencies
            .iter()
            .map(|d| d as &dyn crate::Dependency)
            .collect()
    }

    fn workspace_root(&self) -> Option<&std::path::Path> {
        None
    }

    fn uri(&self) -> &url::Url {
        &self.uri
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Whether a non-empty `GITHUB_TOKEN` is configured in the current process's environment.
///
/// GitHub-backed live tests (Swift's registry is GitHub-tags-based) use this to tell an
/// expected unauthenticated-rate-limit skip apart from a genuine API regression (#1283).
///
/// Matches [`crate::github::GithubTagsClient::new`]'s own `.filter(|t| !t.is_empty())`
/// predicate exactly: an empty `GITHUB_TOKEN` (e.g. an unset GitHub Actions secret, or
/// `export GITHUB_TOKEN=$(gh auth token)` when `gh` isn't authenticated — the exact remedy
/// [`crate::github::github_rate_limit_error`]'s message prints) makes the client go
/// unauthenticated the same as an unset one, so it must count as "not configured" here too.
/// The actual predicate is `is_configured_token`, a pure function over an already-read
/// `Option<String>` rather than reading the env var itself, since `std::env::set_var` is
/// `unsafe` (forbidden workspace-wide) and no test can mutate the real env var to exercise
/// this branching directly.
///
/// # Examples
///
/// ```
/// use deps_core::test_util::github_token_configured;
///
/// // No assertion on the value itself — it depends on the calling environment.
/// let _ = github_token_configured();
/// ```
#[must_use]
pub fn github_token_configured() -> bool {
    is_configured_token(std::env::var("GITHUB_TOKEN").ok())
}

/// Pure predicate behind [`github_token_configured`] — see its doc for why this is split out.
fn is_configured_token(token: Option<String>) -> bool {
    token.is_some_and(|t| !t.is_empty())
}

/// Unwraps `result`, or returns `None` after printing a skip notice on an expected rate limit.
///
/// The skip case is `result` holding an `Err` that is a **verified**
/// [`crate::DepsError::RateLimited`] with no `GITHUB_TOKEN` configured — the expected shape for
/// an unauthenticated GitHub-backed live test hitting the 60 req/h cap (#1283). `test_name` is
/// included in the skip notice and any panic message, to identify which test emitted them when
/// run with `--no-fail-fast`.
///
/// #1295 fix: `RateLimited { verified: RateLimitEvidence::Confirmed, .. }` is produced only
/// when `crate::cache` confirmed genuine exhaustion via the response's
/// `X-RateLimit-Remaining: 0` (primary limit) or a `Retry-After` header (secondary limit, which
/// does not always zero out `remaining` — critic S4) on a 403/429. Real GitHub API responses
/// carry at least one of these on a true rate limit, so a live unauthenticated run reliably
/// gets `verified: RateLimitEvidence::Confirmed` on that path. An unauthenticated 403 with
/// neither signal still classifies as `RateLimited`, but with
/// `verified: RateLimitEvidence::Inferred` — it falls through to the panic arm below instead of
/// being silently skipped, since it could be an abuse-detection false positive, an
/// access-restricted repo, or a genuine regression.
///
/// # Panics
///
/// Panics on any error other than a *verified* `RateLimited`, and on a verified `RateLimited`
/// itself when `GITHUB_TOKEN` *is* configured — in both cases the confirmed rate limit was not
/// the expected cause, so the failure is surfaced rather than silently skipped.
///
/// # Examples
///
/// ```
/// use deps_core::test_util::unwrap_or_skip_github_rate_limit;
///
/// let result: Result<u32, deps_core::DepsError> = Ok(42);
/// assert_eq!(
///     unwrap_or_skip_github_rate_limit(result, "doctest"),
///     Some(42)
/// );
/// ```
pub fn unwrap_or_skip_github_rate_limit<T>(
    result: Result<T, crate::DepsError>,
    test_name: &str,
) -> Option<T> {
    rate_limit_skip_decision(result, test_name, github_token_configured())
}

/// Pure decision behind [`unwrap_or_skip_github_rate_limit`], factored out so its 3 branches
/// (skip / panic on a rate limit with a token configured / panic on any other error) are
/// unit-testable with a synthetic `token_configured` value — see [`github_token_configured`]'s
/// doc for why the real env var can't be mutated in a test here.
fn rate_limit_skip_decision<T>(
    result: Result<T, crate::DepsError>,
    test_name: &str,
    token_configured: bool,
) -> Option<T> {
    match result {
        Ok(value) => Some(value),
        Err(crate::DepsError::RateLimited {
            message,
            verified: crate::RateLimitEvidence::Confirmed,
            ..
        }) if !token_configured => {
            eprintln!(
                "{test_name}: skipping — GitHub API rate-limited and no GITHUB_TOKEN is \
                 configured: {message}"
            );
            None
        }
        Err(e) => panic!(
            "{test_name}: unexpected error (GITHUB_TOKEN configured: {token_configured}): {e:?}"
        ),
    }
}

/// `true` when a caller should skip its own test (return early) after a degraded result.
///
/// `primary_is_empty` signals a degraded result; when it's `true`, `probe` is awaited and
/// this returns `true` only if that determines an expected rate limit. Otherwise (`probe`
/// proved the API healthy, or `primary_is_empty` was never true) this returns `false`,
/// meaning the caller should fall through to its own assertion, which then fails loudly.
///
/// Factors out the repeated "probe on an empty/missing primary result, skip only if that's
/// an expected unauthenticated rate limit, else fall through to fail loudly" shape 3
/// `#[ignore]`d live tests share (`deps-swift::ecosystem`, `deps-cli::check_integration`,
/// `deps-lsp::document::osv_scan`): each calls production code that swallows a registry
/// error to an empty `Vec`/missing entry (graceful degradation), so that emptiness alone
/// can't tell an expected rate limit apart from a real regression — `probe` re-exercises the
/// same host through a call that surfaces the real [`crate::DepsError`] instead (#1283).
///
/// # Examples
///
/// ```no_run
/// # async fn example(registry: &dyn deps_core::Registry) {
/// use deps_core::PackageName;
///
/// let direct = Vec::<()>::new(); // stand-in for a degraded completion result
/// if deps_core::test_util::should_skip_on_empty_result(
///     direct.is_empty(),
///     "doctest",
///     registry.get_versions(&PackageName::new("apple/swift-nio")),
/// )
/// .await
/// {
///     return;
/// }
/// # }
/// ```
pub async fn should_skip_on_empty_result<T>(
    primary_is_empty: bool,
    test_name: &str,
    probe: impl std::future::Future<Output = Result<T, crate::DepsError>>,
) -> bool {
    primary_is_empty
        && rate_limit_skip_decision(probe.await, test_name, github_token_configured()).is_none()
}

/// Test-only recorder proving an internal `Registry`-to-`Registry` delegation forwards the
/// [`crate::SelectionContext`] it actually received.
///
/// Instead of silently substituting a fabricated [`crate::SelectionContext::none()`] (#1444
/// M2/M3) — the "convention, not guarantee" bug class #1444 exists to close, for the
/// ecosystems (cargo, deno, go, pypi, nuget, gitlab-ci) whose own registry client reads
/// nothing from the context and so cannot be proven correct by any assertion on its *return
/// value* alone.
///
/// A production `Registry` implementor's `get_latest_matching`/`get_latest_matching_from`/
/// `select_latest_matching` body calls [`SelectionContextCapture::record`] as its first
/// statement, `#[cfg(test)]`-gated (zero cost and no behavior change outside test builds). A
/// test then calls [`SelectionContextCapture::reset`], drives the delegation path under test
/// with a distinguishable, non-[`crate::SelectionContext::none()`] context, and asserts
/// [`SelectionContextCapture::last`] equals exactly that context — proving the value reaching
/// the innermost delegate is the caller's own, not a fresh substitute. Thread-local, so
/// parallel `cargo nextest` test processes never interfere (each test binary/process has its
/// own thread-local state); tests using this recorder within the same crate should still avoid
/// running concurrently against a shared thread if the harness ever multi-threads a single
/// process's tests onto one thread pool with shared state elsewhere.
///
/// # Examples
///
/// ```
/// use deps_core::selection::{SelectionContext, StabilityFloor};
/// use deps_core::test_util::SelectionContextCapture;
///
/// SelectionContextCapture::reset();
/// let ctx = SelectionContext::with_minimum_stability(StabilityFloor::Rc);
/// SelectionContextCapture::record(&ctx);
/// assert_eq!(SelectionContextCapture::last(), Some(ctx));
/// ```
#[derive(Debug)]
pub struct SelectionContextCapture;

thread_local! {
    static CAPTURED_SELECTION_CONTEXT: std::cell::Cell<Option<crate::SelectionContext>> =
        const { std::cell::Cell::new(None) };
}

impl SelectionContextCapture {
    /// Records `ctx` as the most recently observed [`crate::SelectionContext`] on this
    /// thread. Call from inside a `Registry` impl's `get_latest_matching`/
    /// `get_latest_matching_from`/`select_latest_matching` body, `#[cfg(test)]`-gated.
    pub fn record(ctx: &crate::SelectionContext) {
        CAPTURED_SELECTION_CONTEXT.with(|c| c.set(Some(*ctx)));
    }

    /// Clears any previously recorded context. Call before exercising the delegation path
    /// under test, so a leftover value from an earlier test on the same thread can't produce
    /// a false pass.
    pub fn reset() {
        CAPTURED_SELECTION_CONTEXT.with(|c| c.set(None));
    }

    /// The most recently [`Self::record`]ed context since the last [`Self::reset`], if any.
    #[must_use]
    pub fn last() -> Option<crate::SelectionContext> {
        CAPTURED_SELECTION_CONTEXT.with(std::cell::Cell::get)
    }
}

/// Builds a [`crate::ParseResult`] fixture with `count` synthetic dependencies.
///
/// Names them `"dep-0"`, `"dep-1"`, ... — for tests exercising dependency-count-ceiling
/// logic (#796) without needing a real ecosystem crate's parser.
///
/// # Examples
///
/// ```
/// use deps_core::ParseResult;
/// use deps_core::test_util::stub_parse_result_with_dependencies;
///
/// let parsed = stub_parse_result_with_dependencies(3);
/// assert_eq!(parsed.dependencies().len(), 3);
/// ```
#[must_use]
pub fn stub_parse_result_with_dependencies(count: usize) -> Box<dyn crate::ParseResult> {
    Box::new(StubParseResult {
        dependencies: (0..count)
            .map(|i| StubDependency {
                name: crate::PackageName::new(format!("dep-{i}")),
            })
            .collect(),
        uri: test_uri("/project/manifest.toml"),
    })
}

/// Builds a [`crate::GossipFindings`] fixture for one package version, with an optional
/// active-or-expired cooldown.
///
/// For a cross-crate test (e.g. `deps-engine`'s fetch-level GOSSIP filter, spec 074) that
/// needs a value of this `#[non_exhaustive]` type without going through a live/mocked
/// `DepsDevClient` HTTP round trip. Mirrors [`stub_parse_result_with_dependencies`]'s role
/// for [`crate::ParseResult`].
///
/// # Examples
///
/// ```
/// use deps_core::PublishTime;
/// use deps_core::deps_dev::{GossipCooldown, GossipRiskLevel};
/// use deps_core::test_util::stub_gossip_findings;
///
/// let findings = stub_gossip_findings(
///     "2.0.0",
///     Some(GossipCooldown::new(
///         PublishTime::from_unix_secs(i64::MAX / 2),
///         GossipRiskLevel::High,
///     )),
/// );
/// assert_eq!(findings.version, "2.0.0");
/// assert!(findings.cooldown.is_some());
/// ```
#[must_use]
pub fn stub_gossip_findings(
    version: impl Into<String>,
    cooldown: Option<crate::deps_dev::GossipCooldown>,
) -> crate::GossipFindings {
    crate::GossipFindings {
        version: version.into(),
        cooldown,
        low_usage: None,
    }
}

#[cfg(all(test, feature = "test-util"))]
mod tests {
    use super::capture_tracing_output;
    use super::{is_configured_token, rate_limit_skip_decision};
    use crate::RateLimitEvidence;

    #[test]
    fn is_configured_token_rejects_missing_and_empty() {
        assert!(!is_configured_token(None));
        assert!(!is_configured_token(Some(String::new())));
        assert!(is_configured_token(Some("ghp_x".to_string())));
    }

    #[test]
    fn rate_limit_skip_decision_skips_on_verified_rate_limit_without_token() {
        let result: Result<u32, crate::DepsError> = Err(crate::DepsError::RateLimited {
            message: "rate limited".to_string(),
            verified: RateLimitEvidence::Confirmed,
            source_status: Some(403),
        });
        assert_eq!(rate_limit_skip_decision(result, "unit-test", false), None);
    }

    /// #1295 regression: an *unverified* rate-limit classification (no `X-RateLimit-Remaining`
    /// evidence — could be an unrelated 403 cause) must not be silently skipped, even without
    /// a token configured.
    #[test]
    #[should_panic(expected = "unexpected error")]
    fn rate_limit_skip_decision_panics_on_unverified_rate_limit_without_token() {
        let result: Result<u32, crate::DepsError> = Err(crate::DepsError::RateLimited {
            message: "rate limited".to_string(),
            verified: RateLimitEvidence::Inferred,
            source_status: None,
        });
        let _ = rate_limit_skip_decision(result, "unit-test", false);
    }

    #[test]
    fn rate_limit_skip_decision_passes_through_ok() {
        let result: Result<u32, crate::DepsError> = Ok(7);
        assert_eq!(
            rate_limit_skip_decision(result, "unit-test", false),
            Some(7)
        );
    }

    #[test]
    #[should_panic(expected = "unexpected error")]
    fn rate_limit_skip_decision_panics_on_rate_limit_with_token_configured() {
        let result: Result<u32, crate::DepsError> = Err(crate::DepsError::RateLimited {
            message: "rate limited".to_string(),
            verified: RateLimitEvidence::Confirmed,
            source_status: Some(403),
        });
        let _ = rate_limit_skip_decision(result, "unit-test", true);
    }

    #[test]
    #[should_panic(expected = "unexpected error")]
    fn rate_limit_skip_decision_panics_on_non_rate_limit_error_even_without_token() {
        let result: Result<u32, crate::DepsError> =
            Err(crate::DepsError::InvalidUri("bad uri".to_string()));
        let _ = rate_limit_skip_decision(result, "unit-test", false);
    }

    /// Regression test for #1006: a sibling thread's untraced touch of a callsite,
    /// while a capture is in flight on this thread, must not poison that callsite
    /// against this thread's own capture.
    ///
    /// The channel below forces the spawned thread's untraced touch to complete
    /// before this thread's own (still in-flight) traced touch, rather than leaving
    /// that interleaving to OS scheduling luck as the original flake did. That
    /// synchronization is what makes this a *meaningful regression test against the
    /// old, pre-fix implementation* — it deterministically reproduces the historical
    /// race shape (a second thread winning a first-touch of the callsite while
    /// another thread's scoped subscriber was already active but not yet globally
    /// visible) instead of relying on chance. It is not required for this test to
    /// pass against the current, fixed implementation: the fix makes the property
    /// under test hold unconditionally regardless of timing, since
    /// `ThreadLocalLevelFilter` never lets a callsite's interest finalize to a
    /// terminal `never`/`always` no matter which thread touches it first.
    #[test]
    fn concurrent_untraced_touch_does_not_poison_active_capture() {
        fn emit_marker() {
            tracing::warn!("deps-core-1006-concurrent-touch-regression-marker");
        }

        let output = capture_tracing_output(|| {
            let (untraced_touched_tx, untraced_touched_rx) = std::sync::mpsc::channel();
            let handle = std::thread::spawn(move || {
                // Untraced sibling thread: no capture active here, mirroring the
                // original bug's untraced sibling test.
                emit_marker();
                untraced_touched_tx.send(()).unwrap();
            });
            // Wait for the sibling's touch to complete before this thread's own
            // touch, so the interleaving that mattered for #1006 is forced rather
            // than left to chance.
            untraced_touched_rx.recv().unwrap();
            emit_marker();
            handle.join().unwrap();
        });

        assert!(
            output.contains("deps-core-1006-concurrent-touch-regression-marker"),
            "capture was empty after a concurrent sibling-thread untraced touch — \
             tracing-core's per-callsite Interest cache regressed (#1006): {output:?}"
        );
    }

    /// Locks in two invariants `ThreadLocalLevelFilter`/`begin_capture` depend on for
    /// correctness, neither of which would fail loudly if it regressed:
    /// - `capture_tracing_output`'s default `INFO` filter must still reject a
    ///   `tracing::debug!` emission. If `ThreadLocalLevelFilter::enabled`'s level check, or
    ///   its implicit `Interest::sometimes()` from `callsite_enabled`, were ever changed to
    ///   something more permissive (e.g. `Interest::always()`), level filtering would
    ///   silently stop working instead of failing loudly.
    /// - a `tracing::warn!` emitted outside any capture window must not leak into the
    ///   *next* capture's result — proves the level gate (and the buffer clear on the next
    ///   `begin_capture`) actually prevent cross-call contamination rather than
    ///   accumulating output across calls.
    #[test]
    fn capture_filters_by_level_and_does_not_leak_across_calls() {
        // Below the default INFO filter: must never appear in a plain `capture_tracing_output`.
        let output = capture_tracing_output(|| {
            tracing::debug!("deps-core-1006-level-filter-marker-should-not-appear");
        });
        assert!(
            !output.contains("deps-core-1006-level-filter-marker-should-not-appear"),
            "capture_tracing_output's default INFO filter captured a DEBUG emission — \
             level filtering regressed: {output:?}"
        );

        // Emitted with no capture active on this thread: must not surface in a later capture.
        tracing::warn!("deps-core-1006-stale-marker-should-not-leak");
        let output = capture_tracing_output(|| {
            tracing::warn!("deps-core-1006-fresh-marker");
        });
        assert!(
            !output.contains("deps-core-1006-stale-marker-should-not-leak"),
            "a warn! emitted outside any capture window leaked into the next capture's \
             result — cross-call isolation regressed: {output:?}"
        );
        assert!(
            output.contains("deps-core-1006-fresh-marker"),
            "the current capture's own emission is missing: {output:?}"
        );
    }
}