deps-core 1.1.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
// `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).

/// 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")
}

/// 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);
/// ```
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
    }
}

/// 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
}

/// 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
    }
}

/// 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"),
    })
}

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

    /// 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:?}"
        );
    }
}