Skip to main content

uv_test/
lib.rs

1// The `unreachable_pub` is to silence false positives in RustRover.
2#![allow(dead_code, unreachable_pub)]
3
4pub mod find_links;
5mod http_server;
6pub mod packse;
7mod vendor;
8
9use std::borrow::BorrowMut;
10use std::ffi::OsString;
11use std::io::Write as _;
12use std::iter::Iterator;
13use std::path::{Path, PathBuf};
14use std::process::{Command, Output, Stdio};
15use std::str::FromStr;
16use std::{env, io};
17use uv_python::downloads::ManagedPythonDownloadList;
18
19use assert_cmd::assert::{Assert, OutputAssertExt};
20use assert_fs::assert::PathAssert;
21use assert_fs::fixture::{
22    ChildPath, FileWriteStr, PathChild, PathCopy, PathCreateDir, SymlinkToFile,
23};
24use base64::{Engine, prelude::BASE64_STANDARD as base64};
25use futures::StreamExt;
26use indoc::{formatdoc, indoc};
27use itertools::Itertools;
28use predicates::prelude::predicate;
29use regex::Regex;
30use tokio::io::AsyncWriteExt;
31
32use uv_cache::{Cache, CacheBucket};
33use uv_fs::Simplified;
34use uv_python::managed::ManagedPythonInstallations;
35use uv_python::{
36    EnvironmentPreference, PythonInstallation, PythonPreference, PythonRequest, PythonVersion,
37};
38use uv_static::EnvVars;
39
40// Shared test timestamp for deterministic package availability and relative times.
41static TEST_TIMESTAMP: &str = "2024-03-25T00:00:00Z";
42
43pub const DEFAULT_PYTHON_VERSION: &str = "3.12";
44
45// The expected latest patch version for each Python minor version.
46const LATEST_PYTHON_3_15: &str = "3.15.0b2";
47const LATEST_PYTHON_3_14: &str = "3.14.5";
48const LATEST_PYTHON_3_13: &str = "3.13.13";
49pub const LATEST_PYTHON_3_12: &str = "3.12.13";
50const LATEST_PYTHON_3_11: &str = "3.11.15";
51const LATEST_PYTHON_3_10: &str = "3.10.20";
52
53/// Create a new [`TestContext`] with the given Python version.
54///
55/// Creates a virtual environment for the test.
56///
57/// This macro captures the uv binary path at compile time using `env!("CARGO_BIN_EXE_uv")`,
58/// which is only available in the test crate.
59#[macro_export]
60macro_rules! test_context {
61    ($python_version:expr) => {
62        $crate::TestContext::new_with_bin(
63            $python_version,
64            std::path::PathBuf::from(env!("CARGO_BIN_EXE_uv")),
65        )
66    };
67}
68
69/// Create a new [`TestContext`] with zero or more Python versions.
70///
71/// Unlike [`test_context!`], this does not create a virtual environment.
72///
73/// This macro captures the uv binary path at compile time using `env!("CARGO_BIN_EXE_uv")`,
74/// which is only available in the test crate.
75#[macro_export]
76macro_rules! test_context_with_versions {
77    ($python_versions:expr) => {
78        $crate::TestContext::new_with_versions_and_bin(
79            $python_versions,
80            std::path::PathBuf::from(env!("CARGO_BIN_EXE_uv")),
81        )
82    };
83}
84
85/// Return the path to the uv binary.
86///
87/// This macro captures the uv binary path at compile time using `env!("CARGO_BIN_EXE_uv")`,
88/// which is only available in the test crate.
89#[macro_export]
90macro_rules! get_bin {
91    () => {
92        std::path::PathBuf::from(env!("CARGO_BIN_EXE_uv"))
93    };
94}
95
96#[doc(hidden)] // Macro and test context only, don't use directly.
97pub const INSTA_FILTERS: &[(&str, &str)] = &[
98    (r"--cache-dir [^\s]+", "--cache-dir [CACHE_DIR]"),
99    // Operation times
100    (r"(\s|\()(\d+m )?(\d+\.)?\d+(ms|s)", "$1[TIME]"),
101    // File sizes
102    (r"(\s|\()(\d+\.)?\d+([KM]i)?B", "$1[SIZE]"),
103    // Timestamps
104    (r"tv_sec: \d+", "tv_sec: [TIME]"),
105    (r"tv_nsec: \d+", "tv_nsec: [TIME]"),
106    // Rewrite Windows output to Unix output
107    (r"\\([\w\d]|\.)", "/$1"),
108    (r"uv\.exe", "uv"),
109    // uv version display
110    (
111        r"uv(-.*)? \d+\.\d+\.\d+(-(alpha|beta|rc)\.\d+)?(\+\d+)?( \([^)]*\))?",
112        r"uv [VERSION] ([COMMIT] DATE)",
113    ),
114    // Trim end-of-line whitespaces, to allow removing them on save.
115    (r"([^\s])[ \t]+(\r?\n)", "$1$2"),
116    // Filter SSL certificate loading debug messages (environment-dependent)
117    (r"DEBUG Loaded \d+ certificate\(s\) from [^\n]+\n", ""),
118];
119
120/// Create a context for tests which simplifies shared behavior across tests.
121///
122/// * Set the current directory to a temporary directory (`temp_dir`).
123/// * Set the cache dir to a different temporary directory (`cache_dir`).
124/// * Set a shared test timestamp so snapshots don't change after a new release.
125/// * Set the venv to a fresh `.venv` in `temp_dir`
126pub struct TestContext {
127    pub root: ChildPath,
128    pub temp_dir: ChildPath,
129    pub cache_dir: ChildPath,
130    python_dir: ChildPath,
131    pub home_dir: ChildPath,
132    pub user_config_dir: ChildPath,
133    pub bin_dir: ChildPath,
134    pub venv: ChildPath,
135    pub workspace_root: PathBuf,
136
137    /// The Python version used for the virtual environment, if any.
138    python_version: Option<PythonVersion>,
139
140    /// All the Python versions available during this test context.
141    pub python_versions: Vec<(PythonVersion, PathBuf)>,
142
143    /// Path to the uv binary.
144    uv_bin: PathBuf,
145
146    /// Standard filters for this test context.
147    filters: Vec<(String, String)>,
148
149    /// Extra environment variables to apply to all commands.
150    extra_env: Vec<(OsString, OsString)>,
151
152    #[allow(dead_code)]
153    _root: tempfile::TempDir,
154
155    /// Extra temporary directories whose lifetimes are tied to this context (e.g., directories
156    /// on alternate filesystems created by [`TestContext::with_cache_on_cow_fs`]).
157    #[allow(dead_code)]
158    _extra_tempdirs: Vec<tempfile::TempDir>,
159}
160
161impl TestContext {
162    /// Create a new test context with a virtual environment and explicit uv binary path.
163    ///
164    /// This is called by the `test_context!` macro.
165    pub fn new_with_bin(python_version: &str, uv_bin: PathBuf) -> Self {
166        let new = Self::new_with_versions_and_bin(&[python_version], uv_bin);
167        new.create_venv();
168        new
169    }
170
171    /// Set the "exclude newer" timestamp for all commands in this context.
172    #[must_use]
173    pub fn with_exclude_newer(mut self, exclude_newer: &str) -> Self {
174        self.extra_env
175            .push((EnvVars::UV_EXCLUDE_NEWER.into(), exclude_newer.into()));
176        self
177    }
178
179    /// Set the "http timeout" for all commands in this context.
180    #[must_use]
181    pub fn with_http_timeout(mut self, http_timeout: &str) -> Self {
182        self.extra_env
183            .push((EnvVars::UV_HTTP_TIMEOUT.into(), http_timeout.into()));
184        self
185    }
186
187    /// Set the "concurrent installs" for all commands in this context.
188    #[must_use]
189    pub fn with_concurrent_installs(mut self, concurrent_installs: &str) -> Self {
190        self.extra_env.push((
191            EnvVars::UV_CONCURRENT_INSTALLS.into(),
192            concurrent_installs.into(),
193        ));
194        self
195    }
196
197    /// Add extra standard filtering for messages like "Resolved 10 packages" which
198    /// can differ between platforms.
199    ///
200    /// In some cases, these counts are helpful for the snapshot and should not be filtered.
201    #[must_use]
202    pub fn with_filtered_counts(mut self) -> Self {
203        for verb in &[
204            "Resolved",
205            "Prepared",
206            "Installed",
207            "Uninstalled",
208            "Checked",
209        ] {
210            self.filters.push((
211                format!("{verb} \\d+ packages?"),
212                format!("{verb} [N] packages"),
213            ));
214        }
215        self.filters.push((
216            "Removed \\d+ files?".to_string(),
217            "Removed [N] files".to_string(),
218        ));
219        self
220    }
221
222    /// Add extra filtering for cache size output
223    #[must_use]
224    pub fn with_filtered_cache_size(mut self) -> Self {
225        // Filter raw byte counts (numbers on their own line)
226        self.filters
227            .push((r"(?m)^\d+\n".to_string(), "[SIZE]\n".to_string()));
228        // Filter human-readable sizes (e.g., "384.2 KiB")
229        self.filters.push((
230            r"(?m)^\d+(\.\d+)? [KMGT]i?B\n".to_string(),
231            "[SIZE]\n".to_string(),
232        ));
233        self
234    }
235
236    /// Add extra standard filtering for Windows-compatible missing file errors.
237    #[must_use]
238    pub fn with_filtered_missing_file_error(mut self) -> Self {
239        // The exact message string depends on the system language, so we remove it.
240        // We want to only remove the phrase after `Caused by:`
241        self.filters.push((
242            r"[^:\n]* \(os error 2\)".to_string(),
243            " [OS ERROR 2]".to_string(),
244        ));
245        // Replace the Windows "The system cannot find the path specified. (os error 3)"
246        // with the Unix "No such file or directory (os error 2)"
247        // and mask the language-dependent message.
248        self.filters.push((
249            r"[^:\n]* \(os error 3\)".to_string(),
250            " [OS ERROR 2]".to_string(),
251        ));
252        self
253    }
254
255    /// Add extra standard filtering for executable suffixes on the current platform e.g.
256    /// drops `.exe` on Windows.
257    #[must_use]
258    pub fn with_filtered_exe_suffix(mut self) -> Self {
259        self.filters
260            .push((regex::escape(env::consts::EXE_SUFFIX), String::new()));
261        self
262    }
263
264    /// Add extra standard filtering for Python interpreter sources
265    #[must_use]
266    pub fn with_filtered_python_sources(mut self) -> Self {
267        self.filters.push((
268            "virtual environments, managed installations, or search path".to_string(),
269            "[PYTHON SOURCES]".to_string(),
270        ));
271        self.filters.push((
272            "virtual environments, managed installations, search path, or registry".to_string(),
273            "[PYTHON SOURCES]".to_string(),
274        ));
275        self.filters.push((
276            "virtual environments, search path, or registry".to_string(),
277            "[PYTHON SOURCES]".to_string(),
278        ));
279        self.filters.push((
280            "virtual environments, registry, or search path".to_string(),
281            "[PYTHON SOURCES]".to_string(),
282        ));
283        self.filters.push((
284            "virtual environments or search path".to_string(),
285            "[PYTHON SOURCES]".to_string(),
286        ));
287        self.filters.push((
288            "managed installations or search path".to_string(),
289            "[PYTHON SOURCES]".to_string(),
290        ));
291        self.filters.push((
292            "managed installations, search path, or registry".to_string(),
293            "[PYTHON SOURCES]".to_string(),
294        ));
295        self.filters.push((
296            "search path or registry".to_string(),
297            "[PYTHON SOURCES]".to_string(),
298        ));
299        self.filters.push((
300            "registry or search path".to_string(),
301            "[PYTHON SOURCES]".to_string(),
302        ));
303        self.filters
304            .push(("search path".to_string(), "[PYTHON SOURCES]".to_string()));
305        self
306    }
307
308    /// Add extra standard filtering for Python executable names, e.g., stripping version number
309    /// and `.exe` suffixes.
310    #[must_use]
311    pub fn with_filtered_python_names(mut self) -> Self {
312        for name in ["python", "pypy"] {
313            // Note we strip version numbers from the executable names because, e.g., on Windows
314            // `python.exe` is the equivalent to a Unix `python3.12`.`
315            let suffix = if cfg!(windows) {
316                // On Windows, we'll require a `.exe` suffix for disambiguation
317                // We'll also strip version numbers if present, which is not common for `python.exe`
318                // but can occur for, e.g., `pypy3.12.exe`
319                let exe_suffix = regex::escape(env::consts::EXE_SUFFIX);
320                format!(r"(\d\.\d+|\d)?{exe_suffix}")
321            } else {
322                // On Unix, we'll strip version numbers
323                if name == "python" {
324                    // We can't require them in this case since `/python` is common
325                    r"(\d\.\d+|\d)?(t|d|td)?".to_string()
326                } else {
327                    // However, for other names we'll require them to avoid over-matching
328                    r"(\d\.\d+|\d)(t|d|td)?".to_string()
329                }
330            };
331
332            self.filters.push((
333                // We use a leading path separator to help disambiguate cases where the name is not
334                // used in a path.
335                format!(r"[\\/]{name}{suffix}"),
336                format!("/[{}]", name.to_uppercase()),
337            ));
338        }
339
340        self
341    }
342
343    /// Add extra standard filtering for venv executable directories on the current platform e.g.
344    /// `Scripts` on Windows and `bin` on Unix.
345    #[must_use]
346    pub fn with_filtered_virtualenv_bin(mut self) -> Self {
347        self.filters.push((
348            format!(
349                r"[\\/]{}[\\/]",
350                venv_bin_path(PathBuf::new()).to_string_lossy()
351            ),
352            "/[BIN]/".to_string(),
353        ));
354        self.filters.push((
355            format!(r"[\\/]{}", venv_bin_path(PathBuf::new()).to_string_lossy()),
356            "/[BIN]".to_string(),
357        ));
358        self
359    }
360
361    /// Add extra standard filtering for Python installation `bin/` directories, which are not
362    /// present on Windows but are on Unix. See [`TestContext::with_filtered_virtualenv_bin`] for
363    /// the virtual environment equivalent.
364    #[must_use]
365    pub fn with_filtered_python_install_bin(mut self) -> Self {
366        // We don't want to eagerly match paths that aren't actually Python executables, so we
367        // do our best to detect that case
368        let suffix = if cfg!(windows) {
369            let exe_suffix = regex::escape(env::consts::EXE_SUFFIX);
370            // On Windows, we usually don't have a version attached but we might, e.g., for pypy3.12
371            format!(r"(\d\.\d+|\d)?{exe_suffix}")
372        } else {
373            // On Unix, we'll require a version to be attached to avoid over-matching
374            r"\d\.\d+|\d".to_string()
375        };
376
377        if cfg!(unix) {
378            self.filters.push((
379                format!(r"[\\/]bin/python({suffix})"),
380                "/[INSTALL-BIN]/python$1".to_string(),
381            ));
382            self.filters.push((
383                format!(r"[\\/]bin/pypy({suffix})"),
384                "/[INSTALL-BIN]/pypy$1".to_string(),
385            ));
386        } else {
387            self.filters.push((
388                format!(r"[\\/]python({suffix})"),
389                "/[INSTALL-BIN]/python$1".to_string(),
390            ));
391            self.filters.push((
392                format!(r"[\\/]pypy({suffix})"),
393                "/[INSTALL-BIN]/pypy$1".to_string(),
394            ));
395        }
396        self
397    }
398
399    /// Filtering for various keys in a `pyvenv.cfg` file that will vary
400    /// depending on the specific machine used:
401    /// - `home = foo/bar/baz/python3.X.X/bin`
402    /// - `uv = X.Y.Z`
403    /// - `extends-environment = <path/to/parent/venv>`
404    #[must_use]
405    pub fn with_pyvenv_cfg_filters(mut self) -> Self {
406        let added_filters = [
407            (r"home = .+".to_string(), "home = [PYTHON_HOME]".to_string()),
408            (
409                r"uv = \d+\.\d+\.\d+(-(alpha|beta|rc)\.\d+)?(\+\d+)?".to_string(),
410                "uv = [UV_VERSION]".to_string(),
411            ),
412            (
413                r"extends-environment = .+".to_string(),
414                "extends-environment = [PARENT_VENV]".to_string(),
415            ),
416        ];
417        for filter in added_filters {
418            self.filters.insert(0, filter);
419        }
420        self
421    }
422
423    /// Add extra filtering for ` -> <PATH>` symlink display for Python versions in the test
424    /// context, e.g., for use in `uv python list`.
425    #[must_use]
426    pub fn with_filtered_python_symlinks(mut self) -> Self {
427        for (version, executable) in &self.python_versions {
428            if fs_err::symlink_metadata(executable).unwrap().is_symlink() {
429                self.filters.extend(
430                    Self::path_patterns(executable.read_link().unwrap())
431                        .into_iter()
432                        .map(|pattern| (format! {" -> {pattern}"}, String::new())),
433                );
434            }
435            // Drop links that are byproducts of the test context too
436            self.filters.push((
437                regex::escape(&format!(" -> [PYTHON-{version}]")),
438                String::new(),
439            ));
440        }
441        self
442    }
443
444    /// Add extra standard filtering for a given path.
445    #[must_use]
446    pub fn with_filtered_path(mut self, path: &Path, name: &str) -> Self {
447        // Note this is sloppy, ideally we wouldn't push to the front of the `Vec` but we need
448        // this to come in front of other filters or we can transform the path (e.g., with `[TMP]`)
449        // before we reach this filter.
450        for pattern in Self::path_patterns(path)
451            .into_iter()
452            .map(|pattern| (pattern, format!("[{name}]/")))
453        {
454            self.filters.insert(0, pattern);
455        }
456        self
457    }
458
459    /// Adds a filter that specifically ignores the link mode warning.
460    ///
461    /// This occurs in some cases and can be used on an ad hoc basis to squash
462    /// the warning in the snapshots. This is useful because the warning does
463    /// not consistently appear. It is dependent on the environment. (For
464    /// example, sometimes it's dependent on whether `/tmp` and `~/.local` live
465    /// on the same file system.)
466    #[inline]
467    #[must_use]
468    pub fn with_filtered_link_mode_warning(mut self) -> Self {
469        let pattern = "warning: Failed to hardlink files; .*\n.*\n.*\n";
470        self.filters.push((pattern.to_string(), String::new()));
471        self
472    }
473
474    /// Adds a filter for platform-specific errors when a file is not executable.
475    #[inline]
476    #[must_use]
477    pub fn with_filtered_not_executable(mut self) -> Self {
478        let pattern = if cfg!(unix) {
479            r"Permission denied \(os error 13\)"
480        } else {
481            r"\%1 is not a valid Win32 application. \(os error 193\)"
482        };
483        self.filters
484            .push((pattern.to_string(), "[PERMISSION DENIED]".to_string()));
485        self
486    }
487
488    /// Adds a filter that ignores platform information in a Python installation key.
489    #[must_use]
490    pub fn with_filtered_python_keys(mut self) -> Self {
491        // Filter platform keys
492        let platform_re = r"(?x)
493  (                         # We capture the group before the platform
494    (?:cpython|pypy|graalpy)# Python implementation
495    -
496    \d+\.\d+                # Major and minor version
497    (?:                     # The patch version is handled separately
498      \.
499      (?:
500        \[X\]               # A previously filtered patch version [X]
501        |                   # OR
502        \[LATEST\]          # A previously filtered latest patch version [LATEST]
503        |                   # OR
504        \d+                 # An actual patch version
505      )
506    )?                      # (we allow the patch version to be missing entirely, e.g., in a request)
507    (?:(?:a|b|rc)[0-9]+)?   # Pre-release version component, e.g., `a6` or `rc2`
508    (?:[td])?               # A short variant, such as `t` (for freethreaded) or `d` (for debug)
509    (?:(\+[a-z]+)+)?        # A long variant, such as `+freethreaded` or `+freethreaded+debug`
510  )
511  -
512  [a-z0-9]+                 # Operating system (e.g., 'macos')
513  -
514  [a-z0-9_]+                # Architecture (e.g., 'aarch64')
515  -
516  [a-z]+                    # Libc (e.g., 'none')
517";
518        self.filters
519            .push((platform_re.to_string(), "$1-[PLATFORM]".to_string()));
520        self
521    }
522
523    /// Adds a filter that replaces the latest Python patch versions with `[LATEST]` placeholder.
524    #[must_use]
525    pub fn with_filtered_latest_python_versions(mut self) -> Self {
526        // Filter the latest patch versions with [LATEST] placeholder
527        // The order matters - we want to match the full version first
528        for (minor, patch) in [
529            ("3.15", LATEST_PYTHON_3_15.strip_prefix("3.15.").unwrap()),
530            ("3.14", LATEST_PYTHON_3_14.strip_prefix("3.14.").unwrap()),
531            ("3.13", LATEST_PYTHON_3_13.strip_prefix("3.13.").unwrap()),
532            ("3.12", LATEST_PYTHON_3_12.strip_prefix("3.12.").unwrap()),
533            ("3.11", LATEST_PYTHON_3_11.strip_prefix("3.11.").unwrap()),
534            ("3.10", LATEST_PYTHON_3_10.strip_prefix("3.10.").unwrap()),
535        ] {
536            // Match the full version in various contexts (cpython-X.Y.Z, Python X.Y.Z, etc.)
537            let pattern = format!(r"(\b){minor}\.{patch}(\b)");
538            let replacement = format!("${{1}}{minor}.[LATEST]${{2}}");
539            self.filters.push((pattern, replacement));
540        }
541        self
542    }
543
544    /// Add a filter that ignores temporary directory in path.
545    #[must_use]
546    #[cfg(windows)]
547    pub fn with_filtered_windows_temp_dir(mut self) -> Self {
548        let pattern = regex::escape(
549            &self
550                .temp_dir
551                .simplified_display()
552                .to_string()
553                .replace('/', "\\"),
554        );
555        self.filters.push((pattern, "[TEMP_DIR]".to_string()));
556        self
557    }
558
559    /// Add a filter for (bytecode) compilation file counts
560    #[must_use]
561    pub fn with_filtered_compiled_file_count(mut self) -> Self {
562        self.filters.push((
563            r"compiled \d+ files".to_string(),
564            "compiled [COUNT] files".to_string(),
565        ));
566        self
567    }
568
569    /// Add a (not context aware) filter for the current uv version `v<major>.<minor>.<patch>`
570    #[must_use]
571    pub fn with_filtered_current_version(mut self) -> Self {
572        self.filters.push((
573            regex::escape(&format!("v{}", env!("CARGO_PKG_VERSION"))),
574            "v[CURRENT_VERSION]".to_string(),
575        ));
576        self
577    }
578
579    /// Adds filters for non-deterministic `CycloneDX` data
580    #[must_use]
581    pub fn with_cyclonedx_filters(mut self) -> Self {
582        self.filters.push((
583            r"urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}".to_string(),
584            "[SERIAL_NUMBER]".to_string(),
585        ));
586        self.filters.push((
587            r#""timestamp": "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]+Z""#
588                .to_string(),
589            r#""timestamp": "[TIMESTAMP]""#.to_string(),
590        ));
591        self.filters.push((
592            r#""name": "uv",\s*"version": "\d+\.\d+\.\d+(-(alpha|beta|rc)\.\d+)?(\+\d+)?""#
593                .to_string(),
594            r#""name": "uv",
595        "version": "[VERSION]""#
596                .to_string(),
597        ));
598        self
599    }
600
601    /// Add a filter that collapses duplicate whitespace.
602    #[must_use]
603    pub fn with_collapsed_whitespace(mut self) -> Self {
604        self.filters.push((r"[ \t]+".to_string(), " ".to_string()));
605        self
606    }
607
608    /// Use a shared global cache for Python downloads.
609    #[must_use]
610    pub fn with_python_download_cache(mut self) -> Self {
611        self.extra_env.push((
612            EnvVars::UV_PYTHON_CACHE_DIR.into(),
613            // Respect `UV_PYTHON_CACHE_DIR` if set, or use the default cache directory
614            env::var_os(EnvVars::UV_PYTHON_CACHE_DIR).unwrap_or_else(|| {
615                uv_cache::Cache::from_settings(false, None)
616                    .unwrap()
617                    .bucket(CacheBucket::Python)
618                    .into()
619            }),
620        ));
621        self
622    }
623
624    #[must_use]
625    pub fn with_empty_python_install_mirror(mut self) -> Self {
626        self.extra_env.push((
627            EnvVars::UV_PYTHON_INSTALL_MIRROR.into(),
628            String::new().into(),
629        ));
630        self
631    }
632
633    /// Add extra directories and configuration for managed Python installations.
634    #[must_use]
635    pub fn with_managed_python_dirs(mut self) -> Self {
636        let managed = self.temp_dir.join("managed");
637
638        self.extra_env.push((
639            EnvVars::UV_PYTHON_BIN_DIR.into(),
640            self.bin_dir.as_os_str().to_owned(),
641        ));
642        self.extra_env
643            .push((EnvVars::UV_PYTHON_INSTALL_DIR.into(), managed.into()));
644        self.extra_env
645            .push((EnvVars::UV_PYTHON_DOWNLOADS.into(), "automatic".into()));
646
647        self
648    }
649
650    #[must_use]
651    pub fn with_versions_as_managed(mut self, versions: &[&str]) -> Self {
652        self.extra_env.push((
653            EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED.into(),
654            versions.iter().join(" ").into(),
655        ));
656
657        self
658    }
659
660    /// Add a custom filter to the `TestContext`.
661    #[must_use]
662    pub fn with_filter(mut self, filter: (impl Into<String>, impl Into<String>)) -> Self {
663        self.filters.push((filter.0.into(), filter.1.into()));
664        self
665    }
666
667    // Unsets the git credential helper using temp home gitconfig
668    #[must_use]
669    pub fn with_unset_git_credential_helper(self) -> Self {
670        let git_config = self.home_dir.child(".gitconfig");
671        git_config
672            .write_str(indoc! {r"
673                [credential]
674                    helper =
675            "})
676            .expect("Failed to unset git credential helper");
677
678        self
679    }
680
681    /// Clear filters on `TestContext`.
682    #[must_use]
683    #[cfg(windows)]
684    pub fn clear_filters(mut self) -> Self {
685        self.filters.clear();
686        self
687    }
688
689    /// Use a cache directory on the filesystem specified by
690    /// [`EnvVars::UV_INTERNAL__TEST_COW_FS`].
691    ///
692    /// Returns `Ok(None)` if the environment variable is not set.
693    pub fn with_cache_on_cow_fs(self) -> anyhow::Result<Option<Self>> {
694        let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_COW_FS).ok() else {
695            return Ok(None);
696        };
697        self.with_cache_on_fs(&dir, "COW_FS").map(Some)
698    }
699
700    /// Use a cache directory on the filesystem specified by
701    /// [`EnvVars::UV_INTERNAL__TEST_ALT_FS`].
702    ///
703    /// Returns `Ok(None)` if the environment variable is not set.
704    pub fn with_cache_on_alt_fs(self) -> anyhow::Result<Option<Self>> {
705        let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_ALT_FS).ok() else {
706            return Ok(None);
707        };
708        self.with_cache_on_fs(&dir, "ALT_FS").map(Some)
709    }
710
711    /// Use a cache directory on the filesystem specified by
712    /// [`EnvVars::UV_INTERNAL__TEST_LOWLINKS_FS`].
713    ///
714    /// Returns `Ok(None)` if the environment variable is not set.
715    pub fn with_cache_on_lowlinks_fs(self) -> anyhow::Result<Option<Self>> {
716        let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_LOWLINKS_FS).ok() else {
717            return Ok(None);
718        };
719        self.with_cache_on_fs(&dir, "LOWLINKS_FS").map(Some)
720    }
721
722    /// Use a cache directory on the filesystem specified by
723    /// [`EnvVars::UV_INTERNAL__TEST_NOCOW_FS`].
724    ///
725    /// Returns `Ok(None)` if the environment variable is not set.
726    pub fn with_cache_on_nocow_fs(self) -> anyhow::Result<Option<Self>> {
727        let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_NOCOW_FS).ok() else {
728            return Ok(None);
729        };
730        self.with_cache_on_fs(&dir, "NOCOW_FS").map(Some)
731    }
732
733    /// Use a working directory on the filesystem specified by
734    /// [`EnvVars::UV_INTERNAL__TEST_COW_FS`].
735    ///
736    /// Returns `Ok(None)` if the environment variable is not set.
737    ///
738    /// Note a virtual environment is not created automatically.
739    pub fn with_working_dir_on_cow_fs(self) -> anyhow::Result<Option<Self>> {
740        let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_COW_FS).ok() else {
741            return Ok(None);
742        };
743        self.with_working_dir_on_fs(&dir, "COW_FS").map(Some)
744    }
745
746    /// Use a working directory on the filesystem specified by
747    /// [`EnvVars::UV_INTERNAL__TEST_NOCOW_FS`].
748    ///
749    /// Returns `Ok(None)` if the environment variable is not set.
750    ///
751    /// Note a virtual environment is not created automatically.
752    pub fn with_working_dir_on_nocow_fs(self) -> anyhow::Result<Option<Self>> {
753        let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_NOCOW_FS).ok() else {
754            return Ok(None);
755        };
756        self.with_working_dir_on_fs(&dir, "NOCOW_FS").map(Some)
757    }
758
759    fn with_cache_on_fs(mut self, dir: &str, name: &str) -> anyhow::Result<Self> {
760        fs_err::create_dir_all(dir)?;
761        let tmp = tempfile::TempDir::new_in(dir)?;
762        self.cache_dir = ChildPath::new(tmp.path()).child("cache");
763        fs_err::create_dir_all(&self.cache_dir)?;
764        let replacement = format!("[{name}]/[CACHE_DIR]/");
765        self.filters.extend(
766            Self::path_patterns(&self.cache_dir)
767                .into_iter()
768                .map(|pattern| (pattern, replacement.clone())),
769        );
770        self._extra_tempdirs.push(tmp);
771        Ok(self)
772    }
773
774    fn with_working_dir_on_fs(mut self, dir: &str, name: &str) -> anyhow::Result<Self> {
775        fs_err::create_dir_all(dir)?;
776        let tmp = tempfile::TempDir::new_in(dir)?;
777        self.temp_dir = ChildPath::new(tmp.path()).child("temp");
778        fs_err::create_dir_all(&self.temp_dir)?;
779        // Place the venv inside temp_dir (matching the default TestContext layout)
780        // so that `context.venv()` creates it at the same path that `VIRTUAL_ENV` points to.
781        let canonical_temp_dir = self.temp_dir.canonicalize()?;
782        self.venv = ChildPath::new(canonical_temp_dir.join(".venv"));
783        let temp_replacement = format!("[{name}]/[TEMP_DIR]/");
784        self.filters.extend(
785            Self::path_patterns(&self.temp_dir)
786                .into_iter()
787                .map(|pattern| (pattern, temp_replacement.clone())),
788        );
789        let venv_replacement = format!("[{name}]/[VENV]/");
790        self.filters.extend(
791            Self::path_patterns(&self.venv)
792                .into_iter()
793                .map(|pattern| (pattern, venv_replacement.clone())),
794        );
795        self._extra_tempdirs.push(tmp);
796        Ok(self)
797    }
798
799    /// Default to the canonicalized path to the temp directory. We need to do this because on
800    /// macOS (and Windows on GitHub Actions) the standard temp dir is a symlink. (On macOS, the
801    /// temporary directory is, like `/var/...`, which resolves to `/private/var/...`.)
802    ///
803    /// It turns out that, at least on macOS, if we pass a symlink as `current_dir`, it gets
804    /// _immediately_ resolved (such that if you call `current_dir` in the running `Command`, it
805    /// returns resolved symlink). This breaks some snapshot tests, since we _don't_ want to
806    /// resolve symlinks for user-provided paths.
807    pub fn test_bucket_dir() -> PathBuf {
808        std::env::temp_dir()
809            .simple_canonicalize()
810            .expect("failed to canonicalize temp dir")
811            .join("uv")
812            .join("tests")
813    }
814
815    /// Create a new test context with multiple Python versions and explicit uv binary path.
816    ///
817    /// Does not create a virtual environment by default, but the first Python version
818    /// can be used to create a virtual environment with [`TestContext::create_venv`].
819    ///
820    /// This is called by the `test_context_with_versions!` macro.
821    pub fn new_with_versions_and_bin(python_versions: &[&str], uv_bin: PathBuf) -> Self {
822        let bucket = Self::test_bucket_dir();
823        fs_err::create_dir_all(&bucket).expect("Failed to create test bucket");
824
825        let root = tempfile::TempDir::new_in(bucket).expect("Failed to create test root directory");
826
827        // Create a `.git` directory to isolate tests that search for git boundaries from the state
828        // of the file system
829        fs_err::create_dir_all(root.path().join(".git"))
830            .expect("Failed to create `.git` placeholder in test root directory");
831
832        let temp_dir = ChildPath::new(root.path()).child("temp");
833        fs_err::create_dir_all(&temp_dir).expect("Failed to create test working directory");
834
835        let cache_dir = ChildPath::new(root.path()).child("cache");
836        fs_err::create_dir_all(&cache_dir).expect("Failed to create test cache directory");
837
838        let python_dir = ChildPath::new(root.path()).child("python");
839        fs_err::create_dir_all(&python_dir).expect("Failed to create test Python directory");
840
841        let bin_dir = ChildPath::new(root.path()).child("bin");
842        fs_err::create_dir_all(&bin_dir).expect("Failed to create test bin directory");
843
844        // When the `git` feature is disabled, enforce that the test suite does not use `git`
845        if cfg!(not(feature = "git")) {
846            Self::disallow_git_cli(&bin_dir).expect("Failed to setup disallowed `git` command");
847        }
848
849        let home_dir = ChildPath::new(root.path()).child("home");
850        fs_err::create_dir_all(&home_dir).expect("Failed to create test home directory");
851
852        let user_config_dir = if cfg!(windows) {
853            ChildPath::new(home_dir.path())
854        } else {
855            ChildPath::new(home_dir.path()).child(".config")
856        };
857
858        // Canonicalize the temp dir for consistent snapshot behavior
859        let canonical_temp_dir = temp_dir.canonicalize().unwrap();
860        let venv = ChildPath::new(canonical_temp_dir.join(".venv"));
861
862        let python_version = python_versions
863            .first()
864            .map(|version| PythonVersion::from_str(version).unwrap());
865
866        let site_packages = python_version
867            .as_ref()
868            .map(|version| site_packages_path(&venv, &format!("python{version}")));
869
870        // The workspace root directory is not available without walking up the tree
871        // https://github.com/rust-lang/cargo/issues/3946
872        let workspace_root = Path::new(&env::var(EnvVars::CARGO_MANIFEST_DIR).unwrap())
873            .parent()
874            .expect("CARGO_MANIFEST_DIR should be nested in workspace")
875            .parent()
876            .expect("CARGO_MANIFEST_DIR should be doubly nested in workspace")
877            .to_path_buf();
878
879        let download_list = ManagedPythonDownloadList::new_only_embedded().unwrap();
880
881        let python_versions: Vec<_> = python_versions
882            .iter()
883            .map(|version| PythonVersion::from_str(version).unwrap())
884            .zip(
885                python_installations_for_versions(&temp_dir, python_versions, &download_list)
886                    .expect("Failed to find test Python versions"),
887            )
888            .collect();
889
890        // Construct directories for each Python executable on Unix where the executable names
891        // need to be normalized
892        if cfg!(unix) {
893            for (version, executable) in &python_versions {
894                let parent = python_dir.child(version.to_string());
895                parent.create_dir_all().unwrap();
896                parent.child("python3").symlink_to_file(executable).unwrap();
897            }
898        }
899
900        let mut filters = Vec::new();
901
902        filters.extend(
903            Self::path_patterns(&uv_bin)
904                .into_iter()
905                .map(|pattern| (pattern, "[UV]".to_string())),
906        );
907
908        // Exclude `link-mode` on Windows since we set it in the remote test suite
909        if cfg!(windows) {
910            filters.push((" --link-mode <LINK_MODE>".to_string(), String::new()));
911            filters.push((r#"link-mode = "copy"\n"#.to_string(), String::new()));
912            // Unix uses "exit status", Windows uses "exit code"
913            filters.push((r"exit code: ".to_string(), "exit status: ".to_string()));
914        }
915
916        for (version, executable) in &python_versions {
917            // Add filtering for the interpreter path
918            filters.extend(
919                Self::path_patterns(executable)
920                    .into_iter()
921                    .map(|pattern| (pattern, format!("[PYTHON-{version}]"))),
922            );
923
924            // And for the symlink we created in the test the Python path
925            filters.extend(
926                Self::path_patterns(python_dir.join(version.to_string()))
927                    .into_iter()
928                    .map(|pattern| {
929                        (
930                            format!("{pattern}[a-zA-Z0-9]*"),
931                            format!("[PYTHON-{version}]"),
932                        )
933                    }),
934            );
935
936            // Add Python patch version filtering unless explicitly requested to ensure
937            // snapshots are patch version agnostic when it is not a part of the test.
938            if version.patch().is_none() {
939                filters.push((
940                    format!(r"({})\.\d+", regex::escape(version.to_string().as_str())),
941                    "$1.[X]".to_string(),
942                ));
943            }
944        }
945
946        filters.extend(
947            Self::path_patterns(&bin_dir)
948                .into_iter()
949                .map(|pattern| (pattern, "[BIN]/".to_string())),
950        );
951        filters.extend(
952            Self::path_patterns(&cache_dir)
953                .into_iter()
954                .map(|pattern| (pattern, "[CACHE_DIR]/".to_string())),
955        );
956        if let Some(ref site_packages) = site_packages {
957            filters.extend(
958                Self::path_patterns(site_packages)
959                    .into_iter()
960                    .map(|pattern| (pattern, "[SITE_PACKAGES]/".to_string())),
961            );
962        }
963        filters.extend(
964            Self::path_patterns(&venv)
965                .into_iter()
966                .map(|pattern| (pattern, "[VENV]/".to_string())),
967        );
968
969        // Account for [`Simplified::user_display`] which is relative to the command working directory
970        if let Some(site_packages) = site_packages {
971            filters.push((
972                Self::path_pattern(
973                    site_packages
974                        .strip_prefix(&canonical_temp_dir)
975                        .expect("The test site-packages directory is always in the tempdir"),
976                ),
977                "[SITE_PACKAGES]/".to_string(),
978            ));
979        }
980
981        // Filter Python library path differences between Windows and Unix
982        filters.push((
983            r"[\\/]lib[\\/]python\d+\.\d+[\\/]".to_string(),
984            "/[PYTHON-LIB]/".to_string(),
985        ));
986        filters.push((r"[\\/]Lib[\\/]".to_string(), "/[PYTHON-LIB]/".to_string()));
987
988        filters.extend(
989            Self::path_patterns(&temp_dir)
990                .into_iter()
991                .map(|pattern| (pattern, "[TEMP_DIR]/".to_string())),
992        );
993        filters.extend(
994            Self::path_patterns(&python_dir)
995                .into_iter()
996                .map(|pattern| (pattern, "[PYTHON_DIR]/".to_string())),
997        );
998        let mut uv_user_config_dir = PathBuf::from(user_config_dir.path());
999        uv_user_config_dir.push("uv");
1000        filters.extend(
1001            Self::path_patterns(&uv_user_config_dir)
1002                .into_iter()
1003                .map(|pattern| (pattern, "[UV_USER_CONFIG_DIR]/".to_string())),
1004        );
1005        filters.extend(
1006            Self::path_patterns(&user_config_dir)
1007                .into_iter()
1008                .map(|pattern| (pattern, "[USER_CONFIG_DIR]/".to_string())),
1009        );
1010        filters.extend(
1011            Self::path_patterns(&home_dir)
1012                .into_iter()
1013                .map(|pattern| (pattern, "[HOME]/".to_string())),
1014        );
1015        filters.extend(
1016            Self::path_patterns(&workspace_root)
1017                .into_iter()
1018                .map(|pattern| (pattern, "[WORKSPACE]/".to_string())),
1019        );
1020
1021        // Make virtual environment activation cross-platform and shell-agnostic
1022        filters.push((
1023            r"Activate with: (.*)\\Scripts\\activate".to_string(),
1024            "Activate with: source $1/[BIN]/activate".to_string(),
1025        ));
1026        filters.push((
1027            r"Activate with: Scripts\\activate".to_string(),
1028            "Activate with: source [BIN]/activate".to_string(),
1029        ));
1030        filters.push((
1031            r"Activate with: source (.*/|)bin/activate(?:\.\w+)?".to_string(),
1032            "Activate with: source $1[BIN]/activate".to_string(),
1033        ));
1034
1035        // Filter non-deterministic temporary directory names
1036        // Note we apply this _after_ all the full paths to avoid breaking their matching
1037        filters.push((r"(\\|\/)\.tmp.*(\\|\/)".to_string(), "/[TMP]/".to_string()));
1038
1039        // Account for platform prefix differences `file://` (Unix) vs `file:///` (Windows)
1040        filters.push((r"file:///".to_string(), "file://".to_string()));
1041
1042        // Destroy any remaining UNC prefixes (Windows only)
1043        filters.push((r"\\\\\?\\".to_string(), String::new()));
1044
1045        // For wiremock tests
1046        filters.push((r"127\.0\.0\.1:\d*".to_string(), "[LOCALHOST]".to_string()));
1047        // Avoid breaking the tests when bumping the uv version
1048        filters.push((
1049            format!(
1050                r#"requires = \["uv_build>={},<[0-9.]+"\]"#,
1051                uv_version::version()
1052            ),
1053            r#"requires = ["uv_build>=[CURRENT_VERSION],<[NEXT_BREAKING]"]"#.to_string(),
1054        ));
1055        // Filter script environment hashes
1056        filters.push((
1057            r"environments-v(\d+)[\\/](\w+)-[a-z0-9]+".to_string(),
1058            "environments-v$1/$2-[HASH]".to_string(),
1059        ));
1060        // Filter archive hashes
1061        filters.push((
1062            r"archive-v(\d+)[\\/][A-Za-z0-9\-\_]+".to_string(),
1063            "archive-v$1/[HASH]".to_string(),
1064        ));
1065
1066        Self {
1067            root: ChildPath::new(root.path()),
1068            temp_dir,
1069            cache_dir,
1070            python_dir,
1071            home_dir,
1072            user_config_dir,
1073            bin_dir,
1074            venv,
1075            workspace_root,
1076            python_version,
1077            python_versions,
1078            uv_bin,
1079            filters,
1080            extra_env: vec![],
1081            _root: root,
1082            _extra_tempdirs: vec![],
1083        }
1084    }
1085
1086    /// Create a uv command for testing.
1087    pub fn command(&self) -> Command {
1088        let mut command = self.new_command();
1089        self.add_shared_options(&mut command, true);
1090        command
1091    }
1092
1093    pub fn disallow_git_cli(bin_dir: &Path) -> std::io::Result<()> {
1094        let contents = r"#!/bin/sh
1095    echo 'error: `git` operations are not allowed — are you missing a cfg for the `git` feature?' >&2
1096    exit 127";
1097        let git = bin_dir.join(format!("git{}", env::consts::EXE_SUFFIX));
1098        fs_err::write(&git, contents)?;
1099
1100        #[cfg(unix)]
1101        {
1102            use std::os::unix::fs::PermissionsExt;
1103            let mut perms = fs_err::metadata(&git)?.permissions();
1104            perms.set_mode(0o755);
1105            fs_err::set_permissions(&git, perms)?;
1106        }
1107
1108        Ok(())
1109    }
1110
1111    /// Setup Git LFS Filters
1112    ///
1113    /// You can find the default filters in <https://github.com/git-lfs/git-lfs/blob/v3.7.1/lfs/attribute.go#L66-L71>
1114    /// We set required to true to get a full stacktrace when these commands fail.
1115    #[must_use]
1116    pub fn with_git_lfs_config(mut self) -> Self {
1117        let git_lfs_config = self.root.child(".gitconfig");
1118        git_lfs_config
1119            .write_str(indoc! {r#"
1120                [filter "lfs"]
1121                    clean = git-lfs clean -- %f
1122                    smudge = git-lfs smudge -- %f
1123                    process = git-lfs filter-process
1124                    required = true
1125            "#})
1126            .expect("Failed to setup `git-lfs` filters");
1127
1128        // Its possible your system config can cause conflicts with the Git LFS tests.
1129        // In such cases, add self.extra_env.push(("GIT_CONFIG_NOSYSTEM".into(), "1".into()));
1130        self.extra_env.push((
1131            EnvVars::GIT_CONFIG_GLOBAL.into(),
1132            git_lfs_config.as_os_str().into(),
1133        ));
1134        self
1135    }
1136
1137    /// Shared behaviour for almost all test commands.
1138    ///
1139    /// * Use a temporary cache directory
1140    /// * Use a temporary virtual environment with the Python version of [`Self`]
1141    /// * Don't wrap text output based on the terminal we're in, the test output doesn't get printed
1142    ///   but snapshotted to a string.
1143    /// * Use a fake `HOME` to avoid accidentally changing the developer's machine.
1144    /// * Ignore system configuration to avoid reading machine-specific settings.
1145    /// * Hide other Pythons with `UV_PYTHON_INSTALL_DIR` and installed interpreters with
1146    ///   `UV_PYTHON_SEARCH_PATH` and an active venv (if applicable) by removing `VIRTUAL_ENV`.
1147    /// * Increase the stack size to avoid stack overflows on windows due to large async functions.
1148    pub fn add_shared_options(&self, command: &mut Command, activate_venv: bool) {
1149        self.add_shared_args(command);
1150        self.add_shared_env(command, activate_venv);
1151    }
1152
1153    /// Only the arguments of [`TestContext::add_shared_options`].
1154    fn add_shared_args(&self, command: &mut Command) {
1155        command.arg("--cache-dir").arg(self.cache_dir.path());
1156    }
1157
1158    /// Only the environment variables of [`TestContext::add_shared_options`].
1159    pub fn add_shared_env(&self, command: &mut Command, activate_venv: bool) {
1160        // Push the test context bin to the front of the PATH
1161        let path = env::join_paths(std::iter::once(self.bin_dir.to_path_buf()).chain(
1162            env::split_paths(&env::var(EnvVars::PATH).unwrap_or_default()),
1163        ))
1164        .unwrap();
1165
1166        // Ensure the tests aren't sensitive to the running user's shell without forcing
1167        // `bash` on Windows
1168        if cfg!(not(windows)) {
1169            command.env(EnvVars::SHELL, "bash");
1170        }
1171
1172        command
1173            // When running the tests in a venv, ignore that venv, otherwise we'll capture warnings.
1174            .env_remove(EnvVars::VIRTUAL_ENV)
1175            // Disable wrapping of uv output for readability / determinism in snapshots.
1176            .env(EnvVars::UV_NO_WRAP, "1")
1177            // Avoid reading host system configuration unless a test opts in.
1178            .env(EnvVars::UV_NO_SYSTEM_CONFIG, "1")
1179            // While we disable wrapping in uv above, invoked tools may still wrap their output so
1180            // we set a fixed `COLUMNS` value for isolation from terminal width.
1181            .env(EnvVars::COLUMNS, "100")
1182            .env(EnvVars::PATH, path)
1183            .env(EnvVars::HOME, self.home_dir.as_os_str())
1184            .env(EnvVars::APPDATA, self.home_dir.as_os_str())
1185            .env(EnvVars::USERPROFILE, self.home_dir.as_os_str())
1186            .env(
1187                EnvVars::XDG_CONFIG_DIRS,
1188                self.home_dir.join("config").as_os_str(),
1189            )
1190            .env(
1191                EnvVars::XDG_DATA_HOME,
1192                self.home_dir.join("data").as_os_str(),
1193            )
1194            .env(EnvVars::UV_NO_SYSTEM_CONFIG, "1")
1195            .env(EnvVars::UV_PYTHON_INSTALL_DIR, "")
1196            // Installations are not allowed by default; see `Self::with_managed_python_dirs`
1197            .env(EnvVars::UV_PYTHON_DOWNLOADS, "never")
1198            .env(EnvVars::UV_PYTHON_SEARCH_PATH, self.python_path())
1199            .env(EnvVars::UV_EXCLUDE_NEWER, TEST_TIMESTAMP)
1200            .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, TEST_TIMESTAMP)
1201            .env(EnvVars::UV_TEST_AVAILABLE_VERSION_CUTOFF, TEST_TIMESTAMP)
1202            // Keep Python discovery hermetic and avoid mutating global state, like the Windows
1203            // registry, unless a test opts in explicitly.
1204            .env(EnvVars::UV_PYTHON_NO_REGISTRY, "1")
1205            .env(EnvVars::UV_PYTHON_INSTALL_REGISTRY, "0")
1206            // Since downloads, fetches and builds run in parallel, their message output order is
1207            // non-deterministic, so can't capture them in test output.
1208            .env(EnvVars::UV_TEST_NO_CLI_PROGRESS, "1")
1209            // I believe the intent of all tests is that they are run outside the
1210            // context of an existing git repository. And when they aren't, state
1211            // from the parent git repository can bleed into the behavior of `uv
1212            // init` in a way that makes it difficult to test consistently. By
1213            // setting GIT_CEILING_DIRECTORIES, we specifically prevent git from
1214            // climbing up past the root of our test directory to look for any
1215            // other git repos.
1216            //
1217            // If one wants to write a test specifically targeting uv within a
1218            // pre-existing git repository, then the test should make the parent
1219            // git repo explicitly. The GIT_CEILING_DIRECTORIES here shouldn't
1220            // impact it, since it only prevents git from discovering repositories
1221            // at or above the root.
1222            .env(EnvVars::GIT_CEILING_DIRECTORIES, self.root.path())
1223            .current_dir(self.temp_dir.path());
1224
1225        for (key, value) in &self.extra_env {
1226            command.env(key, value);
1227        }
1228
1229        if activate_venv {
1230            command.env(EnvVars::VIRTUAL_ENV, self.venv.as_os_str());
1231        }
1232
1233        if cfg!(unix) {
1234            // Avoid locale issues in tests
1235            command.env(EnvVars::LC_ALL, "C");
1236        }
1237    }
1238
1239    /// Create a `pip compile` command for testing.
1240    pub fn pip_compile(&self) -> Command {
1241        let mut command = self.new_command();
1242        command.arg("pip").arg("compile");
1243        self.add_shared_options(&mut command, true);
1244        command
1245    }
1246
1247    /// Create a `pip compile` command for testing.
1248    pub fn pip_sync(&self) -> Command {
1249        let mut command = self.new_command();
1250        command.arg("pip").arg("sync");
1251        self.add_shared_options(&mut command, true);
1252        command
1253    }
1254
1255    pub fn pip_show(&self) -> Command {
1256        let mut command = self.new_command();
1257        command.arg("pip").arg("show");
1258        self.add_shared_options(&mut command, true);
1259        command
1260    }
1261
1262    /// Create a `pip freeze` command with options shared across scenarios.
1263    pub fn pip_freeze(&self) -> Command {
1264        let mut command = self.new_command();
1265        command.arg("pip").arg("freeze");
1266        self.add_shared_options(&mut command, true);
1267        command
1268    }
1269
1270    /// Create a `pip check` command with options shared across scenarios.
1271    pub fn pip_check(&self) -> Command {
1272        let mut command = self.new_command();
1273        command.arg("pip").arg("check");
1274        self.add_shared_options(&mut command, true);
1275        command
1276    }
1277
1278    pub fn pip_list(&self) -> Command {
1279        let mut command = self.new_command();
1280        command.arg("pip").arg("list");
1281        self.add_shared_options(&mut command, true);
1282        command
1283    }
1284
1285    /// Create a `uv venv` command
1286    pub fn venv(&self) -> Command {
1287        let mut command = self.new_command();
1288        command.arg("venv");
1289        self.add_shared_options(&mut command, false);
1290        command
1291    }
1292
1293    /// Create a `pip install` command with options shared across scenarios.
1294    pub fn pip_install(&self) -> Command {
1295        let mut command = self.new_command();
1296        command.arg("pip").arg("install");
1297        self.add_shared_options(&mut command, true);
1298        command
1299    }
1300
1301    /// Create a `pip uninstall` command with options shared across scenarios.
1302    pub fn pip_uninstall(&self) -> Command {
1303        let mut command = self.new_command();
1304        command.arg("pip").arg("uninstall");
1305        self.add_shared_options(&mut command, true);
1306        command
1307    }
1308
1309    /// Create a `pip tree` command for testing.
1310    pub fn pip_tree(&self) -> Command {
1311        let mut command = self.new_command();
1312        command.arg("pip").arg("tree");
1313        self.add_shared_options(&mut command, true);
1314        command
1315    }
1316
1317    /// Create a `pip debug` command for testing.
1318    pub fn pip_debug(&self) -> Command {
1319        let mut command = self.new_command();
1320        command.arg("pip").arg("debug");
1321        self.add_shared_options(&mut command, true);
1322        command
1323    }
1324
1325    /// Create a `uv help` command with options shared across scenarios.
1326    pub fn help(&self) -> Command {
1327        let mut command = self.new_command();
1328        command.arg("help");
1329        self.add_shared_env(&mut command, false);
1330        command
1331    }
1332
1333    /// Create a `uv init` command with options shared across scenarios and
1334    /// isolated from any git repository that may exist in a parent directory.
1335    pub fn init(&self) -> Command {
1336        let mut command = self.new_command();
1337        command.arg("init");
1338        self.add_shared_options(&mut command, false);
1339        command
1340    }
1341
1342    /// Create a `uv sync` command with options shared across scenarios.
1343    pub fn sync(&self) -> Command {
1344        let mut command = self.new_command();
1345        command.arg("sync");
1346        self.add_shared_options(&mut command, false);
1347        command
1348    }
1349
1350    /// Create a `uv lock` command with options shared across scenarios.
1351    pub fn lock(&self) -> Command {
1352        let mut command = self.new_command();
1353        command.arg("lock");
1354        self.add_shared_options(&mut command, false);
1355        command
1356    }
1357
1358    /// Create a `uv upgrade` command with options shared across scenarios.
1359    pub fn upgrade(&self) -> Command {
1360        let mut command = self.new_command();
1361        command.arg("upgrade");
1362        self.add_shared_options(&mut command, false);
1363        command
1364    }
1365
1366    /// Create a `uv audit` command with options shared across scenarios.
1367    pub fn audit(&self) -> Command {
1368        let mut command = self.new_command();
1369        command.arg("audit");
1370        self.add_shared_options(&mut command, false);
1371        command
1372    }
1373
1374    /// Create a `uv workspace metadata` command with options shared across scenarios.
1375    pub fn workspace_metadata(&self) -> Command {
1376        let mut command = self.new_command();
1377        command.arg("workspace").arg("metadata");
1378        self.add_shared_options(&mut command, false);
1379        command
1380    }
1381
1382    /// Create a `uv workspace dir` command with options shared across scenarios.
1383    pub fn workspace_dir(&self) -> Command {
1384        let mut command = self.new_command();
1385        command.arg("workspace").arg("dir");
1386        self.add_shared_options(&mut command, false);
1387        command
1388    }
1389
1390    /// Create a `uv workspace list` command with options shared across scenarios.
1391    pub fn workspace_list(&self) -> Command {
1392        let mut command = self.new_command();
1393        command.arg("workspace").arg("list");
1394        self.add_shared_options(&mut command, false);
1395        command
1396    }
1397
1398    /// Create a `uv export` command with options shared across scenarios.
1399    pub fn export(&self) -> Command {
1400        let mut command = self.new_command();
1401        command.arg("export");
1402        self.add_shared_options(&mut command, false);
1403        command
1404    }
1405
1406    /// Create a `uv format` command with options shared across scenarios.
1407    pub fn format(&self) -> Command {
1408        let mut command = self.new_command();
1409        command.arg("format");
1410        self.add_shared_options(&mut command, false);
1411        // Override to a more recent date for ruff version resolution
1412        command.env(EnvVars::UV_EXCLUDE_NEWER, "2026-02-15T00:00:00Z");
1413        command
1414    }
1415
1416    /// Create a `uv check` command with options shared across scenarios.
1417    pub fn check(&self) -> Command {
1418        let mut command = self.new_command();
1419        command.arg("check");
1420        self.add_shared_options(&mut command, false);
1421        // Override to a more recent date for ty version resolution
1422        command.env(EnvVars::UV_EXCLUDE_NEWER, "2026-02-15T00:00:00Z");
1423        command
1424    }
1425
1426    /// Create a `uv build` command with options shared across scenarios.
1427    pub fn build(&self) -> Command {
1428        let mut command = self.new_command();
1429        command.arg("build");
1430        self.add_shared_options(&mut command, false);
1431        command
1432    }
1433
1434    pub fn version(&self) -> Command {
1435        let mut command = self.new_command();
1436        command.arg("version");
1437        self.add_shared_options(&mut command, false);
1438        command
1439    }
1440
1441    pub fn self_version(&self) -> Command {
1442        let mut command = self.new_command();
1443        command.arg("self").arg("version");
1444        self.add_shared_options(&mut command, false);
1445        command
1446    }
1447
1448    pub fn self_update(&self) -> Command {
1449        let mut command = self.new_command();
1450        command.arg("self").arg("update");
1451        self.add_shared_options(&mut command, false);
1452        command
1453    }
1454
1455    /// Create a `uv publish` command with options shared across scenarios.
1456    pub fn publish(&self) -> Command {
1457        let mut command = self.new_command();
1458        command.arg("publish");
1459        self.add_shared_options(&mut command, false);
1460        command
1461    }
1462
1463    /// Create a `uv python find` command with options shared across scenarios.
1464    pub fn python_find(&self) -> Command {
1465        let mut command = self.new_command();
1466        command
1467            .arg("python")
1468            .arg("find")
1469            .env(EnvVars::UV_PREVIEW, "1")
1470            .env(EnvVars::UV_PYTHON_INSTALL_DIR, "");
1471        self.add_shared_options(&mut command, false);
1472        command
1473    }
1474
1475    /// Create a `uv python list` command with options shared across scenarios.
1476    pub fn python_list(&self) -> Command {
1477        let mut command = self.new_command();
1478        command
1479            .arg("python")
1480            .arg("list")
1481            .env(EnvVars::UV_PYTHON_INSTALL_DIR, "");
1482        self.add_shared_options(&mut command, false);
1483        command
1484    }
1485
1486    /// Create a `uv python install` command with options shared across scenarios.
1487    pub fn python_install(&self) -> Command {
1488        let mut command = self.new_command();
1489        command.arg("python").arg("install");
1490        self.add_shared_options(&mut command, true);
1491        command
1492    }
1493
1494    /// Create a `uv python uninstall` command with options shared across scenarios.
1495    pub fn python_uninstall(&self) -> Command {
1496        let mut command = self.new_command();
1497        command.arg("python").arg("uninstall");
1498        self.add_shared_options(&mut command, true);
1499        command
1500    }
1501
1502    /// Create a `uv python upgrade` command with options shared across scenarios.
1503    pub fn python_upgrade(&self) -> Command {
1504        let mut command = self.new_command();
1505        command.arg("python").arg("upgrade");
1506        self.add_shared_options(&mut command, true);
1507        command
1508    }
1509
1510    /// Create a `uv python pin` command with options shared across scenarios.
1511    pub fn python_pin(&self) -> Command {
1512        let mut command = self.new_command();
1513        command.arg("python").arg("pin");
1514        self.add_shared_options(&mut command, true);
1515        command
1516    }
1517
1518    /// Create a `uv python dir` command with options shared across scenarios.
1519    pub fn python_dir(&self) -> Command {
1520        let mut command = self.new_command();
1521        command.arg("python").arg("dir");
1522        self.add_shared_options(&mut command, true);
1523        command
1524    }
1525
1526    /// Create a `uv run` command with options shared across scenarios.
1527    pub fn run(&self) -> Command {
1528        let mut command = self.new_command();
1529        command.arg("run").env(EnvVars::UV_SHOW_RESOLUTION, "1");
1530        self.add_shared_options(&mut command, true);
1531        command
1532    }
1533
1534    /// Create a `uv tool run` command with options shared across scenarios.
1535    pub fn tool_run(&self) -> Command {
1536        let mut command = self.new_command();
1537        command
1538            .arg("tool")
1539            .arg("run")
1540            .env(EnvVars::UV_SHOW_RESOLUTION, "1");
1541        self.add_shared_options(&mut command, false);
1542        command
1543    }
1544
1545    /// Create a `uv upgrade run` command with options shared across scenarios.
1546    pub fn tool_upgrade(&self) -> Command {
1547        let mut command = self.new_command();
1548        command.arg("tool").arg("upgrade");
1549        self.add_shared_options(&mut command, false);
1550        command
1551    }
1552
1553    /// Create a `uv tool install` command with options shared across scenarios.
1554    pub fn tool_install(&self) -> Command {
1555        let mut command = self.new_command();
1556        command.arg("tool").arg("install");
1557        self.add_shared_options(&mut command, false);
1558        command
1559    }
1560
1561    /// Create a `uv tool list` command with options shared across scenarios.
1562    pub fn tool_list(&self) -> Command {
1563        let mut command = self.new_command();
1564        command.arg("tool").arg("list");
1565        self.add_shared_options(&mut command, false);
1566        command
1567    }
1568
1569    /// Create a `uv tool dir` command with options shared across scenarios.
1570    pub fn tool_dir(&self) -> Command {
1571        let mut command = self.new_command();
1572        command.arg("tool").arg("dir");
1573        self.add_shared_options(&mut command, false);
1574        command
1575    }
1576
1577    /// Create a `uv tool uninstall` command with options shared across scenarios.
1578    pub fn tool_uninstall(&self) -> Command {
1579        let mut command = self.new_command();
1580        command.arg("tool").arg("uninstall");
1581        self.add_shared_options(&mut command, false);
1582        command
1583    }
1584
1585    /// Create a `uv add` command for the given requirements.
1586    pub fn add(&self) -> Command {
1587        let mut command = self.new_command();
1588        command.arg("add");
1589        self.add_shared_options(&mut command, false);
1590        command
1591    }
1592
1593    /// Create a `uv remove` command for the given requirements.
1594    pub fn remove(&self) -> Command {
1595        let mut command = self.new_command();
1596        command.arg("remove");
1597        self.add_shared_options(&mut command, false);
1598        command
1599    }
1600
1601    /// Create a `uv tree` command with options shared across scenarios.
1602    pub fn tree(&self) -> Command {
1603        let mut command = self.new_command();
1604        command.arg("tree");
1605        self.add_shared_options(&mut command, false);
1606        command
1607    }
1608
1609    /// Create a `uv cache clean` command.
1610    pub fn clean(&self) -> Command {
1611        let mut command = self.new_command();
1612        command.arg("cache").arg("clean");
1613        self.add_shared_options(&mut command, false);
1614        command
1615    }
1616
1617    /// Create a `uv cache prune` command.
1618    pub fn prune(&self) -> Command {
1619        let mut command = self.new_command();
1620        command.arg("cache").arg("prune");
1621        self.add_shared_options(&mut command, false);
1622        command
1623    }
1624
1625    /// Create a `uv cache size` command.
1626    pub fn cache_size(&self) -> Command {
1627        let mut command = self.new_command();
1628        command.arg("cache").arg("size");
1629        self.add_shared_options(&mut command, false);
1630        command
1631    }
1632
1633    /// Create a `uv build_backend` command.
1634    ///
1635    /// Note that this command is hidden and only invoking it through a build frontend is supported.
1636    pub fn build_backend(&self) -> Command {
1637        let mut command = self.new_command();
1638        command.arg("build-backend");
1639        self.add_shared_options(&mut command, false);
1640        command
1641    }
1642
1643    /// The path to the Python interpreter in the venv.
1644    ///
1645    /// Don't use this for `Command::new`, use `Self::python_command` instead.
1646    pub fn interpreter(&self) -> PathBuf {
1647        let venv = &self.venv;
1648        if cfg!(unix) {
1649            venv.join("bin").join("python")
1650        } else if cfg!(windows) {
1651            venv.join("Scripts").join("python.exe")
1652        } else {
1653            unimplemented!("Only Windows and Unix are supported")
1654        }
1655    }
1656
1657    pub fn python_command(&self) -> Command {
1658        let mut interpreter = self.interpreter();
1659
1660        // If there's not a virtual environment, use the first Python interpreter in the context
1661        if !interpreter.exists() {
1662            interpreter.clone_from(
1663                &self
1664                    .python_versions
1665                    .first()
1666                    .expect("At least one Python version is required")
1667                    .1,
1668            );
1669        }
1670
1671        let mut command = Self::new_command_with(&interpreter);
1672        command
1673            // Our tests change files in <1s, so we must disable CPython bytecode caching or we'll get stale files
1674            // https://github.com/python/cpython/issues/75953
1675            .arg("-B")
1676            // Python on windows
1677            .env(EnvVars::PYTHONUTF8, "1");
1678
1679        self.add_shared_env(&mut command, false);
1680
1681        command
1682    }
1683
1684    /// Create a `uv auth login` command.
1685    pub fn auth_login(&self) -> Command {
1686        let mut command = self.new_command();
1687        command.arg("auth").arg("login");
1688        self.add_shared_options(&mut command, false);
1689        command
1690    }
1691
1692    /// Create a `uv auth logout` command.
1693    pub fn auth_logout(&self) -> Command {
1694        let mut command = self.new_command();
1695        command.arg("auth").arg("logout");
1696        self.add_shared_options(&mut command, false);
1697        command
1698    }
1699
1700    /// Create a `uv auth helper --protocol bazel get` command.
1701    pub fn auth_helper(&self) -> Command {
1702        let mut command = self.new_command();
1703        command.arg("auth").arg("helper");
1704        self.add_shared_options(&mut command, false);
1705        command
1706    }
1707
1708    /// Create a `uv auth token` command.
1709    pub fn auth_token(&self) -> Command {
1710        let mut command = self.new_command();
1711        command.arg("auth").arg("token");
1712        self.add_shared_options(&mut command, false);
1713        command
1714    }
1715
1716    /// Set `HOME` to the real home directory.
1717    ///
1718    /// We need this for testing commands which use the macOS keychain.
1719    #[must_use]
1720    pub fn with_real_home(mut self) -> Self {
1721        if let Some(home) = env::var_os(EnvVars::HOME) {
1722            self.extra_env
1723                .push((EnvVars::HOME.to_string().into(), home));
1724        }
1725        // Use the test's isolated config directory to avoid reading user
1726        // configuration files (like `.python-version`) that could interfere with tests.
1727        self.extra_env.push((
1728            EnvVars::XDG_CONFIG_HOME.into(),
1729            self.user_config_dir.as_os_str().into(),
1730        ));
1731        self
1732    }
1733
1734    /// Run the given python code and check whether it succeeds.
1735    pub fn assert_command(&self, command: &str) -> Assert {
1736        self.python_command()
1737            .arg("-c")
1738            .arg(command)
1739            .current_dir(&self.temp_dir)
1740            .assert()
1741    }
1742
1743    /// Run the given python file and check whether it succeeds.
1744    pub fn assert_file(&self, file: impl AsRef<Path>) -> Assert {
1745        self.python_command()
1746            .arg(file.as_ref())
1747            .current_dir(&self.temp_dir)
1748            .assert()
1749    }
1750
1751    /// Assert a package is installed with the given version.
1752    pub fn assert_installed(&self, package: &'static str, version: &'static str) {
1753        self.assert_command(
1754            format!("import {package} as package; print(package.__version__, end='')").as_str(),
1755        )
1756        .success()
1757        .stdout(version);
1758    }
1759
1760    /// Assert a package is not installed.
1761    pub fn assert_not_installed(&self, package: &'static str) {
1762        self.assert_command(format!("import {package}").as_str())
1763            .failure();
1764    }
1765
1766    /// Generate various escaped regex patterns for the given path.
1767    pub fn path_patterns(path: impl AsRef<Path>) -> Vec<String> {
1768        let mut patterns = Vec::new();
1769
1770        // We can only canonicalize paths that exist already
1771        if path.as_ref().exists() {
1772            patterns.push(Self::path_pattern(
1773                path.as_ref()
1774                    .canonicalize()
1775                    .expect("Failed to create canonical path"),
1776            ));
1777        }
1778
1779        // Include a non-canonicalized version
1780        patterns.push(Self::path_pattern(path));
1781
1782        patterns
1783    }
1784
1785    /// Generate an escaped regex pattern for the given path.
1786    fn path_pattern(path: impl AsRef<Path>) -> String {
1787        format!(
1788            // Trim the trailing separator for cross-platform directories filters
1789            r"{}\\?/?",
1790            regex::escape(&path.as_ref().simplified_display().to_string())
1791                // Make separators platform agnostic because on Windows we will display
1792                // paths with Unix-style separators sometimes
1793                .replace(r"\\", r"(\\|\/)")
1794        )
1795    }
1796
1797    pub fn python_path(&self) -> OsString {
1798        if cfg!(unix) {
1799            // On Unix, we needed to normalize the Python executable names to `python3` for the tests
1800            env::join_paths(
1801                self.python_versions
1802                    .iter()
1803                    .map(|(version, _)| self.python_dir.join(version.to_string())),
1804            )
1805            .unwrap()
1806        } else {
1807            // On Windows, just join the parent directories of the executables
1808            env::join_paths(
1809                self.python_versions
1810                    .iter()
1811                    .map(|(_, executable)| executable.parent().unwrap().to_path_buf()),
1812            )
1813            .unwrap()
1814        }
1815    }
1816
1817    /// Standard snapshot filters _plus_ those for this test context.
1818    pub fn filters(&self) -> Vec<(&str, &str)> {
1819        // Put test context snapshots before the default filters
1820        // This ensures we don't replace other patterns inside paths from the test context first
1821        self.filters
1822            .iter()
1823            .map(|(p, r)| (p.as_str(), r.as_str()))
1824            .chain(INSTA_FILTERS.iter().copied())
1825            .collect()
1826    }
1827
1828    /// Only the filters added to this test context.
1829    #[cfg(windows)]
1830    pub fn filters_without_standard_filters(&self) -> Vec<(&str, &str)> {
1831        self.filters
1832            .iter()
1833            .map(|(p, r)| (p.as_str(), r.as_str()))
1834            .collect()
1835    }
1836
1837    /// For when we add pypy to the test suite.
1838    pub fn python_kind(&self) -> &'static str {
1839        "python"
1840    }
1841
1842    /// Returns the site-packages folder inside the venv.
1843    pub fn site_packages(&self) -> PathBuf {
1844        site_packages_path(
1845            &self.venv,
1846            &format!(
1847                "{}{}",
1848                self.python_kind(),
1849                self.python_version.as_ref().expect(
1850                    "A Python version must be provided to retrieve the test site packages path"
1851                )
1852            ),
1853        )
1854    }
1855
1856    /// Reset the virtual environment in the test context.
1857    pub fn reset_venv(&self) {
1858        self.create_venv();
1859    }
1860
1861    /// Create a new virtual environment named `.venv` in the test context.
1862    fn create_venv(&self) {
1863        let executable = get_python(
1864            self.python_version
1865                .as_ref()
1866                .expect("A Python version must be provided to create a test virtual environment"),
1867        );
1868        create_venv_from_executable(&self.venv, &self.cache_dir, &executable, &self.uv_bin);
1869    }
1870
1871    /// Copies the files from the ecosystem project given into this text
1872    /// context.
1873    ///
1874    /// This will almost always write at least a `pyproject.toml` into this
1875    /// test context.
1876    ///
1877    /// The given name should correspond to the name of a sub-directory (not a
1878    /// path to it) in the `test/ecosystem` directory.
1879    ///
1880    /// This panics (fails the current test) for any failure.
1881    pub fn copy_ecosystem_project(&self, name: &str) {
1882        let project_dir = PathBuf::from(format!("../../test/ecosystem/{name}"));
1883        self.temp_dir.copy_from(project_dir, &["*"]).unwrap();
1884        // If there is a (gitignore) lockfile, remove it.
1885        if let Err(err) = fs_err::remove_file(self.temp_dir.join("uv.lock")) {
1886            assert_eq!(
1887                err.kind(),
1888                io::ErrorKind::NotFound,
1889                "Failed to remove uv.lock: {err}"
1890            );
1891        }
1892    }
1893
1894    /// Creates a way to compare the changes made to a lock file.
1895    ///
1896    /// This routine starts by copying (not moves) the generated lock file to
1897    /// memory. It then calls the given closure with this test context to get a
1898    /// `Command` and runs the command. The diff between the old lock file and
1899    /// the new one is then returned.
1900    ///
1901    /// This assumes that a lock has already been performed.
1902    pub fn diff_lock(&self, change: impl Fn(&Self) -> Command) -> String {
1903        static TRIM_TRAILING_WHITESPACE: std::sync::LazyLock<Regex> =
1904            std::sync::LazyLock::new(|| Regex::new(r"(?m)^\s+$").unwrap());
1905
1906        let lock_path = ChildPath::new(self.temp_dir.join("uv.lock"));
1907        let old_lock = fs_err::read_to_string(&lock_path).unwrap();
1908        let (snapshot, output) = run_and_format(
1909            change(self),
1910            self.filters(),
1911            "diff_lock",
1912            Some(WindowsFilters::Platform),
1913            None,
1914        );
1915        assert!(output.status.success(), "{snapshot}");
1916        let new_lock = fs_err::read_to_string(&lock_path).unwrap();
1917        diff_snapshot(&old_lock, &new_lock, 10)
1918    }
1919
1920    /// Read a file in the temporary directory
1921    pub fn read(&self, file: impl AsRef<Path>) -> String {
1922        fs_err::read_to_string(self.temp_dir.join(&file))
1923            .unwrap_or_else(|_| panic!("Missing file: `{}`", file.user_display()))
1924    }
1925
1926    /// Creates a new `Command` that is intended to be suitable for use in
1927    /// all tests.
1928    fn new_command(&self) -> Command {
1929        Self::new_command_with(&self.uv_bin)
1930    }
1931
1932    /// Creates a new `Command` that is intended to be suitable for use in
1933    /// all tests, but with the given binary.
1934    ///
1935    /// Clears environment variables defined in [`EnvVars`] to avoid reading
1936    /// test host settings.
1937    fn new_command_with(bin: &Path) -> Command {
1938        let mut command = Command::new(bin);
1939
1940        let passthrough = [
1941            // For linux distributions
1942            EnvVars::PATH,
1943            // For debugging tests.
1944            EnvVars::RUST_LOG,
1945            EnvVars::RUST_BACKTRACE,
1946            // Windows System configuration.
1947            EnvVars::SYSTEMDRIVE,
1948            // Work around small default stack sizes and large futures in debug builds.
1949            EnvVars::RUST_MIN_STACK,
1950            EnvVars::UV_STACK_SIZE,
1951            // Allow running tests with custom network settings.
1952            EnvVars::ALL_PROXY,
1953            EnvVars::HTTPS_PROXY,
1954            EnvVars::HTTP_PROXY,
1955            EnvVars::NO_PROXY,
1956            EnvVars::SSL_CERT_DIR,
1957            EnvVars::SSL_CERT_FILE,
1958            EnvVars::UV_NATIVE_TLS,
1959            EnvVars::UV_SYSTEM_CERTS,
1960        ];
1961
1962        for env_var in EnvVars::all_names()
1963            .iter()
1964            .filter(|name| !passthrough.contains(name))
1965        {
1966            command.env_remove(env_var);
1967        }
1968
1969        command
1970    }
1971}
1972
1973/// Creates a "unified" diff between the two line-oriented strings suitable
1974/// for snapshotting.
1975pub fn diff_snapshot(old: &str, new: &str, context_radius: usize) -> String {
1976    static TRIM_TRAILING_WHITESPACE: std::sync::LazyLock<Regex> =
1977        std::sync::LazyLock::new(|| Regex::new(r"(?m)^\s+$").unwrap());
1978
1979    let diff = similar::TextDiff::from_lines(old, new);
1980    let unified = diff
1981        .unified_diff()
1982        .context_radius(context_radius)
1983        .header("old", "new")
1984        .to_string();
1985    // Not totally clear why, but some lines end up containing only
1986    // whitespace in the diff, even though they don't appear in the
1987    // original data. So just strip them here.
1988    TRIM_TRAILING_WHITESPACE
1989        .replace_all(&unified, "")
1990        .into_owned()
1991}
1992
1993/// Assert a snapshot of the diff between `old` and a command's output.
1994///
1995/// Returns the command's snapshot, this is useful for chaining diffs.
1996#[macro_export]
1997macro_rules! diff_uv_snapshot {
1998    ($filters:expr, $old:expr, $spawnable:expr, @$snapshot:literal) => {{
1999        let new = $crate::capture_uv_snapshot!($filters, $spawnable);
2000        let snapshot = $crate::diff_snapshot($old, &new, 3);
2001        let mut settings = ::insta::Settings::clone_current();
2002        // Show the complete diff on failure while avoiding assertions on its unstable metadata.
2003        let description = match settings.description() {
2004            Some(description) => format!("{description}\n\nUnfiltered diff:\n{snapshot}"),
2005            None => format!("Unfiltered diff:\n{snapshot}"),
2006        };
2007        settings.set_description(description);
2008        settings.add_filter(r"^--- old\n\+\+\+ new\n", "");
2009        settings.add_filter(r"(?m)^@@.*$", "...");
2010        settings.add_filter(r"\n$", "\n...\n");
2011        settings.bind(|| {
2012            ::insta::assert_snapshot!(snapshot, @$snapshot);
2013        });
2014        new
2015    }};
2016}
2017
2018/// Capture a command's output, optionally asserting it against a snapshot.
2019#[macro_export]
2020macro_rules! capture_uv_snapshot {
2021    ($filters:expr, $spawnable:expr) => {{
2022        // Don't echo the output to stderr while capturing without asserting.
2023        let (snapshot, _) = $crate::run_and_format_silent(
2024            $spawnable,
2025            &$filters,
2026            $crate::function_name!(),
2027            Some($crate::WindowsFilters::Platform),
2028            None,
2029        );
2030        snapshot
2031    }};
2032    ($filters:expr, $spawnable:expr, @$snapshot:literal) => {{
2033        let (snapshot, _) = $crate::run_and_format(
2034            $spawnable,
2035            &$filters,
2036            $crate::function_name!(),
2037            Some($crate::WindowsFilters::Platform),
2038            None,
2039        );
2040        ::insta::assert_snapshot!(snapshot, @$snapshot);
2041        snapshot
2042    }};
2043}
2044
2045pub fn site_packages_path(venv: &Path, python: &str) -> PathBuf {
2046    if cfg!(unix) {
2047        venv.join("lib").join(python).join("site-packages")
2048    } else if cfg!(windows) {
2049        venv.join("Lib").join("site-packages")
2050    } else {
2051        unimplemented!("Only Windows and Unix are supported")
2052    }
2053}
2054
2055pub fn venv_bin_path(venv: impl AsRef<Path>) -> PathBuf {
2056    if cfg!(unix) {
2057        venv.as_ref().join("bin")
2058    } else if cfg!(windows) {
2059        venv.as_ref().join("Scripts")
2060    } else {
2061        unimplemented!("Only Windows and Unix are supported")
2062    }
2063}
2064
2065/// Get the path to the python interpreter for a specific python version.
2066fn get_python(version: &PythonVersion) -> PathBuf {
2067    ManagedPythonInstallations::from_settings(None)
2068        .map(|installed_pythons| {
2069            installed_pythons
2070                .find_version(version)
2071                .expect("Tests are run on a supported platform")
2072                .next()
2073                .as_ref()
2074                .map(|python| python.executable(false))
2075        })
2076        // We'll search for the request Python on the PATH if not found in the python versions
2077        // We hack this into a `PathBuf` to satisfy the compiler but it's just a string
2078        .unwrap_or_default()
2079        .unwrap_or(PathBuf::from(version.to_string()))
2080}
2081
2082/// Create a virtual environment at the given path.
2083fn create_venv_from_executable<P: AsRef<Path>>(
2084    path: P,
2085    cache_dir: &ChildPath,
2086    python: &Path,
2087    uv_bin: &Path,
2088) {
2089    TestContext::new_command_with(uv_bin)
2090        .arg("venv")
2091        .arg(path.as_ref().as_os_str())
2092        .arg("--clear")
2093        .arg("--cache-dir")
2094        .arg(cache_dir.path())
2095        .arg("--python")
2096        .arg(python)
2097        .current_dir(path.as_ref().parent().unwrap())
2098        .assert()
2099        .success();
2100    ChildPath::new(path.as_ref()).assert(predicate::path::is_dir());
2101}
2102
2103/// Create a `PATH` with the requested Python versions available in order.
2104///
2105/// Generally this should be used with `UV_PYTHON_SEARCH_PATH`.
2106pub fn python_path_with_versions(
2107    temp_dir: &ChildPath,
2108    python_versions: &[&str],
2109) -> anyhow::Result<OsString> {
2110    let download_list = ManagedPythonDownloadList::new_only_embedded().unwrap();
2111    Ok(env::join_paths(
2112        python_installations_for_versions(temp_dir, python_versions, &download_list)?
2113            .into_iter()
2114            .map(|path| path.parent().unwrap().to_path_buf()),
2115    )?)
2116}
2117
2118/// Returns a list of Python executables for the given versions.
2119///
2120/// Generally this should be used with `UV_PYTHON_SEARCH_PATH`.
2121fn python_installations_for_versions(
2122    temp_dir: &ChildPath,
2123    python_versions: &[&str],
2124    download_list: &ManagedPythonDownloadList,
2125) -> anyhow::Result<Vec<PathBuf>> {
2126    let cache = Cache::from_path(temp_dir.child("cache").to_path_buf())
2127        .init_no_wait()?
2128        .expect("No cache contention when setting up Python in tests");
2129    let _preview = uv_preview::test::with_features(&[]);
2130    let selected_pythons = python_versions
2131        .iter()
2132        .map(|python_version| {
2133            if let Ok(python) = PythonInstallation::find(
2134                &PythonRequest::parse(python_version),
2135                EnvironmentPreference::OnlySystem,
2136                PythonPreference::Managed,
2137                download_list,
2138                &cache,
2139            ) {
2140                python.into_interpreter().sys_executable().to_owned()
2141            } else {
2142                panic!("Could not find Python {python_version} for test\nTry `cargo run python install` first, or refer to CONTRIBUTING.md");
2143            }
2144        })
2145        .collect::<Vec<_>>();
2146
2147    assert!(
2148        python_versions.is_empty() || !selected_pythons.is_empty(),
2149        "Failed to fulfill requested test Python versions: {selected_pythons:?}"
2150    );
2151
2152    Ok(selected_pythons)
2153}
2154
2155#[derive(Debug, Copy, Clone)]
2156pub enum WindowsFilters {
2157    Platform,
2158    Universal,
2159}
2160
2161/// Helper method to apply filters to a string. Useful when `!uv_snapshot` cannot be used.
2162pub fn apply_filters<T: AsRef<str>>(mut snapshot: String, filters: impl AsRef<[(T, T)]>) -> String {
2163    for (matcher, replacement) in filters.as_ref() {
2164        // TODO(konstin): Cache regex compilation
2165        let re = Regex::new(matcher.as_ref()).expect("Do you need to regex::escape your filter?");
2166        if re.is_match(&snapshot) {
2167            snapshot = re.replace_all(&snapshot, replacement.as_ref()).to_string();
2168        }
2169    }
2170    snapshot
2171}
2172
2173/// Execute the command and format its output status, stdout and stderr into a snapshot string.
2174///
2175/// This function is derived from `insta_cmd`s `spawn_with_info`.
2176#[expect(clippy::print_stderr)]
2177pub fn run_and_format<T: AsRef<str>>(
2178    command: impl BorrowMut<Command>,
2179    filters: impl AsRef<[(T, T)]>,
2180    function_name: &str,
2181    windows_filters: Option<WindowsFilters>,
2182    input: Option<&str>,
2183) -> (String, Output) {
2184    let (snapshot, output) =
2185        run_and_format_silent(command, filters, function_name, windows_filters, input);
2186    eprintln!("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Unfiltered output ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
2187    eprintln!(
2188        "----- stdout -----\n{}\n----- stderr -----\n{}",
2189        String::from_utf8_lossy(&output.stdout),
2190        String::from_utf8_lossy(&output.stderr),
2191    );
2192    eprintln!("────────────────────────────────────────────────────────────────────────────────\n");
2193    (snapshot, output)
2194}
2195
2196/// Execute the command and format its output without printing the unfiltered output.
2197#[doc(hidden)]
2198pub fn run_and_format_silent<T: AsRef<str>>(
2199    mut command: impl BorrowMut<Command>,
2200    filters: impl AsRef<[(T, T)]>,
2201    function_name: &str,
2202    windows_filters: Option<WindowsFilters>,
2203    input: Option<&str>,
2204) -> (String, Output) {
2205    let program = command
2206        .borrow_mut()
2207        .get_program()
2208        .to_string_lossy()
2209        .to_string();
2210
2211    // Support profiling test run commands with traces.
2212    if let Ok(root) = env::var(EnvVars::TRACING_DURATIONS_TEST_ROOT) {
2213        // We only want to fail if the variable is set at runtime.
2214        #[expect(clippy::assertions_on_constants)]
2215        {
2216            assert!(
2217                cfg!(feature = "tracing-durations-export"),
2218                "You need to enable the tracing-durations-export feature to use `TRACING_DURATIONS_TEST_ROOT`"
2219            );
2220        }
2221        command.borrow_mut().env(
2222            EnvVars::TRACING_DURATIONS_FILE,
2223            Path::new(&root).join(function_name).with_extension("jsonl"),
2224        );
2225    }
2226
2227    let output = if let Some(input) = input {
2228        let mut child = command
2229            .borrow_mut()
2230            .stdin(Stdio::piped())
2231            .stdout(Stdio::piped())
2232            .stderr(Stdio::piped())
2233            .spawn()
2234            .unwrap_or_else(|err| panic!("Failed to spawn {program}: {err}"));
2235        child
2236            .stdin
2237            .as_mut()
2238            .expect("Failed to open stdin")
2239            .write_all(input.as_bytes())
2240            .expect("Failed to write to stdin");
2241
2242        child
2243            .wait_with_output()
2244            .unwrap_or_else(|err| panic!("Failed to read output from {program}: {err}"))
2245    } else {
2246        command
2247            .borrow_mut()
2248            .output()
2249            .unwrap_or_else(|err| panic!("Failed to spawn {program}: {err}"))
2250    };
2251
2252    let mut snapshot = apply_filters(
2253        format!(
2254            "success: {:?}\nexit_code: {}\n----- stdout -----\n{}\n----- stderr -----\n{}",
2255            output.status.success(),
2256            output.status.code().unwrap_or(!0),
2257            String::from_utf8_lossy(&output.stdout),
2258            String::from_utf8_lossy(&output.stderr),
2259        ),
2260        filters,
2261    );
2262
2263    // This is a heuristic filter meant to try and make *most* of our tests
2264    // pass whether it's on Windows or Unix. In particular, there are some very
2265    // common Windows-only dependencies that, when removed from a resolution,
2266    // cause the set of dependencies to be the same across platforms.
2267    if cfg!(windows) {
2268        if let Some(windows_filters) = windows_filters {
2269            // The optional leading +/-/~ is for install logs, the optional next line is for lockfiles
2270            let windows_only_deps = [
2271                (r"( ?[-+~] ?)?colorama==\d+(\.\d+)+( [\\]\n\s+--hash=.*)?\n(\s+# via .*\n)?"),
2272                (r"( ?[-+~] ?)?colorama==\d+(\.\d+)+(\s+[-+~]?\s+# via .*)?\n"),
2273                (r"( ?[-+~] ?)?tzdata==\d+(\.\d+)+( [\\]\n\s+--hash=.*)?\n(\s+# via .*\n)?"),
2274                (r"( ?[-+~] ?)?tzdata==\d+(\.\d+)+(\s+[-+~]?\s+# via .*)?\n"),
2275            ];
2276            let mut removed_packages = 0;
2277            for windows_only_dep in windows_only_deps {
2278                // TODO(konstin): Cache regex compilation
2279                let re = Regex::new(windows_only_dep).unwrap();
2280                if re.is_match(&snapshot) {
2281                    snapshot = re.replace(&snapshot, "").to_string();
2282                    removed_packages += 1;
2283                }
2284            }
2285            if removed_packages > 0 {
2286                for i in 1..20 {
2287                    for verb in match windows_filters {
2288                        WindowsFilters::Platform => [
2289                            "Resolved",
2290                            "Prepared",
2291                            "Installed",
2292                            "Checked",
2293                            "Uninstalled",
2294                        ]
2295                        .iter(),
2296                        WindowsFilters::Universal => {
2297                            ["Prepared", "Installed", "Checked", "Uninstalled"].iter()
2298                        }
2299                    } {
2300                        snapshot = snapshot.replace(
2301                            &format!("{verb} {} packages", i + removed_packages),
2302                            &format!("{verb} {} package{}", i, if i > 1 { "s" } else { "" }),
2303                        );
2304                    }
2305                }
2306            }
2307        }
2308    }
2309
2310    (snapshot, output)
2311}
2312
2313/// Recursively copy a directory and its contents, skipping gitignored files.
2314pub fn copy_dir_ignore(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> anyhow::Result<()> {
2315    for entry in ignore::Walk::new(&src) {
2316        let entry = entry?;
2317        let relative = entry.path().strip_prefix(&src)?;
2318        let ty = entry.file_type().unwrap();
2319        if ty.is_dir() {
2320            fs_err::create_dir(dst.as_ref().join(relative))?;
2321        } else {
2322            fs_err::copy(entry.path(), dst.as_ref().join(relative))?;
2323        }
2324    }
2325    Ok(())
2326}
2327
2328/// Create a stub package `name` in `dir` with the given `pyproject.toml` body.
2329pub fn make_project(dir: &Path, name: &str, body: &str) -> anyhow::Result<()> {
2330    let pyproject_toml = formatdoc! {r#"
2331        [project]
2332        name = "{name}"
2333        version = "0.1.0"
2334        requires-python = ">=3.11,<3.13"
2335        {body}
2336
2337        [build-system]
2338        requires = ["uv_build>=0.9.0,<10000"]
2339        build-backend = "uv_build"
2340        "#
2341    };
2342    fs_err::create_dir_all(dir)?;
2343    fs_err::write(dir.join("pyproject.toml"), pyproject_toml)?;
2344    fs_err::create_dir_all(dir.join("src").join(name))?;
2345    fs_err::write(dir.join("src").join(name).join("__init__.py"), "")?;
2346    Ok(())
2347}
2348
2349// This is a fine-grained token that only has read-only access to the `uv-private-pypackage` repository
2350pub const READ_ONLY_GITHUB_TOKEN: &[&str] = &[
2351    "Z2l0aHViCg==",
2352    "cGF0Cg==",
2353    "MTFBQlVDUjZBMERMUTQ3aVphN3hPdV9qQmhTMkZUeHZ4ZE13OHczakxuZndsV2ZlZjc2cE53eHBWS2tiRUFwdnpmUk8zV0dDSUhicDFsT01aago=",
2354];
2355
2356// This is a fine-grained token that only has read-only access to the `uv-private-pypackage-2` repository
2357#[cfg(not(windows))]
2358pub const READ_ONLY_GITHUB_TOKEN_2: &[&str] = &[
2359    "Z2l0aHViCg==",
2360    "cGF0Cg==",
2361    "MTFBQlVDUjZBMDJTOFYwMTM4YmQ0bV9uTXpueWhxZDBrcllROTQ5SERTeTI0dENKZ2lmdzIybDFSR2s1SE04QW8xTUVYQ1I0Q1YxYUdPRGpvZQo=",
2362];
2363
2364pub const READ_ONLY_GITHUB_SSH_DEPLOY_KEY: &str = "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUFNd0FBQUF0emMyZ3RaVwpReU5UVXhPUUFBQUNBeTF1SnNZK1JXcWp1NkdIY3Z6a3AwS21yWDEwdmo3RUZqTkpNTkRqSGZPZ0FBQUpqWUpwVnAyQ2FWCmFRQUFBQXR6YzJndFpXUXlOVFV4T1FBQUFDQXkxdUpzWStSV3FqdTZHSGN2emtwMEttclgxMHZqN0VGak5KTU5EakhmT2cKQUFBRUMwbzBnd1BxbGl6TFBJOEFXWDVaS2dVZHJyQ2ptMDhIQm9FenB4VDg3MXBqTFc0bXhqNUZhcU83b1lkeS9PU25RcQphdGZYUytQc1FXTTBrdzBPTWQ4NkFBQUFFR3R2Ym5OMGFVQmhjM1J5WVd3dWMyZ0JBZ01FQlE9PQotLS0tLUVORCBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0K";
2365
2366/// Decode a split, base64 encoded authentication token.
2367/// We split and encode the token to bypass revoke by GitHub's secret scanning
2368pub fn decode_token(content: &[&str]) -> String {
2369    content
2370        .iter()
2371        .map(|part| base64.decode(part).unwrap())
2372        .map(|decoded| {
2373            std::str::from_utf8(decoded.as_slice())
2374                .unwrap()
2375                .trim_end()
2376                .to_string()
2377        })
2378        .join("_")
2379}
2380
2381/// Simulates `reqwest::blocking::get` but returns bytes directly, and disables
2382/// certificate verification, passing through the `BaseClient`
2383#[tokio::main(flavor = "current_thread")]
2384pub async fn download_to_disk(url: &str, path: &Path) {
2385    let trusted_hosts: Vec<_> = env::var(EnvVars::UV_INSECURE_HOST)
2386        .unwrap_or_default()
2387        .split(' ')
2388        .map(|h| uv_configuration::TrustedHost::from_str(h).unwrap())
2389        .collect();
2390
2391    let client = uv_client::BaseClientBuilder::default()
2392        .allow_insecure_host(trusted_hosts)
2393        .build()
2394        .expect("failed to build base client");
2395    let url = url.parse().unwrap();
2396    let response = client
2397        .for_host(&url)
2398        .get(reqwest::Url::from(url))
2399        .send()
2400        .await
2401        .unwrap();
2402
2403    let mut file = fs_err::tokio::File::create(path).await.unwrap();
2404    let mut stream = response.bytes_stream();
2405    while let Some(chunk) = stream.next().await {
2406        file.write_all(&chunk.unwrap()).await.unwrap();
2407    }
2408    file.sync_all().await.unwrap();
2409}
2410
2411/// A guard that sets a directory to read-only and restores original permissions when dropped.
2412///
2413/// This is useful for tests that need to make a directory read-only and ensure
2414/// the permissions are restored even if the test panics.
2415#[cfg(unix)]
2416pub struct ReadOnlyDirectoryGuard {
2417    path: PathBuf,
2418    original_mode: u32,
2419}
2420
2421#[cfg(unix)]
2422impl ReadOnlyDirectoryGuard {
2423    /// Sets the directory to read-only (removes write permission) and returns a guard
2424    /// that will restore the original permissions when dropped.
2425    pub fn new(path: impl Into<PathBuf>) -> std::io::Result<Self> {
2426        use std::os::unix::fs::PermissionsExt;
2427        let path = path.into();
2428        let metadata = fs_err::metadata(&path)?;
2429        let original_mode = metadata.permissions().mode();
2430        // Remove write permissions (keep read and execute)
2431        let readonly_mode = original_mode & !0o222;
2432        fs_err::set_permissions(&path, std::fs::Permissions::from_mode(readonly_mode))?;
2433        Ok(Self {
2434            path,
2435            original_mode,
2436        })
2437    }
2438}
2439
2440#[cfg(unix)]
2441impl Drop for ReadOnlyDirectoryGuard {
2442    fn drop(&mut self) {
2443        use std::os::unix::fs::PermissionsExt;
2444        let _ = fs_err::set_permissions(
2445            &self.path,
2446            std::fs::Permissions::from_mode(self.original_mode),
2447        );
2448    }
2449}
2450
2451/// Utility macro to return the name of the current function.
2452///
2453/// https://stackoverflow.com/a/40234666/3549270
2454#[doc(hidden)]
2455#[macro_export]
2456macro_rules! function_name {
2457    () => {{
2458        fn f() {}
2459        fn type_name_of_val<T>(_: T) -> &'static str {
2460            std::any::type_name::<T>()
2461        }
2462        let mut name = type_name_of_val(f).strip_suffix("::f").unwrap_or("");
2463        while let Some(rest) = name.strip_suffix("::{{closure}}") {
2464            name = rest;
2465        }
2466        name
2467    }};
2468}
2469
2470/// Run [`assert_cmd_snapshot!`], with default filters or with custom filters.
2471///
2472/// By default, the filters will search for the generally windows-only deps colorama and tzdata,
2473/// filter them out and decrease the package counts by one for each match.
2474#[macro_export]
2475macro_rules! uv_snapshot {
2476    ($spawnable:expr, @$snapshot:literal) => {{
2477        uv_snapshot!($crate::INSTA_FILTERS.to_vec(), $spawnable, @$snapshot)
2478    }};
2479    ($filters:expr, $spawnable:expr, @$snapshot:literal) => {{
2480        // Take a reference for backwards compatibility with the vec-expecting insta filters.
2481        let (snapshot, output) = $crate::run_and_format($spawnable, &$filters, $crate::function_name!(), Some($crate::WindowsFilters::Platform), None);
2482        ::insta::assert_snapshot!(snapshot, @$snapshot);
2483        output
2484    }};
2485    ($filters:expr, $spawnable:expr, input=$input:expr, @$snapshot:literal) => {{
2486        // Take a reference for backwards compatibility with the vec-expecting insta filters.
2487        let (snapshot, output) = $crate::run_and_format($spawnable, &$filters, $crate::function_name!(), Some($crate::WindowsFilters::Platform), Some($input));
2488        ::insta::assert_snapshot!(snapshot, @$snapshot);
2489        output
2490    }};
2491    ($filters:expr, windows_filters=false, $spawnable:expr, @$snapshot:literal) => {{
2492        // Take a reference for backwards compatibility with the vec-expecting insta filters.
2493        let (snapshot, output) = $crate::run_and_format($spawnable, &$filters, $crate::function_name!(), None, None);
2494        ::insta::assert_snapshot!(snapshot, @$snapshot);
2495        output
2496    }};
2497    ($filters:expr, universal_windows_filters=true, $spawnable:expr, @$snapshot:literal) => {{
2498        // Take a reference for backwards compatibility with the vec-expecting insta filters.
2499        let (snapshot, output) = $crate::run_and_format($spawnable, &$filters, $crate::function_name!(), Some($crate::WindowsFilters::Universal), None);
2500        ::insta::assert_snapshot!(snapshot, @$snapshot);
2501        output
2502    }};
2503}