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