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