1#![allow(dead_code, unreachable_pub)]
3
4pub mod find_links;
5mod http_server;
6pub mod packse;
7pub mod pypi_proxy;
8mod vendor;
9
10use std::borrow::BorrowMut;
11use std::ffi::OsString;
12use std::io::Write as _;
13use std::iter::Iterator;
14use std::path::{Path, PathBuf};
15use std::process::{Command, Output, Stdio};
16use std::str::FromStr;
17use std::{env, io};
18use uv_python::downloads::ManagedPythonDownloadList;
19
20use assert_cmd::assert::{Assert, OutputAssertExt};
21use assert_fs::assert::PathAssert;
22use assert_fs::fixture::{
23 ChildPath, FileWriteStr, PathChild, PathCopy, PathCreateDir, SymlinkToFile,
24};
25use base64::{Engine, prelude::BASE64_STANDARD as base64};
26use futures::StreamExt;
27use indoc::{formatdoc, indoc};
28use itertools::Itertools;
29use predicates::prelude::predicate;
30use regex::{Regex, regex};
31use tokio::io::AsyncWriteExt;
32
33use uv_cache::{Cache, CacheBucket};
34use uv_fs::Simplified;
35use uv_python::managed::ManagedPythonInstallations;
36use uv_python::{
37 EnvironmentPreference, PythonInstallation, PythonPreference, PythonRequest, PythonVersion,
38};
39use uv_static::EnvVars;
40
41static TEST_TIMESTAMP: &str = "2024-03-25T00:00:00Z";
43
44pub const DEFAULT_PYTHON_VERSION: &str = "3.12";
45
46const LATEST_PYTHON_3_15: &str = "3.15.0rc1";
48const LATEST_PYTHON_3_14: &str = "3.14.7";
49const LATEST_PYTHON_3_13: &str = "3.13.15";
50pub const LATEST_PYTHON_3_12: &str = "3.12.13";
51const LATEST_PYTHON_3_11: &str = "3.11.15";
52const LATEST_PYTHON_3_10: &str = "3.10.20";
53
54#[macro_export]
61macro_rules! test_context {
62 ($python_version:expr) => {
63 $crate::TestContext::new_with_bin(
64 $python_version,
65 std::path::PathBuf::from(env!("CARGO_BIN_EXE_uv")),
66 )
67 };
68}
69
70#[macro_export]
77macro_rules! test_context_with_versions {
78 ($python_versions:expr) => {
79 $crate::TestContext::new_with_versions_and_bin(
80 $python_versions,
81 std::path::PathBuf::from(env!("CARGO_BIN_EXE_uv")),
82 )
83 };
84}
85
86#[macro_export]
91macro_rules! get_bin {
92 () => {
93 std::path::PathBuf::from(env!("CARGO_BIN_EXE_uv"))
94 };
95}
96
97#[doc(hidden)] pub const INSTA_FILTERS: &[(&str, &str)] = &[
99 (r"--cache-dir [^\s]+", "--cache-dir [CACHE_DIR]"),
100 (r"(\s|\()(\d+m )?(\d+\.)?\d+(ms|s)", "$1[TIME]"),
102 (r"tv_sec: \d+", "tv_sec: [TIME]"),
104 (r"tv_nsec: \d+", "tv_nsec: [TIME]"),
105 (r"\\([\w\d]|\.)", "/$1"),
107 (r"uv\.exe", "uv"),
108 (
110 r"uv(-.*)? \d+\.\d+\.\d+(-(alpha|beta|rc)\.\d+)?(\+\d+)?( \([^)]*\))?",
111 r"uv [VERSION] ([COMMIT] DATE)",
112 ),
113 (r"([^\s])[ \t]+(\r?\n)", "$1$2"),
115 (
117 r"(?ms)^([ \t]*custom_certificates: )(?:None|Some\(\n.*?^[ \t]*\),\n[ \t]*\)),",
118 "${1}[CERTIFICATES],",
119 ),
120 (r"DEBUG Loaded \d+ certificate\(s\) from [^\n]+\n", ""),
122];
123
124pub struct TestContext {
131 pub root: ChildPath,
132 pub temp_dir: ChildPath,
133 pub cache_dir: ChildPath,
134 python_dir: ChildPath,
135 pub home_dir: ChildPath,
136 pub user_config_dir: ChildPath,
137 pub bin_dir: ChildPath,
138 pub venv: ChildPath,
139 pub workspace_root: PathBuf,
140
141 python_version: Option<PythonVersion>,
143
144 pub python_versions: Vec<(PythonVersion, PathBuf)>,
146
147 uv_bin: PathBuf,
149
150 filters: Vec<(String, String)>,
152
153 extra_env: Vec<(OsString, OsString)>,
155
156 #[allow(dead_code)]
157 _root: tempfile::TempDir,
158
159 #[allow(dead_code)]
162 _extra_tempdirs: Vec<tempfile::TempDir>,
163}
164
165impl TestContext {
166 pub fn new_with_bin(python_version: &str, uv_bin: PathBuf) -> Self {
170 let new = Self::new_with_versions_and_bin(&[python_version], uv_bin);
171 new.create_venv();
172 new
173 }
174
175 #[must_use]
177 pub fn with_exclude_newer(mut self, exclude_newer: &str) -> Self {
178 self.extra_env
179 .push((EnvVars::UV_EXCLUDE_NEWER.into(), exclude_newer.into()));
180 self
181 }
182
183 #[must_use]
185 pub fn with_http_timeout(mut self, http_timeout: &str) -> Self {
186 self.extra_env
187 .push((EnvVars::UV_HTTP_TIMEOUT.into(), http_timeout.into()));
188 self
189 }
190
191 #[must_use]
193 pub fn with_concurrent_installs(mut self, concurrent_installs: &str) -> Self {
194 self.extra_env.push((
195 EnvVars::UV_CONCURRENT_INSTALLS.into(),
196 concurrent_installs.into(),
197 ));
198 self
199 }
200
201 #[must_use]
206 pub fn with_filtered_counts(mut self) -> Self {
207 for verb in &[
208 "Resolved",
209 "Prepared",
210 "Installed",
211 "Uninstalled",
212 "Checked",
213 ] {
214 self.filters.push((
215 format!("{verb} \\d+ packages?"),
216 format!("{verb} [N] packages"),
217 ));
218 }
219 self.with_filtered_file_counts()
220 }
221
222 #[must_use]
224 pub fn with_filtered_file_counts(mut self) -> Self {
225 self.filters.push((
226 "Removed \\d+ files?".to_string(),
227 "Removed [N] files".to_string(),
228 ));
229 self
230 }
231
232 #[must_use]
234 pub fn with_filtered_sizes(mut self) -> Self {
235 self.filters.push((
236 r"(\s|\()(\d+\.)?\d+(([KMGT]i)?B)".to_string(),
237 "$1[SIZE]$3".to_string(),
238 ));
239 self
240 }
241
242 #[must_use]
244 pub fn with_filtered_sizes_and_units(mut self) -> Self {
245 self.filters.push((
246 r"(\s|\()(\d+\.)?\d+([KMGT]i)?B".to_string(),
247 "$1[SIZE]".to_string(),
248 ));
249 self
250 }
251
252 #[must_use]
254 pub fn with_filtered_cache_size(mut self) -> Self {
255 self.filters
257 .push((r"(?m)^\d+\n".to_string(), "[SIZE]\n".to_string()));
258 self.filters.push((
260 r"(?m)^\d+(\.\d+)?( ?[KMGT]i?B)\n".to_string(),
261 "[SIZE]$2\n".to_string(),
262 ));
263 self
264 }
265
266 #[must_use]
268 pub fn with_filtered_centralized_environment_hashes(mut self) -> Self {
269 self.filters.push((
270 r"`([\w.\[\]-]+)-[a-f0-9]{16}`".to_string(),
271 "`$1-[HASH]`".to_string(),
272 ));
273 self
274 }
275
276 #[must_use]
278 pub fn with_filtered_missing_file_error(mut self) -> Self {
279 self.filters.push((
282 r"[^:\n]* \(os error 2\)".to_string(),
283 " [OS ERROR 2]".to_string(),
284 ));
285 self.filters.push((
289 r"[^:\n]* \(os error 3\)".to_string(),
290 " [OS ERROR 2]".to_string(),
291 ));
292 self
293 }
294
295 #[must_use]
298 pub fn with_filtered_exe_suffix(mut self) -> Self {
299 self.filters
300 .push((regex::escape(env::consts::EXE_SUFFIX), String::new()));
301 self
302 }
303
304 #[must_use]
306 pub fn with_filtered_python_sources(mut self) -> Self {
307 self.filters.push((
308 "virtual environments, managed installations, or search path".to_string(),
309 "[PYTHON SOURCES]".to_string(),
310 ));
311 self.filters.push((
312 "virtual environments, managed installations, search path, or registry".to_string(),
313 "[PYTHON SOURCES]".to_string(),
314 ));
315 self.filters.push((
316 "virtual environments, search path, or registry".to_string(),
317 "[PYTHON SOURCES]".to_string(),
318 ));
319 self.filters.push((
320 "virtual environments, registry, or search path".to_string(),
321 "[PYTHON SOURCES]".to_string(),
322 ));
323 self.filters.push((
324 "virtual environments or search path".to_string(),
325 "[PYTHON SOURCES]".to_string(),
326 ));
327 self.filters.push((
328 "managed installations or search path".to_string(),
329 "[PYTHON SOURCES]".to_string(),
330 ));
331 self.filters.push((
332 "managed installations, search path, or registry".to_string(),
333 "[PYTHON SOURCES]".to_string(),
334 ));
335 self.filters.push((
336 "search path or registry".to_string(),
337 "[PYTHON SOURCES]".to_string(),
338 ));
339 self.filters.push((
340 "registry or search path".to_string(),
341 "[PYTHON SOURCES]".to_string(),
342 ));
343 self.filters
344 .push(("search path".to_string(), "[PYTHON SOURCES]".to_string()));
345 self
346 }
347
348 #[must_use]
351 pub fn with_filtered_python_names(mut self) -> Self {
352 for name in ["python", "pypy"] {
353 let suffix = if cfg!(windows) {
356 let exe_suffix = regex::escape(env::consts::EXE_SUFFIX);
360 format!(r"(\d\.\d+|\d)?{exe_suffix}")
361 } else {
362 if name == "python" {
364 r"(\d\.\d+|\d)?(t|d|td)?".to_string()
366 } else {
367 r"(\d\.\d+|\d)(t|d|td)?".to_string()
369 }
370 };
371
372 self.filters.push((
373 format!(r"[\\/]{name}{suffix}"),
376 format!("/[{}]", name.to_uppercase()),
377 ));
378 }
379
380 self
381 }
382
383 #[must_use]
386 pub fn with_filtered_virtualenv_bin(mut self) -> Self {
387 self.filters.push((
388 format!(
389 r"[\\/]{}[\\/]",
390 venv_bin_path(PathBuf::new()).to_string_lossy()
391 ),
392 "/[BIN]/".to_string(),
393 ));
394 self.filters.push((
395 format!(r"[\\/]{}", venv_bin_path(PathBuf::new()).to_string_lossy()),
396 "/[BIN]".to_string(),
397 ));
398 self
399 }
400
401 #[must_use]
405 pub fn with_filtered_python_install_bin(mut self) -> Self {
406 let suffix = if cfg!(windows) {
409 let exe_suffix = regex::escape(env::consts::EXE_SUFFIX);
410 format!(r"(\d\.\d+|\d)?{exe_suffix}")
412 } else {
413 r"\d\.\d+|\d".to_string()
415 };
416
417 if cfg!(unix) {
418 self.filters.push((
419 format!(r"[\\/]bin/python({suffix})"),
420 "/[INSTALL-BIN]/python$1".to_string(),
421 ));
422 self.filters.push((
423 format!(r"[\\/]bin/pypy({suffix})"),
424 "/[INSTALL-BIN]/pypy$1".to_string(),
425 ));
426 } else {
427 self.filters.push((
428 format!(r"[\\/]python({suffix})"),
429 "/[INSTALL-BIN]/python$1".to_string(),
430 ));
431 self.filters.push((
432 format!(r"[\\/]pypy({suffix})"),
433 "/[INSTALL-BIN]/pypy$1".to_string(),
434 ));
435 }
436 self
437 }
438
439 #[must_use]
444 pub fn with_pyvenv_cfg_filters(mut self) -> Self {
445 let added_filters = [
446 (r"home = .+".to_string(), "home = [PYTHON_HOME]".to_string()),
447 (
448 r"uv = \d+\.\d+\.\d+(-(alpha|beta|rc)\.\d+)?(\+\d+)?".to_string(),
449 "uv = [UV_VERSION]".to_string(),
450 ),
451 ];
452 for filter in added_filters {
453 self.filters.insert(0, filter);
454 }
455 self
456 }
457
458 #[must_use]
461 pub fn with_filtered_python_symlinks(mut self) -> Self {
462 for (version, executable) in &self.python_versions {
463 if fs_err::symlink_metadata(executable).unwrap().is_symlink() {
464 self.filters.extend(
465 Self::path_patterns(executable.read_link().unwrap())
466 .into_iter()
467 .map(|pattern| (format! {" -> {pattern}"}, String::new())),
468 );
469 }
470 self.filters.push((
472 regex::escape(&format!(" -> [PYTHON-{version}]")),
473 String::new(),
474 ));
475 }
476 self
477 }
478
479 #[must_use]
481 pub fn with_filtered_path(mut self, path: &Path, name: &str) -> Self {
482 for pattern in Self::path_patterns(path)
486 .into_iter()
487 .map(|pattern| (pattern, format!("[{name}]/")))
488 {
489 self.filters.insert(0, pattern);
490 }
491 self
492 }
493
494 #[inline]
502 #[must_use]
503 pub fn with_filtered_link_mode_warning(mut self) -> Self {
504 let pattern = "warning: Failed to hardlink files; .*\n.*\n.*\n";
505 self.filters.push((pattern.to_string(), String::new()));
506 self
507 }
508
509 #[inline]
511 #[must_use]
512 pub fn with_filtered_not_executable(mut self) -> Self {
513 let pattern = if cfg!(unix) {
514 r"Permission denied \(os error 13\)"
515 } else {
516 r"\%1 is not a valid Win32 application. \(os error 193\)"
517 };
518 self.filters
519 .push((pattern.to_string(), "[PERMISSION DENIED]".to_string()));
520 self
521 }
522
523 #[must_use]
525 pub fn with_filtered_python_keys(mut self) -> Self {
526 let platform_re = r"(?x)
528 ( # We capture the group before the platform
529 (?:cpython|pypy|graalpy)# Python implementation
530 -
531 \d+\.\d+ # Major and minor version
532 (?: # The patch version is handled separately
533 \.
534 (?:
535 \[X\] # A previously filtered patch version [X]
536 | # OR
537 \[LATEST\] # A previously filtered latest patch version [LATEST]
538 | # OR
539 \d+ # An actual patch version
540 )
541 )? # (we allow the patch version to be missing entirely, e.g., in a request)
542 (?:(?:a|b|rc)[0-9]+)? # Pre-release version component, e.g., `a6` or `rc2`
543 (?:[td])? # A short variant, such as `t` (for freethreaded) or `d` (for debug)
544 (?:(\+[a-z]+)+)? # A long variant, such as `+freethreaded` or `+freethreaded+debug`
545 )
546 -
547 [a-z0-9]+ # Operating system (e.g., 'macos')
548 -
549 [a-z0-9_]+ # Architecture (e.g., 'aarch64')
550 -
551 [a-z]+ # Libc (e.g., 'none')
552";
553 self.filters
554 .push((platform_re.to_string(), "$1-[PLATFORM]".to_string()));
555 self
556 }
557
558 #[must_use]
560 pub fn with_filtered_latest_python_versions(mut self) -> Self {
561 for (minor, patch) in [
564 ("3.15", LATEST_PYTHON_3_15.strip_prefix("3.15.").unwrap()),
565 ("3.14", LATEST_PYTHON_3_14.strip_prefix("3.14.").unwrap()),
566 ("3.13", LATEST_PYTHON_3_13.strip_prefix("3.13.").unwrap()),
567 ("3.12", LATEST_PYTHON_3_12.strip_prefix("3.12.").unwrap()),
568 ("3.11", LATEST_PYTHON_3_11.strip_prefix("3.11.").unwrap()),
569 ("3.10", LATEST_PYTHON_3_10.strip_prefix("3.10.").unwrap()),
570 ] {
571 let pattern = format!(r"(\b){minor}\.{patch}(\b)");
573 let replacement = format!("${{1}}{minor}.[LATEST]${{2}}");
574 self.filters.push((pattern, replacement));
575 }
576 self
577 }
578
579 #[must_use]
581 #[cfg(windows)]
582 pub fn with_filtered_windows_temp_dir(mut self) -> Self {
583 let pattern = regex::escape(
584 &self
585 .temp_dir
586 .simplified_display()
587 .to_string()
588 .replace('/', "\\"),
589 );
590 self.filters.push((pattern, "[TEMP_DIR]".to_string()));
591 self
592 }
593
594 #[must_use]
596 pub fn with_filtered_compiled_file_count(mut self) -> Self {
597 self.filters.push((
598 r"compiled \d+ files".to_string(),
599 "compiled [COUNT] files".to_string(),
600 ));
601 self
602 }
603
604 #[must_use]
606 pub fn with_filtered_current_version(mut self) -> Self {
607 self.filters.push((
608 regex::escape(&format!("v{}", env!("CARGO_PKG_VERSION"))),
609 "v[CURRENT_VERSION]".to_string(),
610 ));
611 self
612 }
613
614 #[must_use]
616 pub fn with_cyclonedx_filters(mut self) -> Self {
617 self.filters.push((
618 r"urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}".to_string(),
619 "[SERIAL_NUMBER]".to_string(),
620 ));
621 self.filters.push((
622 r#""timestamp": "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]+Z""#
623 .to_string(),
624 r#""timestamp": "[TIMESTAMP]""#.to_string(),
625 ));
626 self.filters.push((
627 r#""name": "uv",\s*"version": "\d+\.\d+\.\d+(-(alpha|beta|rc)\.\d+)?(\+\d+)?""#
628 .to_string(),
629 r#""name": "uv",
630 "version": "[VERSION]""#
631 .to_string(),
632 ));
633 self
634 }
635
636 #[must_use]
638 pub fn with_collapsed_whitespace(mut self) -> Self {
639 self.filters.push((r"[ \t]+".to_string(), " ".to_string()));
640 self
641 }
642
643 #[must_use]
645 pub fn with_python_download_cache(mut self) -> Self {
646 self.extra_env.push((
647 EnvVars::UV_PYTHON_CACHE_DIR.into(),
648 env::var_os(EnvVars::UV_PYTHON_CACHE_DIR).unwrap_or_else(|| {
650 uv_cache::Cache::from_settings(false, None)
651 .unwrap()
652 .bucket(CacheBucket::Python)
653 .into()
654 }),
655 ));
656 self
657 }
658
659 #[must_use]
660 pub fn with_empty_python_install_mirror(mut self) -> Self {
661 self.extra_env.push((
662 EnvVars::UV_PYTHON_INSTALL_MIRROR.into(),
663 String::new().into(),
664 ));
665 self
666 }
667
668 #[must_use]
670 pub fn with_managed_python_dirs(mut self) -> Self {
671 let managed = self.temp_dir.join("managed");
672
673 self.extra_env.push((
674 EnvVars::UV_PYTHON_BIN_DIR.into(),
675 self.bin_dir.as_os_str().to_owned(),
676 ));
677 self.extra_env
678 .push((EnvVars::UV_PYTHON_INSTALL_DIR.into(), managed.into()));
679 self.extra_env
680 .push((EnvVars::UV_PYTHON_DOWNLOADS.into(), "automatic".into()));
681
682 self
683 }
684
685 #[must_use]
686 pub fn with_versions_as_managed(mut self, versions: &[&str]) -> Self {
687 self.extra_env.push((
688 EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED.into(),
689 versions.iter().join(" ").into(),
690 ));
691
692 self
693 }
694
695 #[must_use]
697 pub fn with_filter(mut self, filter: (impl Into<String>, impl Into<String>)) -> Self {
698 self.filters.push((filter.0.into(), filter.1.into()));
699 self
700 }
701
702 #[must_use]
704 pub fn with_unset_git_credential_helper(self) -> Self {
705 let git_config = self.home_dir.child(".gitconfig");
706 git_config
707 .write_str(indoc! {r"
708 [credential]
709 helper =
710 "})
711 .expect("Failed to unset git credential helper");
712
713 self
714 }
715
716 #[must_use]
718 #[cfg(windows)]
719 pub fn clear_filters(mut self) -> Self {
720 self.filters.clear();
721 self
722 }
723
724 pub fn with_cache_on_cow_fs(self) -> anyhow::Result<Option<Self>> {
729 let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_COW_FS).ok() else {
730 return Ok(None);
731 };
732 self.with_cache_on_fs(&dir, "COW_FS").map(Some)
733 }
734
735 pub fn with_cache_on_alt_fs(self) -> anyhow::Result<Option<Self>> {
740 let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_ALT_FS).ok() else {
741 return Ok(None);
742 };
743 self.with_cache_on_fs(&dir, "ALT_FS").map(Some)
744 }
745
746 pub fn with_cache_on_lowlinks_fs(self) -> anyhow::Result<Option<Self>> {
751 let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_LOWLINKS_FS).ok() else {
752 return Ok(None);
753 };
754 self.with_cache_on_fs(&dir, "LOWLINKS_FS").map(Some)
755 }
756
757 pub fn with_cache_on_nocow_fs(self) -> anyhow::Result<Option<Self>> {
762 let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_NOCOW_FS).ok() else {
763 return Ok(None);
764 };
765 self.with_cache_on_fs(&dir, "NOCOW_FS").map(Some)
766 }
767
768 pub fn with_working_dir_on_cow_fs(self) -> anyhow::Result<Option<Self>> {
775 let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_COW_FS).ok() else {
776 return Ok(None);
777 };
778 self.with_working_dir_on_fs(&dir, "COW_FS").map(Some)
779 }
780
781 pub fn with_working_dir_on_nocow_fs(self) -> anyhow::Result<Option<Self>> {
788 let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_NOCOW_FS).ok() else {
789 return Ok(None);
790 };
791 self.with_working_dir_on_fs(&dir, "NOCOW_FS").map(Some)
792 }
793
794 fn with_cache_on_fs(mut self, dir: &str, name: &str) -> anyhow::Result<Self> {
795 fs_err::create_dir_all(dir)?;
796 let tmp = tempfile::TempDir::new_in(dir)?;
797 self.cache_dir = ChildPath::new(tmp.path()).child("cache");
798 fs_err::create_dir_all(&self.cache_dir)?;
799 let replacement = format!("[{name}]/[CACHE_DIR]/");
800 for pattern in Self::path_patterns(&self.cache_dir) {
801 self.filters.insert(0, (pattern, replacement.clone()));
802 }
803 self._extra_tempdirs.push(tmp);
804 Ok(self)
805 }
806
807 fn with_working_dir_on_fs(mut self, dir: &str, name: &str) -> anyhow::Result<Self> {
808 fs_err::create_dir_all(dir)?;
809 let tmp = tempfile::TempDir::new_in(dir)?;
810 self.temp_dir = ChildPath::new(tmp.path()).child("temp");
811 fs_err::create_dir_all(&self.temp_dir)?;
812 let canonical_temp_dir = self.temp_dir.canonicalize()?;
815 self.venv = ChildPath::new(canonical_temp_dir.join(".venv"));
816 let temp_replacement = format!("[{name}]/[TEMP_DIR]/");
817 self.filters.extend(
818 Self::path_patterns(&self.temp_dir)
819 .into_iter()
820 .map(|pattern| (pattern, temp_replacement.clone())),
821 );
822 let venv_replacement = format!("[{name}]/[VENV]/");
823 self.filters.extend(
824 Self::path_patterns(&self.venv)
825 .into_iter()
826 .map(|pattern| (pattern, venv_replacement.clone())),
827 );
828 self._extra_tempdirs.push(tmp);
829 Ok(self)
830 }
831
832 pub fn test_bucket_dir() -> PathBuf {
841 std::env::temp_dir()
842 .simple_canonicalize()
843 .expect("failed to canonicalize temp dir")
844 .join("uv")
845 .join("tests")
846 }
847
848 pub fn new_with_versions_and_bin(python_versions: &[&str], uv_bin: PathBuf) -> Self {
855 let bucket = Self::test_bucket_dir();
856 fs_err::create_dir_all(&bucket).expect("Failed to create test bucket");
857
858 let root = tempfile::TempDir::new_in(bucket).expect("Failed to create test root directory");
859
860 fs_err::create_dir_all(root.path().join(".git"))
863 .expect("Failed to create `.git` placeholder in test root directory");
864
865 let temp_dir = ChildPath::new(root.path()).child("temp");
866 fs_err::create_dir_all(&temp_dir).expect("Failed to create test working directory");
867
868 let cache_dir = ChildPath::new(root.path()).child("cache");
869 fs_err::create_dir_all(&cache_dir).expect("Failed to create test cache directory");
870
871 let python_dir = ChildPath::new(root.path()).child("python");
872 fs_err::create_dir_all(&python_dir).expect("Failed to create test Python directory");
873
874 let bin_dir = ChildPath::new(root.path()).child("bin");
875 fs_err::create_dir_all(&bin_dir).expect("Failed to create test bin directory");
876
877 if cfg!(not(feature = "git")) {
879 Self::disallow_git_cli(&bin_dir).expect("Failed to setup disallowed `git` command");
880 }
881
882 let home_dir = ChildPath::new(root.path()).child("home");
883 fs_err::create_dir_all(&home_dir).expect("Failed to create test home directory");
884
885 let user_config_dir = if cfg!(windows) {
886 ChildPath::new(home_dir.path())
887 } else {
888 ChildPath::new(home_dir.path()).child(".config")
889 };
890
891 let canonical_temp_dir = temp_dir.canonicalize().unwrap();
893 let venv = ChildPath::new(canonical_temp_dir.join(".venv"));
894
895 let python_version = python_versions
896 .first()
897 .map(|version| PythonVersion::from_str(version).unwrap());
898
899 let site_packages = python_version
900 .as_ref()
901 .map(|version| site_packages_path(&venv, &format!("python{version}")));
902
903 let workspace_root = Path::new(&env::var(EnvVars::CARGO_MANIFEST_DIR).unwrap())
906 .parent()
907 .expect("CARGO_MANIFEST_DIR should be nested in workspace")
908 .parent()
909 .expect("CARGO_MANIFEST_DIR should be doubly nested in workspace")
910 .to_path_buf();
911
912 let download_list = ManagedPythonDownloadList::new_only_embedded().unwrap();
913
914 let python_versions: Vec<_> = python_versions
915 .iter()
916 .map(|version| PythonVersion::from_str(version).unwrap())
917 .zip(
918 python_installations_for_versions(&temp_dir, python_versions, &download_list)
919 .expect("Failed to find test Python versions"),
920 )
921 .collect();
922
923 if cfg!(unix) {
926 for (version, executable) in &python_versions {
927 let parent = python_dir.child(version.to_string());
928 parent.create_dir_all().unwrap();
929 parent.child("python3").symlink_to_file(executable).unwrap();
930 }
931 }
932
933 let mut filters = Vec::new();
934
935 filters.extend(
936 Self::path_patterns(&uv_bin)
937 .into_iter()
938 .map(|pattern| (pattern, "[UV]".to_string())),
939 );
940
941 if cfg!(windows) {
943 filters.push((" --link-mode <LINK_MODE>".to_string(), String::new()));
944 filters.push((r#"link-mode = "copy"\n"#.to_string(), String::new()));
945 filters.push((r"exit code: ".to_string(), "exit status: ".to_string()));
947 }
948
949 for (version, executable) in &python_versions {
950 filters.extend(
952 Self::path_patterns(executable)
953 .into_iter()
954 .map(|pattern| (pattern, format!("[PYTHON-{version}]"))),
955 );
956
957 filters.extend(
959 Self::path_patterns(python_dir.join(version.to_string()))
960 .into_iter()
961 .map(|pattern| {
962 (
963 format!("{pattern}[a-zA-Z0-9]*"),
964 format!("[PYTHON-{version}]"),
965 )
966 }),
967 );
968
969 if version.patch().is_none() {
972 filters.push((
973 format!(r"({})\.\d+", regex::escape(version.to_string().as_str())),
974 "$1.[X]".to_string(),
975 ));
976 }
977 }
978
979 filters.extend(
980 Self::path_patterns(&bin_dir)
981 .into_iter()
982 .map(|pattern| (pattern, "[BIN]/".to_string())),
983 );
984 filters.extend(
985 Self::path_patterns(&cache_dir)
986 .into_iter()
987 .map(|pattern| (pattern, "[CACHE_DIR]/".to_string())),
988 );
989 if let Some(ref site_packages) = site_packages {
990 filters.extend(
991 Self::path_patterns(site_packages)
992 .into_iter()
993 .map(|pattern| (pattern, "[SITE_PACKAGES]/".to_string())),
994 );
995 }
996 filters.extend(
997 Self::path_patterns(&venv)
998 .into_iter()
999 .map(|pattern| (pattern, "[VENV]/".to_string())),
1000 );
1001
1002 if let Some(site_packages) = site_packages {
1004 filters.push((
1005 Self::path_pattern(
1006 site_packages
1007 .strip_prefix(&canonical_temp_dir)
1008 .expect("The test site-packages directory is always in the tempdir"),
1009 ),
1010 "[SITE_PACKAGES]/".to_string(),
1011 ));
1012 }
1013
1014 filters.push((
1016 r"[\\/]lib[\\/]python\d+\.\d+[\\/]".to_string(),
1017 "/[PYTHON-LIB]/".to_string(),
1018 ));
1019 filters.push((r"[\\/]Lib[\\/]".to_string(), "/[PYTHON-LIB]/".to_string()));
1020
1021 filters.extend(
1022 Self::path_patterns(&temp_dir)
1023 .into_iter()
1024 .map(|pattern| (pattern, "[TEMP_DIR]/".to_string())),
1025 );
1026 filters.extend(
1027 Self::path_patterns(&python_dir)
1028 .into_iter()
1029 .map(|pattern| (pattern, "[PYTHON_DIR]/".to_string())),
1030 );
1031 let mut uv_user_config_dir = PathBuf::from(user_config_dir.path());
1032 uv_user_config_dir.push("uv");
1033 filters.extend(
1034 Self::path_patterns(&uv_user_config_dir)
1035 .into_iter()
1036 .map(|pattern| (pattern, "[UV_USER_CONFIG_DIR]/".to_string())),
1037 );
1038 filters.extend(
1039 Self::path_patterns(&user_config_dir)
1040 .into_iter()
1041 .map(|pattern| (pattern, "[USER_CONFIG_DIR]/".to_string())),
1042 );
1043 filters.extend(
1044 Self::path_patterns(&home_dir)
1045 .into_iter()
1046 .map(|pattern| (pattern, "[HOME]/".to_string())),
1047 );
1048 filters.extend(
1049 Self::path_patterns(&workspace_root)
1050 .into_iter()
1051 .map(|pattern| (pattern, "[WORKSPACE]/".to_string())),
1052 );
1053
1054 filters.push((
1056 r"Activate with: (.*)\\Scripts\\activate".to_string(),
1057 "Activate with: source $1/[BIN]/activate".to_string(),
1058 ));
1059 filters.push((
1060 r"Activate with: Scripts\\activate".to_string(),
1061 "Activate with: source [BIN]/activate".to_string(),
1062 ));
1063 filters.push((
1064 r"Activate with: source (.*/|)bin/activate(?:\.\w+)?".to_string(),
1065 "Activate with: source $1[BIN]/activate".to_string(),
1066 ));
1067
1068 filters.push((
1071 r#"(\\|/)\.tmp[^\\/\s"'`]*"#.to_string(),
1072 "/[TMP]".to_string(),
1073 ));
1074
1075 filters.push((r"file:///".to_string(), "file://".to_string()));
1077
1078 filters.push((r"\\\\\?\\".to_string(), String::new()));
1080
1081 filters.push((r"127\.0\.0\.1:\d*".to_string(), "[LOCALHOST]".to_string()));
1083 filters.push((
1085 format!(
1086 r#"requires = \["uv_build>={},<[0-9.]+"\]"#,
1087 uv_version::version()
1088 ),
1089 r#"requires = ["uv_build>=[CURRENT_VERSION],<[NEXT_BREAKING]"]"#.to_string(),
1090 ));
1091 filters.push((
1093 r"environments-v(\d+)[\\/]([\w.\[\]-]+)-[a-f0-9]{16}".to_string(),
1094 "environments-v$1/$2-[HASH]".to_string(),
1095 ));
1096 filters.push((
1098 r"archive-v(\d+)[\\/][A-Za-z0-9\-\_]+".to_string(),
1099 "archive-v$1/[HASH]".to_string(),
1100 ));
1101
1102 Self {
1103 root: ChildPath::new(root.path()),
1104 temp_dir,
1105 cache_dir,
1106 python_dir,
1107 home_dir,
1108 user_config_dir,
1109 bin_dir,
1110 venv,
1111 workspace_root,
1112 python_version,
1113 python_versions,
1114 uv_bin,
1115 filters,
1116 extra_env: vec![],
1117 _root: root,
1118 _extra_tempdirs: vec![],
1119 }
1120 }
1121
1122 pub fn command(&self) -> Command {
1124 let mut command = self.new_command();
1125 self.add_shared_options(&mut command, true);
1126 command
1127 }
1128
1129 pub fn disallow_git_cli(bin_dir: &Path) -> std::io::Result<()> {
1130 let contents = r"#!/bin/sh
1131 echo 'error: `git` operations are not allowed — are you missing a cfg for the `git` feature?' >&2
1132 exit 127";
1133 let git = bin_dir.join(format!("git{}", env::consts::EXE_SUFFIX));
1134 fs_err::write(&git, contents)?;
1135
1136 #[cfg(unix)]
1137 {
1138 use std::os::unix::fs::PermissionsExt;
1139 let mut perms = fs_err::metadata(&git)?.permissions();
1140 perms.set_mode(0o755);
1141 fs_err::set_permissions(&git, perms)?;
1142 }
1143
1144 Ok(())
1145 }
1146
1147 #[must_use]
1152 pub fn with_git_lfs_config(mut self) -> Self {
1153 let git_lfs_config = self.root.child(".gitconfig");
1154 git_lfs_config
1155 .write_str(indoc! {r#"
1156 [filter "lfs"]
1157 clean = git-lfs clean -- %f
1158 smudge = git-lfs smudge -- %f
1159 process = git-lfs filter-process
1160 required = true
1161 "#})
1162 .expect("Failed to setup `git-lfs` filters");
1163
1164 self.extra_env.push((
1167 EnvVars::GIT_CONFIG_GLOBAL.into(),
1168 git_lfs_config.as_os_str().into(),
1169 ));
1170 self
1171 }
1172
1173 pub fn add_shared_options(&self, command: &mut Command, activate_venv: bool) {
1185 self.add_shared_args(command);
1186 self.add_shared_env(command, activate_venv);
1187 }
1188
1189 fn add_shared_args(&self, command: &mut Command) {
1191 command.arg("--cache-dir").arg(self.cache_dir.path());
1192 }
1193
1194 pub fn add_shared_env(&self, command: &mut Command, activate_venv: bool) {
1196 let path = env::join_paths(std::iter::once(self.bin_dir.to_path_buf()).chain(
1198 env::split_paths(&env::var(EnvVars::PATH).unwrap_or_default()),
1199 ))
1200 .unwrap();
1201
1202 if cfg!(not(windows)) {
1205 command.env(EnvVars::SHELL, "bash");
1206 }
1207
1208 command
1209 .env_remove(EnvVars::VIRTUAL_ENV)
1211 .env(EnvVars::UV_NO_WRAP, "1")
1213 .env(EnvVars::UV_NO_SYSTEM_CONFIG, "1")
1215 .env(EnvVars::COLUMNS, "100")
1218 .env(EnvVars::PATH, path)
1219 .env(EnvVars::HOME, self.home_dir.as_os_str())
1220 .env(EnvVars::APPDATA, self.home_dir.as_os_str())
1221 .env(EnvVars::USERPROFILE, self.home_dir.as_os_str())
1222 .env(
1223 EnvVars::XDG_CONFIG_DIRS,
1224 self.home_dir.join("config").as_os_str(),
1225 )
1226 .env(
1227 EnvVars::XDG_DATA_HOME,
1228 self.home_dir.join("data").as_os_str(),
1229 )
1230 .env(EnvVars::UV_NO_SYSTEM_CONFIG, "1")
1231 .env(EnvVars::UV_PYTHON_INSTALL_DIR, "")
1232 .env(EnvVars::UV_PYTHON_DOWNLOADS, "never")
1234 .env(EnvVars::UV_PYTHON_SEARCH_PATH, self.python_path())
1235 .env(EnvVars::UV_EXCLUDE_NEWER, TEST_TIMESTAMP)
1236 .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, TEST_TIMESTAMP)
1237 .env(EnvVars::UV_TEST_AVAILABLE_VERSION_CUTOFF, TEST_TIMESTAMP)
1238 .env(EnvVars::UV_PYTHON_NO_REGISTRY, "1")
1241 .env(EnvVars::UV_PYTHON_INSTALL_REGISTRY, "0")
1242 .env(EnvVars::UV_TEST_NO_CLI_PROGRESS, "1")
1245 .env(EnvVars::GIT_CEILING_DIRECTORIES, self.root.path())
1259 .current_dir(self.temp_dir.path());
1260
1261 for (key, value) in &self.extra_env {
1262 command.env(key, value);
1263 }
1264
1265 if activate_venv {
1266 command.env(EnvVars::VIRTUAL_ENV, self.venv.as_os_str());
1267 }
1268
1269 if cfg!(unix) {
1270 command.env(EnvVars::LC_ALL, "C");
1272 }
1273 }
1274
1275 pub fn pip_compile(&self) -> Command {
1277 let mut command = self.new_command();
1278 command.arg("pip").arg("compile");
1279 self.add_shared_options(&mut command, true);
1280 command
1281 }
1282
1283 pub fn pip_sync(&self) -> Command {
1285 let mut command = self.new_command();
1286 command.arg("pip").arg("sync");
1287 self.add_shared_options(&mut command, true);
1288 command
1289 }
1290
1291 pub fn pip_show(&self) -> Command {
1292 let mut command = self.new_command();
1293 command.arg("pip").arg("show");
1294 self.add_shared_options(&mut command, true);
1295 command
1296 }
1297
1298 pub fn pip_freeze(&self) -> Command {
1300 let mut command = self.new_command();
1301 command.arg("pip").arg("freeze");
1302 self.add_shared_options(&mut command, true);
1303 command
1304 }
1305
1306 pub fn pip_check(&self) -> Command {
1308 let mut command = self.new_command();
1309 command.arg("pip").arg("check");
1310 self.add_shared_options(&mut command, true);
1311 command
1312 }
1313
1314 pub fn pip_list(&self) -> Command {
1315 let mut command = self.new_command();
1316 command.arg("pip").arg("list");
1317 self.add_shared_options(&mut command, true);
1318 command
1319 }
1320
1321 pub fn venv(&self) -> Command {
1323 let mut command = self.new_command();
1324 command.arg("venv");
1325 self.add_shared_options(&mut command, false);
1326 command
1327 }
1328
1329 pub fn pip_install(&self) -> Command {
1331 let mut command = self.new_command();
1332 command.arg("pip").arg("install");
1333 self.add_shared_options(&mut command, true);
1334 command
1335 }
1336
1337 pub fn pip_uninstall(&self) -> Command {
1339 let mut command = self.new_command();
1340 command.arg("pip").arg("uninstall");
1341 self.add_shared_options(&mut command, true);
1342 command
1343 }
1344
1345 pub fn pip_tree(&self) -> Command {
1347 let mut command = self.new_command();
1348 command.arg("pip").arg("tree");
1349 self.add_shared_options(&mut command, true);
1350 command
1351 }
1352
1353 pub fn pip_debug(&self) -> Command {
1355 let mut command = self.new_command();
1356 command.arg("pip").arg("debug");
1357 self.add_shared_options(&mut command, true);
1358 command
1359 }
1360
1361 pub fn help(&self) -> Command {
1363 let mut command = self.new_command();
1364 command.arg("help");
1365 self.add_shared_env(&mut command, false);
1366 command
1367 }
1368
1369 pub fn init(&self) -> Command {
1372 let mut command = self.new_command();
1373 command.arg("init");
1374 self.add_shared_options(&mut command, false);
1375 command
1376 }
1377
1378 pub fn sync(&self) -> Command {
1380 let mut command = self.new_command();
1381 command.arg("sync");
1382 self.add_shared_options(&mut command, false);
1383 command
1384 }
1385
1386 pub fn lock(&self) -> Command {
1388 let mut command = self.new_command();
1389 command.arg("lock");
1390 self.add_shared_options(&mut command, false);
1391 command
1392 }
1393
1394 pub fn upgrade(&self) -> Command {
1396 let mut command = self.new_command();
1397 command.arg("upgrade");
1398 self.add_shared_options(&mut command, false);
1399 command
1400 }
1401
1402 pub fn audit(&self) -> Command {
1404 let mut command = self.new_command();
1405 command.arg("audit");
1406 self.add_shared_options(&mut command, false);
1407 command
1408 }
1409
1410 pub fn workspace_metadata(&self) -> Command {
1412 let mut command = self.new_command();
1413 command.arg("workspace").arg("metadata");
1414 self.add_shared_options(&mut command, false);
1415 command
1416 }
1417
1418 pub fn workspace_dir(&self) -> Command {
1420 let mut command = self.new_command();
1421 command.arg("workspace").arg("dir");
1422 self.add_shared_options(&mut command, false);
1423 command
1424 }
1425
1426 pub fn workspace_list(&self) -> Command {
1428 let mut command = self.new_command();
1429 command.arg("workspace").arg("list");
1430 self.add_shared_options(&mut command, false);
1431 command
1432 }
1433
1434 pub fn export(&self) -> Command {
1436 let mut command = self.new_command();
1437 command.arg("export");
1438 self.add_shared_options(&mut command, false);
1439 command
1440 }
1441
1442 pub fn format(&self) -> Command {
1444 let mut command = self.new_command();
1445 command.arg("format");
1446 self.add_shared_options(&mut command, false);
1447 command.env(EnvVars::UV_EXCLUDE_NEWER, "2026-02-15T00:00:00Z");
1449 command
1450 }
1451
1452 pub fn check(&self) -> Command {
1454 let mut command = self.new_command();
1455 command.arg("check");
1456 self.add_shared_options(&mut command, false);
1457 command.env(EnvVars::UV_EXCLUDE_NEWER, "2026-02-15T00:00:00Z");
1459 command
1460 }
1461
1462 pub fn build(&self) -> Command {
1464 let mut command = self.new_command();
1465 command.arg("build");
1466 self.add_shared_options(&mut command, false);
1467 command
1468 }
1469
1470 pub fn version(&self) -> Command {
1471 let mut command = self.new_command();
1472 command.arg("version");
1473 self.add_shared_options(&mut command, false);
1474 command
1475 }
1476
1477 pub fn self_version(&self) -> Command {
1478 let mut command = self.new_command();
1479 command.arg("self").arg("version");
1480 self.add_shared_options(&mut command, false);
1481 command
1482 }
1483
1484 pub fn self_update(&self) -> Command {
1485 let mut command = self.new_command();
1486 command.arg("self").arg("update");
1487 self.add_shared_options(&mut command, false);
1488 command
1489 }
1490
1491 pub fn publish(&self) -> Command {
1493 let mut command = self.new_command();
1494 command.arg("publish");
1495 self.add_shared_options(&mut command, false);
1496 command
1497 }
1498
1499 pub fn python_find(&self) -> Command {
1501 let mut command = self.new_command();
1502 command
1503 .arg("python")
1504 .arg("find")
1505 .env(EnvVars::UV_PREVIEW, "1")
1506 .env(EnvVars::UV_PYTHON_INSTALL_DIR, "");
1507 self.add_shared_options(&mut command, false);
1508 command
1509 }
1510
1511 pub fn python_list(&self) -> Command {
1513 let mut command = self.new_command();
1514 command
1515 .arg("python")
1516 .arg("list")
1517 .env(EnvVars::UV_PYTHON_INSTALL_DIR, "");
1518 self.add_shared_options(&mut command, false);
1519 command
1520 }
1521
1522 pub fn python_install(&self) -> Command {
1524 let mut command = self.new_command();
1525 command.arg("python").arg("install");
1526 self.add_shared_options(&mut command, true);
1527 command
1528 }
1529
1530 pub fn python_uninstall(&self) -> Command {
1532 let mut command = self.new_command();
1533 command.arg("python").arg("uninstall");
1534 self.add_shared_options(&mut command, true);
1535 command
1536 }
1537
1538 pub fn python_upgrade(&self) -> Command {
1540 let mut command = self.new_command();
1541 command.arg("python").arg("upgrade");
1542 self.add_shared_options(&mut command, true);
1543 command
1544 }
1545
1546 pub fn python_pin(&self) -> Command {
1548 let mut command = self.new_command();
1549 command.arg("python").arg("pin");
1550 self.add_shared_options(&mut command, true);
1551 command
1552 }
1553
1554 pub fn python_dir(&self) -> Command {
1556 let mut command = self.new_command();
1557 command.arg("python").arg("dir");
1558 self.add_shared_options(&mut command, true);
1559 command
1560 }
1561
1562 pub fn run(&self) -> Command {
1564 let mut command = self.new_command();
1565 command.arg("run").env(EnvVars::UV_SHOW_RESOLUTION, "1");
1566 self.add_shared_options(&mut command, true);
1567 command
1568 }
1569
1570 pub fn tool_run(&self) -> Command {
1572 let mut command = self.new_command();
1573 command
1574 .arg("tool")
1575 .arg("run")
1576 .env(EnvVars::UV_SHOW_RESOLUTION, "1");
1577 self.add_shared_options(&mut command, false);
1578 command
1579 }
1580
1581 pub fn tool_upgrade(&self) -> Command {
1583 let mut command = self.new_command();
1584 command.arg("tool").arg("upgrade");
1585 self.add_shared_options(&mut command, false);
1586 command
1587 }
1588
1589 pub fn tool_install(&self) -> Command {
1591 let mut command = self.new_command();
1592 command.arg("tool").arg("install");
1593 self.add_shared_options(&mut command, false);
1594 command
1595 }
1596
1597 pub fn tool_list(&self) -> Command {
1599 let mut command = self.new_command();
1600 command.arg("tool").arg("list");
1601 self.add_shared_options(&mut command, false);
1602 command
1603 }
1604
1605 pub fn tool_audit(&self) -> Command {
1607 let mut command = self.new_command();
1608 command.arg("tool").arg("audit");
1609 self.add_shared_options(&mut command, false);
1610 command
1611 }
1612
1613 pub fn tool_dir(&self) -> Command {
1615 let mut command = self.new_command();
1616 command.arg("tool").arg("dir");
1617 self.add_shared_options(&mut command, false);
1618 command
1619 }
1620
1621 pub fn tool_uninstall(&self) -> Command {
1623 let mut command = self.new_command();
1624 command.arg("tool").arg("uninstall");
1625 self.add_shared_options(&mut command, false);
1626 command
1627 }
1628
1629 pub fn add(&self) -> Command {
1631 let mut command = self.new_command();
1632 command.arg("add");
1633 self.add_shared_options(&mut command, false);
1634 command
1635 }
1636
1637 pub fn remove(&self) -> Command {
1639 let mut command = self.new_command();
1640 command.arg("remove");
1641 self.add_shared_options(&mut command, false);
1642 command
1643 }
1644
1645 pub fn tree(&self) -> Command {
1647 let mut command = self.new_command();
1648 command.arg("tree");
1649 self.add_shared_options(&mut command, false);
1650 command
1651 }
1652
1653 pub fn clean(&self) -> Command {
1655 let mut command = self.new_command();
1656 command.arg("cache").arg("clean");
1657 self.add_shared_options(&mut command, false);
1658 command
1659 }
1660
1661 pub fn prune(&self) -> Command {
1663 let mut command = self.new_command();
1664 command.arg("cache").arg("prune");
1665 self.add_shared_options(&mut command, false);
1666 command
1667 }
1668
1669 pub fn cache_size(&self) -> Command {
1671 let mut command = self.new_command();
1672 command.arg("cache").arg("size");
1673 self.add_shared_options(&mut command, false);
1674 command
1675 }
1676
1677 pub fn build_backend(&self) -> Command {
1681 let mut command = self.new_command();
1682 command.arg("build-backend");
1683 self.add_shared_options(&mut command, false);
1684 command
1685 }
1686
1687 pub fn interpreter(&self) -> PathBuf {
1691 let venv = &self.venv;
1692 if cfg!(unix) {
1693 venv.join("bin").join("python")
1694 } else if cfg!(windows) {
1695 venv.join("Scripts").join("python.exe")
1696 } else {
1697 unimplemented!("Only Windows and Unix are supported")
1698 }
1699 }
1700
1701 pub fn python_command(&self) -> Command {
1702 let mut interpreter = self.interpreter();
1703
1704 if !interpreter.exists() {
1706 interpreter.clone_from(
1707 &self
1708 .python_versions
1709 .first()
1710 .expect("At least one Python version is required")
1711 .1,
1712 );
1713 }
1714
1715 let mut command = Self::new_command_with(&interpreter);
1716 command
1717 .arg("-B")
1720 .env(EnvVars::PYTHONUTF8, "1");
1722
1723 self.add_shared_env(&mut command, false);
1724
1725 command
1726 }
1727
1728 pub fn auth_login(&self) -> Command {
1730 let mut command = self.new_command();
1731 command.arg("auth").arg("login");
1732 self.add_shared_options(&mut command, false);
1733 command
1734 }
1735
1736 pub fn auth_logout(&self) -> Command {
1738 let mut command = self.new_command();
1739 command.arg("auth").arg("logout");
1740 self.add_shared_options(&mut command, false);
1741 command
1742 }
1743
1744 pub fn auth_helper(&self) -> Command {
1746 let mut command = self.new_command();
1747 command.arg("auth").arg("helper");
1748 self.add_shared_options(&mut command, false);
1749 command
1750 }
1751
1752 pub fn auth_token(&self) -> Command {
1754 let mut command = self.new_command();
1755 command.arg("auth").arg("token");
1756 self.add_shared_options(&mut command, false);
1757 command
1758 }
1759
1760 #[must_use]
1764 pub fn with_real_home(mut self) -> Self {
1765 if let Some(home) = env::var_os(EnvVars::HOME) {
1766 self.extra_env
1767 .push((EnvVars::HOME.to_string().into(), home));
1768 }
1769 self.extra_env.push((
1772 EnvVars::XDG_CONFIG_HOME.into(),
1773 self.user_config_dir.as_os_str().into(),
1774 ));
1775 self
1776 }
1777
1778 pub fn assert_command(&self, command: &str) -> Assert {
1780 self.python_command()
1781 .arg("-c")
1782 .arg(command)
1783 .current_dir(&self.temp_dir)
1784 .assert()
1785 }
1786
1787 pub fn assert_file(&self, file: impl AsRef<Path>) -> Assert {
1789 self.python_command()
1790 .arg(file.as_ref())
1791 .current_dir(&self.temp_dir)
1792 .assert()
1793 }
1794
1795 pub fn assert_installed(&self, package: &'static str, version: &'static str) {
1797 self.assert_command(
1798 format!("import {package} as package; print(package.__version__, end='')").as_str(),
1799 )
1800 .success()
1801 .stdout(version);
1802 }
1803
1804 pub fn assert_not_installed(&self, package: &'static str) {
1806 self.assert_command(format!("import {package}").as_str())
1807 .failure();
1808 }
1809
1810 pub fn path_patterns(path: impl AsRef<Path>) -> Vec<String> {
1812 let mut patterns = Vec::new();
1813
1814 if path.as_ref().exists() {
1816 patterns.push(Self::path_pattern(
1817 path.as_ref()
1818 .canonicalize()
1819 .expect("Failed to create canonical path"),
1820 ));
1821 }
1822
1823 patterns.push(Self::path_pattern(path));
1825
1826 patterns
1827 }
1828
1829 fn path_pattern(path: impl AsRef<Path>) -> String {
1831 format!(
1832 r"{}\\?/?",
1834 regex::escape(&path.as_ref().simplified_display().to_string())
1835 .replace(r"\\", r"(\\|\/)")
1838 )
1839 }
1840
1841 pub fn python_path(&self) -> OsString {
1842 if cfg!(unix) {
1843 env::join_paths(
1845 self.python_versions
1846 .iter()
1847 .map(|(version, _)| self.python_dir.join(version.to_string())),
1848 )
1849 .unwrap()
1850 } else {
1851 env::join_paths(
1853 self.python_versions
1854 .iter()
1855 .map(|(_, executable)| executable.parent().unwrap().to_path_buf()),
1856 )
1857 .unwrap()
1858 }
1859 }
1860
1861 pub fn filters(&self) -> Vec<(&str, &str)> {
1863 self.filters
1866 .iter()
1867 .map(|(p, r)| (p.as_str(), r.as_str()))
1868 .chain(INSTA_FILTERS.iter().copied())
1869 .collect()
1870 }
1871
1872 #[cfg(windows)]
1874 pub fn filters_without_standard_filters(&self) -> Vec<(&str, &str)> {
1875 self.filters
1876 .iter()
1877 .map(|(p, r)| (p.as_str(), r.as_str()))
1878 .collect()
1879 }
1880
1881 pub fn python_kind(&self) -> &'static str {
1883 "python"
1884 }
1885
1886 pub fn site_packages(&self) -> PathBuf {
1888 site_packages_path(
1889 &self.venv,
1890 &format!(
1891 "{}{}",
1892 self.python_kind(),
1893 self.python_version.as_ref().expect(
1894 "A Python version must be provided to retrieve the test site packages path"
1895 )
1896 ),
1897 )
1898 }
1899
1900 pub fn reset_venv(&self) {
1902 self.create_venv();
1903 }
1904
1905 fn create_venv(&self) {
1907 let executable = get_python(
1908 self.python_version
1909 .as_ref()
1910 .expect("A Python version must be provided to create a test virtual environment"),
1911 );
1912 create_venv_from_executable(&self.venv, &self.cache_dir, &executable, &self.uv_bin);
1913 }
1914
1915 pub fn copy_ecosystem_project(&self, name: &str) {
1926 let project_dir = PathBuf::from(format!("../../test/ecosystem/{name}"));
1927 self.temp_dir.copy_from(project_dir, &["**/*"]).unwrap();
1928 if let Err(err) = fs_err::remove_file(self.temp_dir.join("uv.lock")) {
1930 assert_eq!(
1931 err.kind(),
1932 io::ErrorKind::NotFound,
1933 "Failed to remove uv.lock: {err}"
1934 );
1935 }
1936 }
1937
1938 pub fn diff_lock(&self, change: impl Fn(&Self) -> Command) -> String {
1947 let lock_path = ChildPath::new(self.temp_dir.join("uv.lock"));
1948 let old_lock = fs_err::read_to_string(&lock_path).unwrap();
1949 let (snapshot, output) = run_and_format(
1950 change(self),
1951 self.filters(),
1952 "diff_lock",
1953 Some(WindowsFilters::Platform),
1954 None,
1955 );
1956 assert!(output.status.success(), "{snapshot}");
1957 let new_lock = fs_err::read_to_string(&lock_path).unwrap();
1958 diff_snapshot(&old_lock, &new_lock, 10)
1959 }
1960
1961 pub fn read(&self, file: impl AsRef<Path>) -> String {
1963 fs_err::read_to_string(self.temp_dir.join(&file))
1964 .unwrap_or_else(|_| panic!("Missing file: `{}`", file.user_display()))
1965 }
1966
1967 fn new_command(&self) -> Command {
1970 Self::new_command_with(&self.uv_bin)
1971 }
1972
1973 fn new_command_with(bin: &Path) -> Command {
1979 let mut command = Command::new(bin);
1980
1981 let passthrough = [
1982 EnvVars::PATH,
1984 EnvVars::RUST_LOG,
1986 EnvVars::RUST_BACKTRACE,
1987 EnvVars::SYSTEMDRIVE,
1989 EnvVars::RUST_MIN_STACK,
1991 EnvVars::UV_STACK_SIZE,
1992 EnvVars::ALL_PROXY,
1994 EnvVars::HTTPS_PROXY,
1995 EnvVars::HTTP_PROXY,
1996 EnvVars::NO_PROXY,
1997 EnvVars::SSL_CERT_DIR,
1998 EnvVars::SSL_CERT_FILE,
1999 EnvVars::UV_NATIVE_TLS,
2000 EnvVars::UV_SYSTEM_CERTS,
2001 ];
2002
2003 for env_var in EnvVars::all_names()
2004 .iter()
2005 .filter(|name| !passthrough.contains(name))
2006 {
2007 command.env_remove(env_var);
2008 }
2009
2010 command
2011 }
2012}
2013
2014pub fn diff_snapshot(old: &str, new: &str, context_radius: usize) -> String {
2017 let diff = similar::TextDiff::from_lines(old, new);
2018 let unified = diff
2019 .unified_diff()
2020 .context_radius(context_radius)
2021 .header("old", "new")
2022 .to_string();
2023 regex!(r"(?m)^\s+$").replace_all(&unified, "").into_owned()
2027}
2028
2029#[macro_export]
2033macro_rules! diff_uv_snapshot {
2034 ($filters:expr, $old:expr, $spawnable:expr, @$snapshot:literal) => {{
2035 let new = $crate::capture_uv_snapshot!($filters, $spawnable);
2036 let snapshot = $crate::diff_snapshot($old, &new, 3);
2037 let mut settings = ::insta::Settings::clone_current();
2038 let description = match settings.description() {
2040 Some(description) => format!("{description}\n\nUnfiltered diff:\n{snapshot}"),
2041 None => format!("Unfiltered diff:\n{snapshot}"),
2042 };
2043 settings.set_description(description);
2044 settings.add_filter(r"^--- old\n\+\+\+ new\n", "");
2045 settings.add_filter(r"(?m)^@@.*$", "...");
2046 settings.add_filter(r"\n$", "\n...\n");
2047 settings.bind(|| {
2048 ::insta::assert_snapshot!(snapshot, @$snapshot);
2049 });
2050 new
2051 }};
2052}
2053
2054#[macro_export]
2056macro_rules! capture_uv_snapshot {
2057 ($filters:expr, $spawnable:expr) => {{
2058 let (snapshot, _) = $crate::run_and_format_silent(
2060 $spawnable,
2061 &$filters,
2062 $crate::function_name!(),
2063 Some($crate::WindowsFilters::Platform),
2064 None,
2065 );
2066 snapshot
2067 }};
2068 ($filters:expr, $spawnable:expr, @$snapshot:literal) => {{
2069 let (snapshot, _) = $crate::run_and_format(
2070 $spawnable,
2071 &$filters,
2072 $crate::function_name!(),
2073 Some($crate::WindowsFilters::Platform),
2074 None,
2075 );
2076 ::insta::assert_snapshot!(snapshot, @$snapshot);
2077 snapshot
2078 }};
2079}
2080
2081pub fn site_packages_path(venv: &Path, python: &str) -> PathBuf {
2082 if cfg!(unix) {
2083 venv.join("lib").join(python).join("site-packages")
2084 } else if cfg!(windows) {
2085 venv.join("Lib").join("site-packages")
2086 } else {
2087 unimplemented!("Only Windows and Unix are supported")
2088 }
2089}
2090
2091pub fn venv_bin_path(venv: impl AsRef<Path>) -> PathBuf {
2092 if cfg!(unix) {
2093 venv.as_ref().join("bin")
2094 } else if cfg!(windows) {
2095 venv.as_ref().join("Scripts")
2096 } else {
2097 unimplemented!("Only Windows and Unix are supported")
2098 }
2099}
2100
2101fn get_python(version: &PythonVersion) -> PathBuf {
2103 ManagedPythonInstallations::from_settings(None)
2104 .map(|installed_pythons| {
2105 installed_pythons
2106 .find_version(version)
2107 .expect("Tests are run on a supported platform")
2108 .next()
2109 .as_ref()
2110 .map(|python| python.executable(false))
2111 })
2112 .unwrap_or_default()
2115 .unwrap_or(PathBuf::from(version.to_string()))
2116}
2117
2118fn create_venv_from_executable<P: AsRef<Path>>(
2120 path: P,
2121 cache_dir: &ChildPath,
2122 python: &Path,
2123 uv_bin: &Path,
2124) {
2125 TestContext::new_command_with(uv_bin)
2126 .arg("venv")
2127 .arg(path.as_ref().as_os_str())
2128 .arg("--clear")
2129 .arg("--cache-dir")
2130 .arg(cache_dir.path())
2131 .arg("--python")
2132 .arg(python)
2133 .current_dir(path.as_ref().parent().unwrap())
2134 .assert()
2135 .success();
2136 ChildPath::new(path.as_ref()).assert(predicate::path::is_dir());
2137}
2138
2139pub fn python_path_with_versions(
2143 temp_dir: &ChildPath,
2144 python_versions: &[&str],
2145) -> anyhow::Result<OsString> {
2146 let download_list = ManagedPythonDownloadList::new_only_embedded().unwrap();
2147 Ok(env::join_paths(
2148 python_installations_for_versions(temp_dir, python_versions, &download_list)?
2149 .into_iter()
2150 .map(|path| path.parent().unwrap().to_path_buf()),
2151 )?)
2152}
2153
2154fn python_installations_for_versions(
2158 temp_dir: &ChildPath,
2159 python_versions: &[&str],
2160 download_list: &ManagedPythonDownloadList,
2161) -> anyhow::Result<Vec<PathBuf>> {
2162 let cache = Cache::from_path(temp_dir.child("cache").to_path_buf())
2163 .init_no_wait()?
2164 .expect("No cache contention when setting up Python in tests");
2165 let _preview = uv_preview::test::with_features(&[]);
2166 let selected_pythons = python_versions
2167 .iter()
2168 .map(|python_version| {
2169 if let Ok(python) = PythonInstallation::find(
2170 &PythonRequest::parse(python_version),
2171 EnvironmentPreference::OnlySystem,
2172 PythonPreference::Managed,
2173 download_list,
2174 &cache,
2175 ) {
2176 python.into_interpreter().sys_executable().to_owned()
2177 } else {
2178 panic!("Could not find Python {python_version} for test\nTry `cargo run python install` first, or refer to CONTRIBUTING.md");
2179 }
2180 })
2181 .collect::<Vec<_>>();
2182
2183 assert!(
2184 python_versions.is_empty() || !selected_pythons.is_empty(),
2185 "Failed to fulfill requested test Python versions: {selected_pythons:?}"
2186 );
2187
2188 Ok(selected_pythons)
2189}
2190
2191#[derive(Debug, Copy, Clone)]
2192pub enum WindowsFilters {
2193 Platform,
2194 Universal,
2195}
2196
2197pub fn apply_filters<T: AsRef<str>>(mut snapshot: String, filters: impl AsRef<[(T, T)]>) -> String {
2199 for (matcher, replacement) in filters.as_ref() {
2200 let re = Regex::new(matcher.as_ref()).expect("Do you need to regex::escape your filter?");
2202 if re.is_match(&snapshot) {
2203 snapshot = re.replace_all(&snapshot, replacement.as_ref()).to_string();
2204 }
2205 }
2206 snapshot
2207}
2208
2209#[expect(clippy::print_stderr)]
2213pub fn run_and_format<T: AsRef<str>>(
2214 command: impl BorrowMut<Command>,
2215 filters: impl AsRef<[(T, T)]>,
2216 function_name: &str,
2217 windows_filters: Option<WindowsFilters>,
2218 input: Option<&str>,
2219) -> (String, Output) {
2220 let (snapshot, output) =
2221 run_and_format_silent(command, filters, function_name, windows_filters, input);
2222 eprintln!("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Unfiltered output ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
2223 eprintln!(
2224 "----- stdout -----\n{}\n----- stderr -----\n{}",
2225 String::from_utf8_lossy(&output.stdout),
2226 String::from_utf8_lossy(&output.stderr),
2227 );
2228 eprintln!("────────────────────────────────────────────────────────────────────────────────\n");
2229 (snapshot, output)
2230}
2231
2232#[doc(hidden)]
2234pub fn run_and_format_silent<T: AsRef<str>>(
2235 mut command: impl BorrowMut<Command>,
2236 filters: impl AsRef<[(T, T)]>,
2237 function_name: &str,
2238 windows_filters: Option<WindowsFilters>,
2239 input: Option<&str>,
2240) -> (String, Output) {
2241 let program = command
2242 .borrow_mut()
2243 .get_program()
2244 .to_string_lossy()
2245 .to_string();
2246
2247 if let Ok(root) = env::var(EnvVars::TRACING_DURATIONS_TEST_ROOT) {
2249 #[expect(clippy::assertions_on_constants)]
2251 {
2252 assert!(
2253 cfg!(feature = "tracing-durations-export"),
2254 "You need to enable the tracing-durations-export feature to use `TRACING_DURATIONS_TEST_ROOT`"
2255 );
2256 }
2257 command.borrow_mut().env(
2258 EnvVars::TRACING_DURATIONS_FILE,
2259 Path::new(&root).join(function_name).with_extension("jsonl"),
2260 );
2261 }
2262
2263 let output = if let Some(input) = input {
2264 let mut child = command
2265 .borrow_mut()
2266 .stdin(Stdio::piped())
2267 .stdout(Stdio::piped())
2268 .stderr(Stdio::piped())
2269 .spawn()
2270 .unwrap_or_else(|err| panic!("Failed to spawn {program}: {err}"));
2271 child
2272 .stdin
2273 .as_mut()
2274 .expect("Failed to open stdin")
2275 .write_all(input.as_bytes())
2276 .expect("Failed to write to stdin");
2277
2278 child
2279 .wait_with_output()
2280 .unwrap_or_else(|err| panic!("Failed to read output from {program}: {err}"))
2281 } else {
2282 command
2283 .borrow_mut()
2284 .output()
2285 .unwrap_or_else(|err| panic!("Failed to spawn {program}: {err}"))
2286 };
2287
2288 let mut snapshot = format!(
2289 "exit_code: {} ({})\n",
2290 output.status.code().unwrap_or(!0),
2291 if output.status.success() {
2292 "success"
2293 } else {
2294 "failure"
2295 },
2296 );
2297 if !output.stdout.is_empty() {
2298 snapshot.push_str("----- stdout -----\n");
2299 snapshot.push_str(&String::from_utf8_lossy(&output.stdout));
2300 }
2301 if !output.stderr.is_empty() {
2302 if !output.stdout.is_empty() {
2303 snapshot.push('\n');
2304 }
2305 snapshot.push_str("----- stderr -----\n");
2306 snapshot.push_str(&String::from_utf8_lossy(&output.stderr));
2307 }
2308 let mut snapshot = apply_filters(snapshot, filters);
2309
2310 if cfg!(windows) {
2315 if let Some(windows_filters) = windows_filters {
2316 let windows_only_deps = [
2318 (r"( ?[-+~] ?)?colorama==\d+(\.\d+)+( [\\]\n\s+--hash=.*)?\n(\s+# via .*\n)?"),
2319 (r"( ?[-+~] ?)?colorama==\d+(\.\d+)+(\s+[-+~]?\s+# via .*)?\n"),
2320 (r"( ?[-+~] ?)?tzdata==\d+(\.\d+)+( [\\]\n\s+--hash=.*)?\n(\s+# via .*\n)?"),
2321 (r"( ?[-+~] ?)?tzdata==\d+(\.\d+)+(\s+[-+~]?\s+# via .*)?\n"),
2322 ];
2323 let mut removed_packages = 0;
2324 for windows_only_dep in windows_only_deps {
2325 let re = Regex::new(windows_only_dep).unwrap();
2327 if re.is_match(&snapshot) {
2328 snapshot = re.replace(&snapshot, "").to_string();
2329 removed_packages += 1;
2330 }
2331 }
2332 if removed_packages > 0 {
2333 for i in 1..20 {
2334 for verb in match windows_filters {
2335 WindowsFilters::Platform => [
2336 "Resolved",
2337 "Prepared",
2338 "Installed",
2339 "Checked",
2340 "Uninstalled",
2341 ]
2342 .iter(),
2343 WindowsFilters::Universal => {
2344 ["Prepared", "Installed", "Checked", "Uninstalled"].iter()
2345 }
2346 } {
2347 snapshot = snapshot.replace(
2348 &format!("{verb} {} packages", i + removed_packages),
2349 &format!("{verb} {} package{}", i, if i > 1 { "s" } else { "" }),
2350 );
2351 }
2352 }
2353 }
2354 }
2355 }
2356
2357 (snapshot, output)
2358}
2359
2360pub fn copy_dir_ignore(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> anyhow::Result<()> {
2362 for entry in ignore::Walk::new(&src) {
2363 let entry = entry?;
2364 let relative = entry.path().strip_prefix(&src)?;
2365 let ty = entry.file_type().unwrap();
2366 if ty.is_dir() {
2367 fs_err::create_dir(dst.as_ref().join(relative))?;
2368 } else {
2369 fs_err::copy(entry.path(), dst.as_ref().join(relative))?;
2370 }
2371 }
2372 Ok(())
2373}
2374
2375pub fn make_project(dir: &Path, name: &str, body: &str) -> anyhow::Result<()> {
2377 let pyproject_toml = formatdoc! {r#"
2378 [project]
2379 name = "{name}"
2380 version = "0.1.0"
2381 requires-python = ">=3.11,<3.13"
2382 {body}
2383
2384 [build-system]
2385 requires = ["uv_build>=0.9.0,<10000"]
2386 build-backend = "uv_build"
2387 "#
2388 };
2389 fs_err::create_dir_all(dir)?;
2390 fs_err::write(dir.join("pyproject.toml"), pyproject_toml)?;
2391 fs_err::create_dir_all(dir.join("src").join(name))?;
2392 fs_err::write(dir.join("src").join(name).join("__init__.py"), "")?;
2393 Ok(())
2394}
2395
2396pub const READ_ONLY_GITHUB_TOKEN: &[&str] = &[
2398 "Z2l0aHViCg==",
2399 "cGF0Cg==",
2400 "MTFBQlVDUjZBMERMUTQ3aVphN3hPdV9qQmhTMkZUeHZ4ZE13OHczakxuZndsV2ZlZjc2cE53eHBWS2tiRUFwdnpmUk8zV0dDSUhicDFsT01aago=",
2401];
2402
2403#[cfg(not(windows))]
2405pub const READ_ONLY_GITHUB_TOKEN_2: &[&str] = &[
2406 "Z2l0aHViCg==",
2407 "cGF0Cg==",
2408 "MTFBQlVDUjZBMDJTOFYwMTM4YmQ0bV9uTXpueWhxZDBrcllROTQ5SERTeTI0dENKZ2lmdzIybDFSR2s1SE04QW8xTUVYQ1I0Q1YxYUdPRGpvZQo=",
2409];
2410
2411pub const READ_ONLY_GITHUB_SSH_DEPLOY_KEY: &str = "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUFNd0FBQUF0emMyZ3RaVwpReU5UVXhPUUFBQUNBeTF1SnNZK1JXcWp1NkdIY3Z6a3AwS21yWDEwdmo3RUZqTkpNTkRqSGZPZ0FBQUpqWUpwVnAyQ2FWCmFRQUFBQXR6YzJndFpXUXlOVFV4T1FBQUFDQXkxdUpzWStSV3FqdTZHSGN2emtwMEttclgxMHZqN0VGak5KTU5EakhmT2cKQUFBRUMwbzBnd1BxbGl6TFBJOEFXWDVaS2dVZHJyQ2ptMDhIQm9FenB4VDg3MXBqTFc0bXhqNUZhcU83b1lkeS9PU25RcQphdGZYUytQc1FXTTBrdzBPTWQ4NkFBQUFFR3R2Ym5OMGFVQmhjM1J5WVd3dWMyZ0JBZ01FQlE9PQotLS0tLUVORCBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0K";
2412
2413pub fn decode_token(content: &[&str]) -> String {
2416 content
2417 .iter()
2418 .map(|part| base64.decode(part).unwrap())
2419 .map(|decoded| {
2420 std::str::from_utf8(decoded.as_slice())
2421 .unwrap()
2422 .trim_end()
2423 .to_string()
2424 })
2425 .join("_")
2426}
2427
2428#[tokio::main(flavor = "current_thread")]
2431pub async fn download_to_disk(url: &str, path: &Path) {
2432 let trusted_hosts: Vec<_> = env::var(EnvVars::UV_INSECURE_HOST)
2433 .unwrap_or_default()
2434 .split(' ')
2435 .map(|h| uv_configuration::TrustedHost::from_str(h).unwrap())
2436 .collect();
2437
2438 let client = uv_client::BaseClientBuilder::default()
2439 .allow_insecure_host(trusted_hosts)
2440 .build()
2441 .expect("failed to build base client");
2442 let url = url.parse().unwrap();
2443 let response = client
2444 .for_host(&url)
2445 .get(reqwest::Url::from(url))
2446 .send()
2447 .await
2448 .unwrap();
2449
2450 let mut file = fs_err::tokio::File::create(path).await.unwrap();
2451 let mut stream = response.bytes_stream();
2452 while let Some(chunk) = stream.next().await {
2453 file.write_all(&chunk.unwrap()).await.unwrap();
2454 }
2455 file.sync_all().await.unwrap();
2456}
2457
2458#[cfg(unix)]
2463pub struct ReadOnlyDirectoryGuard {
2464 path: PathBuf,
2465 original_mode: u32,
2466}
2467
2468#[cfg(unix)]
2469impl ReadOnlyDirectoryGuard {
2470 pub fn new(path: impl Into<PathBuf>) -> std::io::Result<Self> {
2473 use std::os::unix::fs::PermissionsExt;
2474 let path = path.into();
2475 let metadata = fs_err::metadata(&path)?;
2476 let original_mode = metadata.permissions().mode();
2477 let readonly_mode = original_mode & !0o222;
2479 fs_err::set_permissions(&path, std::fs::Permissions::from_mode(readonly_mode))?;
2480 Ok(Self {
2481 path,
2482 original_mode,
2483 })
2484 }
2485}
2486
2487#[cfg(unix)]
2488impl Drop for ReadOnlyDirectoryGuard {
2489 fn drop(&mut self) {
2490 use std::os::unix::fs::PermissionsExt;
2491 let _ = fs_err::set_permissions(
2492 &self.path,
2493 std::fs::Permissions::from_mode(self.original_mode),
2494 );
2495 }
2496}
2497
2498#[doc(hidden)]
2502#[macro_export]
2503macro_rules! function_name {
2504 () => {{
2505 fn f() {}
2506 fn type_name_of_val<T>(_: T) -> &'static str {
2507 std::any::type_name::<T>()
2508 }
2509 let mut name = type_name_of_val(f).strip_suffix("::f").unwrap_or("");
2510 while let Some(rest) = name.strip_suffix("::{{closure}}") {
2511 name = rest;
2512 }
2513 name
2514 }};
2515}
2516
2517#[macro_export]
2522macro_rules! uv_snapshot {
2523 ($spawnable:expr, @$snapshot:literal) => {{
2524 uv_snapshot!($crate::INSTA_FILTERS.to_vec(), $spawnable, @$snapshot)
2525 }};
2526 ($filters:expr, $spawnable:expr, @$snapshot:literal) => {{
2527 let (snapshot, output) = $crate::run_and_format($spawnable, &$filters, $crate::function_name!(), Some($crate::WindowsFilters::Platform), None);
2529 ::insta::assert_snapshot!(snapshot, @$snapshot);
2530 output
2531 }};
2532 ($filters:expr, $spawnable:expr, input=$input:expr, @$snapshot:literal) => {{
2533 let (snapshot, output) = $crate::run_and_format($spawnable, &$filters, $crate::function_name!(), Some($crate::WindowsFilters::Platform), Some($input));
2535 ::insta::assert_snapshot!(snapshot, @$snapshot);
2536 output
2537 }};
2538 ($filters:expr, windows_filters=false, $spawnable:expr, @$snapshot:literal) => {{
2539 let (snapshot, output) = $crate::run_and_format($spawnable, &$filters, $crate::function_name!(), None, None);
2541 ::insta::assert_snapshot!(snapshot, @$snapshot);
2542 output
2543 }};
2544 ($filters:expr, universal_windows_filters=true, $spawnable:expr, @$snapshot:literal) => {{
2545 let (snapshot, output) = $crate::run_and_format($spawnable, &$filters, $crate::function_name!(), Some($crate::WindowsFilters::Universal), None);
2547 ::insta::assert_snapshot!(snapshot, @$snapshot);
2548 output
2549 }};
2550}