Skip to main content

uv_python_discovery/
lib.rs

1//! Discover and select Python installations for projects, scripts, and commands.
2use thiserror::Error;
3use uv_python_interpreter::PythonEnvironmentError;
4use uv_python_types::PythonRequest;
5
6#[cfg(test)]
7use uv_static::EnvVars;
8
9#[cfg(all(test, unix))]
10use crate::discovery::find_python_installations;
11pub use discovery::{Error as DiscoveryError, PythonNotFound, find_all_python_installations};
12pub use installation::{PythonInstallation, find_environment};
13pub use version_files::{
14    ConfigDiscovery, DiscoveryOptions as VersionFileDiscoveryOptions,
15    FilePreference as VersionFilePreference, PYTHON_VERSION_FILENAME, PYTHON_VERSIONS_FILENAME,
16    PythonVersionFile,
17};
18
19mod discovery;
20mod installation;
21#[cfg(windows)]
22mod microsoft_store;
23mod project;
24mod reporter;
25mod script;
26mod selection_error;
27mod version_files;
28mod virtualenv_discovery;
29#[cfg(windows)]
30mod windows_registry;
31
32pub use project::{
33    CompatibleProjectPython, ProjectPythonRequest, ProjectPythonRequirement, PythonRequestSource,
34    PythonRequirementConflicts, PythonRequirementSource, find_requires_python,
35    format_requires_python_sources,
36};
37pub use reporter::{PythonDownloadReporter, report_interpreter};
38pub use script::{
39    EnvironmentIncompatibilityError, EnvironmentKind, ScriptInterpreter,
40    check_environment_compatibility, init_script_python_requirement,
41};
42pub use selection_error::PythonSelectionError;
43
44#[cfg(not(test))]
45fn current_dir() -> Result<std::path::PathBuf, std::io::Error> {
46    std::env::current_dir()
47}
48
49#[cfg(test)]
50fn current_dir() -> Result<std::path::PathBuf, std::io::Error> {
51    std::env::var_os(EnvVars::PWD)
52        .map(std::path::PathBuf::from)
53        .map(Ok)
54        .unwrap_or(std::env::current_dir())
55}
56
57#[derive(Debug, Error)]
58pub enum Error {
59    #[error(transparent)]
60    Io(#[from] std::io::Error),
61
62    #[error(transparent)]
63    VirtualEnv(#[from] uv_python_interpreter::VirtualEnvError),
64
65    #[error(transparent)]
66    Query(#[from] uv_python_interpreter::InterpreterError),
67
68    #[error(transparent)]
69    Discovery(#[from] discovery::Error),
70
71    #[error(transparent)]
72    ManagedPython(#[from] uv_python_managed::Error),
73
74    #[error(transparent)]
75    Download(#[from] uv_python_managed::downloads::Error),
76
77    #[error(transparent)]
78    ClientBuild(#[from] uv_client::ClientBuildError),
79
80    // TODO(zanieb) We might want to ensure this is always wrapped in another type
81    #[error(transparent)]
82    KeyError(#[from] uv_python_types::PythonInstallationKeyError),
83
84    #[error("{}", .0)]
85    MissingPython(PythonNotFound, Option<Box<MissingPythonHint>>),
86
87    #[error(transparent)]
88    MissingEnvironment(#[from] uv_python_interpreter::EnvironmentNotFound),
89
90    #[error(transparent)]
91    InvalidEnvironment(#[from] uv_python_interpreter::InvalidEnvironment),
92
93    #[error(transparent)]
94    RetryParsing(#[from] uv_client::RetryParsingError),
95}
96
97/// The reason a managed Python download could not be used.
98#[derive(Debug)]
99pub enum MissingPythonHint {
100    /// uv's embedded download metadata may be stale.
101    RequiresUpdate,
102    /// Downloads are set to `manual`.
103    DownloadsManual(PythonRequest),
104    /// Downloads are set to `never`.
105    DownloadsNever(PythonRequest),
106    /// Python preference is set to `only-system`.
107    PreferenceOnlySystem(PythonRequest),
108    /// uv is in offline mode.
109    Offline(PythonRequest),
110}
111
112impl MissingPythonHint {
113    fn for_request(request: &PythonRequest) -> String {
114        match request {
115            PythonRequest::Default | PythonRequest::Any => String::new(),
116            _ => format!(" for {request}"),
117        }
118    }
119}
120
121impl std::fmt::Display for MissingPythonHint {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        match self {
124            Self::RequiresUpdate => {
125                write!(
126                    f,
127                    "uv embeds available Python downloads and may require an update to install new versions. Consider retrying on a newer version of uv."
128                )
129            }
130            Self::DownloadsManual(request) => {
131                write!(
132                    f,
133                    "A managed Python download is available{}, but Python downloads are set to 'manual', use `uv python install {}` to install the required version",
134                    Self::for_request(request),
135                    request.to_canonical_string(),
136                )
137            }
138            Self::DownloadsNever(request) => {
139                write!(
140                    f,
141                    "A managed Python download is available{}, but Python downloads are set to 'never'",
142                    Self::for_request(request),
143                )
144            }
145            Self::PreferenceOnlySystem(request) => {
146                write!(
147                    f,
148                    "A managed Python download is available{}, but the Python preference is set to 'only system'",
149                    Self::for_request(request),
150                )
151            }
152            Self::Offline(request) => {
153                write!(
154                    f,
155                    "A managed Python download is available{}, but uv is set to offline mode",
156                    Self::for_request(request),
157                )
158            }
159        }
160    }
161}
162
163impl uv_errors::Hinted for Error {
164    fn hints(&self) -> uv_errors::Hints<'_> {
165        match self {
166            Self::MissingPython(_, Some(hint)) => uv_errors::Hints::from(hint.to_string()),
167            Self::Discovery(err) => err.hints(),
168            _ => uv_errors::Hints::none(),
169        }
170    }
171}
172
173impl Error {
174    fn with_hint(self, hint: MissingPythonHint) -> Self {
175        match self {
176            Self::MissingPython(err, _) => Self::MissingPython(err, Some(Box::new(hint))),
177            _ => self,
178        }
179    }
180}
181
182impl From<PythonNotFound> for Error {
183    fn from(err: PythonNotFound) -> Self {
184        Self::MissingPython(err, None)
185    }
186}
187
188impl From<uv_python_types::PythonDownloadRequestError> for Error {
189    fn from(error: uv_python_types::PythonDownloadRequestError) -> Self {
190        Self::Download(error.into())
191    }
192}
193
194impl From<PythonEnvironmentError> for Error {
195    fn from(error: PythonEnvironmentError) -> Self {
196        match error {
197            PythonEnvironmentError::Io(error) => Self::Io(error),
198            PythonEnvironmentError::Query(error) => Self::Query(error),
199            PythonEnvironmentError::VirtualEnv(error) => Self::VirtualEnv(error),
200            PythonEnvironmentError::MissingEnvironment(error) => Self::MissingEnvironment(error),
201            PythonEnvironmentError::InvalidEnvironment(error) => Self::InvalidEnvironment(error),
202        }
203    }
204}
205
206// The mock interpreters are not valid on Windows so we don't have unit test coverage there
207// TODO(zanieb): We should write a mock interpreter script that works on Windows
208#[cfg(all(test, unix))]
209mod tests {
210    fn parse_request(value: &str) -> PythonRequest {
211        PythonRequest::parse_with_working_directory(
212            value,
213            &crate::current_dir().expect("The test working directory must be available"),
214        )
215    }
216
217    use std::assert_matches;
218    use std::{
219        env,
220        ffi::{OsStr, OsString},
221        fs::Permissions,
222        io,
223        os::unix::fs::PermissionsExt,
224        path::{Path, PathBuf},
225        str::FromStr,
226    };
227
228    use anyhow::Result;
229    use assert_fs::{TempDir, fixture::ChildPath, prelude::*};
230    use indoc::{formatdoc, indoc};
231    use temp_env::with_vars;
232    use test_log::test;
233    use uv_client::BaseClientBuilder;
234    use uv_preview::PreviewFeature;
235    use uv_state::{StateBucket, StateStore};
236    use uv_static::EnvVars;
237
238    use uv_cache::Cache;
239
240    use crate::PythonNotFound;
241    use crate::discovery;
242    use crate::discovery::find_best_python_installation;
243    use crate::discovery::find_python_installation;
244    use crate::find_all_python_installations;
245    use crate::find_python_installations;
246    use crate::installation::PythonInstallation;
247    use uv_python_interpreter::virtualenv_python_executable;
248    use uv_python_managed::ManagedPythonInstallations;
249    use uv_python_types::{
250        EnvironmentPreference, ImplementationName, PythonArchitecture, PythonDownloadMirrors,
251        PythonDownloads, PythonPreference, PythonRequest, PythonSource, PythonVersion,
252    };
253
254    struct TestContext {
255        tempdir: TempDir,
256        cache: Cache,
257        installations: ManagedPythonInstallations,
258        search_path: Option<Vec<PathBuf>>,
259        workdir: ChildPath,
260    }
261
262    impl TestContext {
263        fn new() -> Result<Self> {
264            let tempdir = TempDir::new()?;
265            let workdir = tempdir.child("workdir");
266            workdir.create_dir_all()?;
267
268            Ok(Self {
269                tempdir,
270                cache: Cache::temp()?,
271                installations: ManagedPythonInstallations::from_settings(Some(
272                    StateStore::temp()?.bucket(StateBucket::ManagedPython),
273                ))?,
274                search_path: None,
275                workdir,
276            })
277        }
278
279        /// Clear the search path.
280        fn reset_search_path(&mut self) {
281            self.search_path = None;
282        }
283
284        /// Add a directory to the search path.
285        fn add_to_search_path(&mut self, path: PathBuf) {
286            match self.search_path.as_mut() {
287                Some(paths) => paths.push(path),
288                None => self.search_path = Some(vec![path]),
289            }
290        }
291
292        /// Create a new directory and add it to the search path.
293        fn new_search_path_directory(&mut self, name: impl AsRef<Path>) -> Result<ChildPath> {
294            let child = self.tempdir.child(name);
295            child.create_dir_all()?;
296            self.add_to_search_path(child.to_path_buf());
297            Ok(child)
298        }
299
300        fn run<F, R>(&self, closure: F) -> R
301        where
302            F: FnOnce() -> R,
303        {
304            self.run_with_vars(&[], closure)
305        }
306
307        fn run_with_vars<F, R>(&self, vars: &[(&str, Option<&OsStr>)], closure: F) -> R
308        where
309            F: FnOnce() -> R,
310        {
311            let path = self
312                .search_path
313                .as_ref()
314                .map(|paths| env::join_paths(paths).unwrap());
315
316            let mut run_vars: Vec<(&str, Option<&OsStr>)> = EnvVars::all_names()
317                .iter()
318                .copied()
319                .map(|name| (name, None))
320                .collect();
321            run_vars.extend([
322                // Keep discovery hermetic by disabling registry-based sources unless a test opts in.
323                (EnvVars::UV_PYTHON_NO_REGISTRY, Some(OsStr::new("1"))),
324                (EnvVars::PATH, path.as_deref()),
325                // Use the temporary python directory
326                (
327                    EnvVars::UV_PYTHON_INSTALL_DIR,
328                    Some(self.installations.root().as_os_str()),
329                ),
330                // Set a working directory
331                (EnvVars::PWD, Some(self.workdir.path().as_os_str())),
332            ]);
333            run_vars.extend(vars.iter().copied());
334            with_vars(&run_vars, closure)
335        }
336
337        fn run_with_vars_and_preview<F, R>(
338            &self,
339            vars: &[(&str, Option<&OsStr>)],
340            preview_features: &[PreviewFeature],
341            closure: F,
342        ) -> R
343        where
344            F: FnOnce() -> R,
345        {
346            let _preview = uv_preview::test::with_features(preview_features);
347            self.run_with_vars(vars, closure)
348        }
349
350        /// Create a fake Python interpreter executable which returns fixed metadata mocking our interpreter
351        /// query script output.
352        fn create_mock_interpreter(
353            path: &Path,
354            version: &PythonVersion,
355            implementation: ImplementationName,
356            system: bool,
357            free_threaded: bool,
358        ) -> Result<()> {
359            let json = indoc! {r##"
360                {
361                    "result": "success",
362                    "os": {
363                        "name": "manylinux",
364                        "major": 2,
365                        "minor": 38
366                    },
367                    "arch": "x86_64",
368                    "cpu_info": {"unavailable": "Mock interpreter has no CPU data"},
369                    "manylinux_compatible": true,
370                    "standalone": true,
371                    "markers": {
372                        "implementation_name": "{IMPLEMENTATION}",
373                        "implementation_version": "{FULL_VERSION}",
374                        "os_name": "posix",
375                        "platform_machine": "x86_64",
376                        "platform_python_implementation": "{IMPLEMENTATION}",
377                        "platform_release": "6.5.0-13-generic",
378                        "platform_system": "Linux",
379                        "platform_version": "#13-Ubuntu SMP PREEMPT_DYNAMIC Fri Nov  3 12:16:05 UTC 2023",
380                        "python_full_version": "{FULL_VERSION}",
381                        "python_version": "{VERSION}",
382                        "sys_platform": "linux"
383                    },
384                    "sys_base_exec_prefix": "/home/ferris/.pyenv/versions/{FULL_VERSION}",
385                    "sys_base_prefix": "/home/ferris/.pyenv/versions/{FULL_VERSION}",
386                    "sys_prefix": "{PREFIX}",
387                    "sys_executable": "{PATH}",
388                    "sys_path": [
389                        "/home/ferris/.pyenv/versions/{FULL_VERSION}/lib/python{VERSION}/lib/python{VERSION}",
390                        "/home/ferris/.pyenv/versions/{FULL_VERSION}/lib/python{VERSION}/site-packages"
391                    ],
392                    "site_packages": [
393                        "/home/ferris/.pyenv/versions/{FULL_VERSION}/lib/python{VERSION}/site-packages"
394                    ],
395                    "stdlib": "/home/ferris/.pyenv/versions/{FULL_VERSION}/lib/python{VERSION}",
396                    "extension_suffixes": [".cpython-{VERSION}-x86_64-linux-gnu.so", ".abi3.so", ".so"],
397                    "scheme": {
398                        "data": "/home/ferris/.pyenv/versions/{FULL_VERSION}",
399                        "include": "/home/ferris/.pyenv/versions/{FULL_VERSION}/include",
400                        "platlib": "/home/ferris/.pyenv/versions/{FULL_VERSION}/lib/python{VERSION}/site-packages",
401                        "purelib": "/home/ferris/.pyenv/versions/{FULL_VERSION}/lib/python{VERSION}/site-packages",
402                        "scripts": "/home/ferris/.pyenv/versions/{FULL_VERSION}/bin"
403                    },
404                    "virtualenv": {
405                        "data": "",
406                        "include": "include",
407                        "platlib": "lib/python{VERSION}/site-packages",
408                        "purelib": "lib/python{VERSION}/site-packages",
409                        "scripts": "bin"
410                    },
411                    "pointer_size": "64",
412                    "gil_disabled": {FREE_THREADED},
413                    "debug_enabled": false
414                }
415            "##};
416
417            let json = if system {
418                json.replace("{PREFIX}", "/home/ferris/.pyenv/versions/{FULL_VERSION}")
419            } else {
420                json.replace("{PREFIX}", "/home/ferris/projects/uv/.venv")
421            };
422
423            let json = json
424                .replace(
425                    "{PATH}",
426                    path.to_str().expect("Path can be represented as string"),
427                )
428                .replace("{FULL_VERSION}", &version.to_string())
429                .replace(
430                    "{VERSION}",
431                    &format!("{}.{}", version.major(), version.minor()),
432                )
433                .replace("{FREE_THREADED}", &free_threaded.to_string())
434                .replace("{IMPLEMENTATION}", implementation.long_name());
435
436            fs_err::create_dir_all(path.parent().unwrap())?;
437            fs_err::write(
438                path,
439                formatdoc! {r"
440                #!/bin/sh
441                echo '{json}'
442                "},
443            )?;
444
445            fs_err::set_permissions(path, std::os::unix::fs::PermissionsExt::from_mode(0o770))?;
446
447            Ok(())
448        }
449
450        fn create_mock_pyodide_interpreter(path: &Path, version: &PythonVersion) -> Result<()> {
451            let json = indoc! {r##"
452                {
453                    "result": "success",
454                    "os": {
455                        "name": "pyodide",
456                        "major": 2025,
457                        "minor": 0
458                    },
459                    "arch": "wasm32",
460                    "cpu_info": { "unsupported_architecture": "wasm32" },
461                    "manylinux_compatible": false,
462                    "standalone": false,
463                    "markers": {
464                        "implementation_name": "cpython",
465                        "implementation_version": "{FULL_VERSION}",
466                        "os_name": "posix",
467                        "platform_machine": "wasm32",
468                        "platform_python_implementation": "CPython",
469                        "platform_release": "4.0.9",
470                        "platform_system": "Emscripten",
471                        "platform_version": "#1",
472                        "python_full_version": "{FULL_VERSION}",
473                        "python_version": "{VERSION}",
474                        "sys_platform": "emscripten"
475                    },
476                    "sys_base_exec_prefix": "/",
477                    "sys_base_prefix": "/",
478                    "sys_prefix": "/",
479                    "sys_executable": "{PATH}",
480                    "sys_path": [
481                        "",
482                        "/lib/python313.zip",
483                        "/lib/python{VERSION}",
484                        "/lib/python{VERSION}/lib-dynload",
485                        "/lib/python{VERSION}/site-packages"
486                    ],
487                    "site_packages": [
488                        "/lib/python{VERSION}/site-packages"
489                    ],
490                    "stdlib": "//lib/python{VERSION}",
491                    "extension_suffixes": [".cpython-{VERSION}-wasm32-emscripten.so", ".so"],
492                    "scheme": {
493                        "platlib": "//lib/python{VERSION}/site-packages",
494                        "purelib": "//lib/python{VERSION}/site-packages",
495                        "include": "//include/python{VERSION}",
496                        "scripts": "//bin",
497                        "data": "/"
498                    },
499                    "virtualenv": {
500                        "purelib": "lib/python{VERSION}/site-packages",
501                        "platlib": "lib/python{VERSION}/site-packages",
502                        "include": "include/site/python{VERSION}",
503                        "scripts": "bin",
504                        "data": ""
505                    },
506                    "pointer_size": "32",
507                    "gil_disabled": false,
508                    "debug_enabled": false
509                }
510            "##};
511
512            let json = json
513                .replace(
514                    "{PATH}",
515                    path.to_str().expect("Path can be represented as string"),
516                )
517                .replace("{FULL_VERSION}", &version.to_string())
518                .replace(
519                    "{VERSION}",
520                    &format!("{}.{}", version.major(), version.minor()),
521                );
522
523            fs_err::create_dir_all(path.parent().unwrap())?;
524            fs_err::write(
525                path,
526                formatdoc! {r"
527                #!/bin/sh
528                echo '{json}'
529                "},
530            )?;
531
532            fs_err::set_permissions(path, std::os::unix::fs::PermissionsExt::from_mode(0o770))?;
533
534            Ok(())
535        }
536
537        /// Create a mock Python 2 interpreter executable which returns a fixed error message mocking
538        /// invocation of Python 2 with the `-I` flag as done by our query script.
539        fn create_mock_python2_interpreter(path: &Path) -> Result<()> {
540            let output = indoc! { r"
541                Unknown option: -I
542                usage: /usr/bin/python [option] ... [-c cmd | -m mod | file | -] [arg] ...
543                Try `python -h` for more information.
544            "};
545
546            fs_err::write(
547                path,
548                formatdoc! {r"
549                #!/bin/sh
550                echo '{output}' 1>&2
551                "},
552            )?;
553
554            fs_err::set_permissions(path, std::os::unix::fs::PermissionsExt::from_mode(0o770))?;
555
556            Ok(())
557        }
558
559        /// Create child directories in a temporary directory.
560        fn new_search_path_directories(
561            &mut self,
562            names: &[impl AsRef<Path>],
563        ) -> Result<Vec<ChildPath>> {
564            let paths = names
565                .iter()
566                .map(|name| self.new_search_path_directory(name))
567                .collect::<Result<Vec<_>>>()?;
568            Ok(paths)
569        }
570
571        /// Create fake Python interpreters the given Python versions.
572        ///
573        /// Adds them to the test context search path.
574        fn add_python_to_workdir(&self, name: &str, version: &str) -> Result<()> {
575            Self::create_mock_interpreter(
576                self.workdir.child(name).as_ref(),
577                &PythonVersion::from_str(version).expect("Test uses valid version"),
578                ImplementationName::default(),
579                true,
580                false,
581            )
582        }
583
584        fn add_pyodide_version(&mut self, version: &'static str) -> Result<()> {
585            let path = self.new_search_path_directory(format!("pyodide-{version}"))?;
586            let python = format!("pyodide{}", env::consts::EXE_SUFFIX);
587            Self::create_mock_pyodide_interpreter(
588                &path.join(python),
589                &PythonVersion::from_str(version).unwrap(),
590            )?;
591            Ok(())
592        }
593
594        /// Create fake Python interpreters the given Python versions.
595        ///
596        /// Adds them to the test context search path.
597        fn add_python_versions(&mut self, versions: &[&'static str]) -> Result<()> {
598            let interpreters: Vec<_> = versions
599                .iter()
600                .map(|version| (true, ImplementationName::default(), "python", *version))
601                .collect();
602            self.add_python_interpreters(interpreters.as_slice())
603        }
604
605        /// Create fake Python interpreters the given Python implementations and versions.
606        ///
607        /// Adds them to the test context search path.
608        fn add_python_interpreters(
609            &mut self,
610            kinds: &[(bool, ImplementationName, &'static str, &'static str)],
611        ) -> Result<()> {
612            // Generate a "unique" folder name for each interpreter
613            let names: Vec<OsString> = kinds
614                .iter()
615                .map(|(system, implementation, name, version)| {
616                    OsString::from_str(&format!("{system}-{implementation}-{name}-{version}"))
617                        .unwrap()
618                })
619                .collect();
620            let paths = self.new_search_path_directories(names.as_slice())?;
621            for (path, (system, implementation, executable, version)) in
622                itertools::zip_eq(&paths, kinds)
623            {
624                let python = format!("{executable}{}", env::consts::EXE_SUFFIX);
625                Self::create_mock_interpreter(
626                    &path.join(python),
627                    &PythonVersion::from_str(version).unwrap(),
628                    *implementation,
629                    *system,
630                    false,
631                )?;
632            }
633            Ok(())
634        }
635
636        /// Create a mock virtual environment at the given directory
637        fn mock_venv(path: impl AsRef<Path>, version: &'static str) -> Result<()> {
638            let executable = virtualenv_python_executable(path.as_ref());
639            fs_err::create_dir_all(
640                executable
641                    .parent()
642                    .expect("A Python executable path should always have a parent"),
643            )?;
644            Self::create_mock_interpreter(
645                &executable,
646                &PythonVersion::from_str(version)
647                    .expect("A valid Python version is used for tests"),
648                ImplementationName::default(),
649                false,
650                false,
651            )?;
652            ChildPath::new(path.as_ref().join("pyvenv.cfg")).touch()?;
653            Ok(())
654        }
655
656        /// Create a mock conda prefix at the given directory.
657        ///
658        /// These are like virtual environments but they look like system interpreters because `prefix` and `base_prefix` are equal.
659        fn mock_conda_prefix(path: impl AsRef<Path>, version: &'static str) -> Result<()> {
660            let executable = virtualenv_python_executable(&path);
661            fs_err::create_dir_all(
662                executable
663                    .parent()
664                    .expect("A Python executable path should always have a parent"),
665            )?;
666            Self::create_mock_interpreter(
667                &executable,
668                &PythonVersion::from_str(version)
669                    .expect("A valid Python version is used for tests"),
670                ImplementationName::default(),
671                true,
672                false,
673            )?;
674            ChildPath::new(path.as_ref().join("pyvenv.cfg")).touch()?;
675            Ok(())
676        }
677    }
678
679    #[test]
680    fn find_python_default_arch() -> Result<()> {
681        let mut context = TestContext::new()?;
682        let version = PythonVersion::from_str("3.14.1").expect("valid Python version");
683        let x86_64 = context
684            .new_search_path_directory("x86_64")?
685            .join("python3.14");
686        let aarch64 = context
687            .new_search_path_directory("aarch64")?
688            .join("python3.14");
689        for executable in [&x86_64, &aarch64] {
690            TestContext::create_mock_interpreter(
691                executable,
692                &version,
693                ImplementationName::CPython,
694                true,
695                false,
696            )?;
697        }
698        let script = fs_err::read_to_string(&aarch64)?;
699        fs_err::write(&aarch64, script.replace("x86_64", "aarch64"))?;
700        let arch = Some("aarch64".parse()?);
701
702        let installation = context.run(|| {
703            find_python_installation(
704                &parse_request("3.14"),
705                EnvironmentPreference::OnlySystem,
706                PythonPreference::OnlySystem,
707                arch,
708                &context.cache,
709            )
710        })??;
711        assert_eq!(installation.interpreter().sys_executable(), aarch64);
712
713        // Relaxing the requested Python version still requires the selected architecture.
714        for request in ["3.14.99", "3.99"] {
715            let installation = context.run(|| {
716                find_best_python_installation_no_download(
717                    &parse_request(request),
718                    EnvironmentPreference::OnlySystem,
719                    PythonPreference::OnlySystem,
720                    arch,
721                    &context.cache,
722                )
723            })?;
724            assert_eq!(installation.interpreter().sys_executable(), aarch64);
725        }
726
727        let installations = context.run(|| {
728            find_all_python_installations(
729                &parse_request("3.14"),
730                EnvironmentPreference::OnlySystem,
731                PythonPreference::OnlySystem,
732                arch,
733                &context.cache,
734            )
735        })?;
736        assert_eq!(
737            installations
738                .iter()
739                .map(|installation| installation.interpreter().sys_executable())
740                .collect::<Vec<_>>(),
741            vec![aarch64.as_path()]
742        );
743
744        let installation = context.run(|| {
745            find_python_installation(
746                &parse_request("cpython-3.14-linux-x86_64-gnu"),
747                EnvironmentPreference::OnlySystem,
748                PythonPreference::OnlySystem,
749                arch,
750                &context.cache,
751            )
752        })??;
753        assert_eq!(installation.interpreter().sys_executable(), x86_64);
754
755        let installation = context.run(|| {
756            find_python_installation(
757                &PythonRequest::File(x86_64.clone()),
758                EnvironmentPreference::OnlySystem,
759                PythonPreference::OnlySystem,
760                arch,
761                &context.cache,
762            )
763        })??;
764        assert_eq!(installation.interpreter().sys_executable(), x86_64);
765        Ok(())
766    }
767
768    #[test]
769    fn find_python_empty_path() -> Result<()> {
770        let mut context = TestContext::new()?;
771
772        context.search_path = Some(vec![]);
773        let result = context.run(|| {
774            find_python_installation(
775                &PythonRequest::Default,
776                EnvironmentPreference::OnlySystem,
777                PythonPreference::default(),
778                None,
779                &context.cache,
780            )
781        });
782        assert_matches!(
783            result,
784            Ok(Err(PythonNotFound { .. })),
785            "With an empty path, no Python installation should be detected got {result:?}"
786        );
787
788        context.search_path = None;
789        let result = context.run(|| {
790            find_python_installation(
791                &PythonRequest::Default,
792                EnvironmentPreference::OnlySystem,
793                PythonPreference::default(),
794                None,
795                &context.cache,
796            )
797        });
798        assert_matches!(
799            result,
800            Ok(Err(PythonNotFound { .. })),
801            "With an unset path, no Python installation should be detected got {result:?}"
802        );
803
804        Ok(())
805    }
806
807    #[test]
808    fn find_python_unexecutable_file() -> Result<()> {
809        let mut context = TestContext::new()?;
810        context
811            .new_search_path_directory("path")?
812            .child(format!("python{}", env::consts::EXE_SUFFIX))
813            .touch()?;
814
815        let result = context.run(|| {
816            find_python_installation(
817                &PythonRequest::Default,
818                EnvironmentPreference::OnlySystem,
819                PythonPreference::default(),
820                None,
821                &context.cache,
822            )
823        });
824        assert_matches!(
825            result,
826            Ok(Err(PythonNotFound { .. })),
827            "With a non-executable Python, no Python installation should be detected; got {result:?}"
828        );
829
830        Ok(())
831    }
832
833    #[test]
834    fn find_python_valid_executable() -> Result<()> {
835        let mut context = TestContext::new()?;
836        context.add_python_versions(&["3.12.1"])?;
837
838        let interpreter = context.run(|| {
839            find_python_installation(
840                &PythonRequest::Default,
841                EnvironmentPreference::OnlySystem,
842                PythonPreference::default(),
843                None,
844                &context.cache,
845            )
846        })??;
847        assert_matches!(
848            interpreter,
849            PythonInstallation {
850                source: PythonSource::SearchPathFirst,
851                interpreter: _
852            },
853            "We should find the valid executable; got {interpreter:?}"
854        );
855
856        Ok(())
857    }
858
859    #[test]
860    fn find_or_download_skips_download_metadata_when_python_is_found() -> Result<()> {
861        let mut context = TestContext::new()?;
862        context.add_python_versions(&["3.12.1"])?;
863        // Pass a missing metadata file to assert that an already-installed Python can
864        // be returned without reading the download list.
865        let missing_downloads = context.tempdir.child("missing-downloads.json");
866
867        let interpreter = context.run(|| {
868            let client_builder = BaseClientBuilder::default();
869            tokio::runtime::Builder::new_current_thread()
870                .enable_all()
871                .build()
872                .expect("Failed to build runtime")
873                .block_on(PythonInstallation::find_or_download(
874                    None,
875                    EnvironmentPreference::OnlySystem,
876                    PythonPreference::OnlySystem,
877                    None,
878                    PythonDownloads::Never,
879                    &client_builder,
880                    &context.cache,
881                    None,
882                    PythonDownloadMirrors::default(),
883                    missing_downloads.path().to_str(),
884                ))
885        })?;
886
887        assert_matches!(
888            interpreter,
889            PythonInstallation {
890                source: PythonSource::SearchPathFirst,
891                interpreter: _
892            },
893            "We should find the local Python without reading download metadata; got {interpreter:?}"
894        );
895        assert_eq!(
896            &interpreter.interpreter().python_full_version().to_string(),
897            "3.12.1",
898            "We should find the local interpreter"
899        );
900
901        Ok(())
902    }
903
904    #[test]
905    fn find_python_valid_executable_after_invalid() -> Result<()> {
906        let mut context = TestContext::new()?;
907        let children = context.new_search_path_directories(&[
908            "query-parse-error",
909            "not-executable",
910            "empty",
911            "good",
912        ])?;
913
914        // An executable file with a bad response
915        #[cfg(unix)]
916        fs_err::write(
917            children[0].join(format!("python{}", env::consts::EXE_SUFFIX)),
918            formatdoc! {r"
919        #!/bin/sh
920        echo 'foo'
921        "},
922        )?;
923        fs_err::set_permissions(
924            children[0].join(format!("python{}", env::consts::EXE_SUFFIX)),
925            std::os::unix::fs::PermissionsExt::from_mode(0o770),
926        )?;
927
928        // A non-executable file
929        ChildPath::new(children[1].join(format!("python{}", env::consts::EXE_SUFFIX))).touch()?;
930
931        // An empty directory at `children[2]`
932
933        // An good interpreter!
934        let python_path = children[3].join(format!("python{}", env::consts::EXE_SUFFIX));
935        TestContext::create_mock_interpreter(
936            &python_path,
937            &PythonVersion::from_str("3.12.1").unwrap(),
938            ImplementationName::default(),
939            true,
940            false,
941        )?;
942
943        let python = context.run(|| {
944            find_python_installation(
945                &PythonRequest::Default,
946                EnvironmentPreference::OnlySystem,
947                PythonPreference::default(),
948                None,
949                &context.cache,
950            )
951        })??;
952        assert_matches!(
953            python,
954            PythonInstallation {
955                source: PythonSource::SearchPath,
956                interpreter: _
957            },
958            "We should skip the bad executables in favor of the good one; got {python:?}"
959        );
960        assert_eq!(python.interpreter().sys_executable(), python_path);
961
962        Ok(())
963    }
964
965    #[test]
966    fn find_python_installations_discovers_search_path_lazily() -> Result<()> {
967        let context = TestContext::new()?;
968        let first_directory = context.tempdir.child("first");
969        let second_directory = context.tempdir.child("second");
970
971        let python = first_directory.join(format!("python{}", env::consts::EXE_SUFFIX));
972        let second = second_directory.join(format!("python{}", env::consts::EXE_SUFFIX));
973
974        let installation = context.run(|| -> Result<_> {
975            let mut installations = find_python_installations(
976                &PythonRequest::Default,
977                EnvironmentPreference::OnlySystem,
978                PythonPreference::OnlySystem,
979                None,
980                &context.cache,
981            );
982
983            TestContext::create_mock_interpreter(
984                &python,
985                &PythonVersion::from_str("3.12.1").expect("Test uses a valid Python version"),
986                ImplementationName::CPython,
987                true,
988                false,
989            )?;
990
991            let search_path = env::join_paths([first_directory.path(), second_directory.path()])?;
992            with_vars(
993                [(EnvVars::PATH, Some(search_path.as_os_str()))],
994                || -> Result<_> {
995                    let installation = installations
996                        .next()
997                        .expect("Deferred search path should contain an interpreter")??;
998
999                    TestContext::create_mock_interpreter(
1000                        &second,
1001                        &PythonVersion::from_str("3.11.9")
1002                            .expect("Test uses a valid Python version"),
1003                        ImplementationName::CPython,
1004                        true,
1005                        false,
1006                    )?;
1007                    let second_installation = installations
1008                        .next()
1009                        .expect("Later search path directory should be discovered")??;
1010                    assert_eq!(second_installation.interpreter().sys_executable(), second);
1011
1012                    Ok(installation)
1013                },
1014            )
1015        })?;
1016
1017        assert_eq!(installation.interpreter().sys_executable(), python);
1018
1019        Ok(())
1020    }
1021
1022    #[test]
1023    fn find_python_installation_queries_lazily() -> Result<()> {
1024        let mut context = TestContext::new()?;
1025        let first_directory = context.new_search_path_directory("first")?;
1026        let second_directory = context.new_search_path_directory("second")?;
1027
1028        let first = first_directory.join(format!("python{}", env::consts::EXE_SUFFIX));
1029        TestContext::create_mock_interpreter(
1030            &first,
1031            &PythonVersion::from_str("3.12.1").expect("Test uses a valid Python version"),
1032            ImplementationName::CPython,
1033            true,
1034            false,
1035        )?;
1036
1037        let second = second_directory.join(format!("python{}", env::consts::EXE_SUFFIX));
1038        TestContext::create_mock_interpreter(
1039            &second,
1040            &PythonVersion::from_str("3.11.9").expect("Test uses a valid Python version"),
1041            ImplementationName::CPython,
1042            true,
1043            false,
1044        )?;
1045        let second_target =
1046            second_directory.join(format!("python-real{}", env::consts::EXE_SUFFIX));
1047        fs_err::rename(&second, &second_target)?;
1048
1049        let marker = context.tempdir.child("second-was-queried");
1050        fs_err::write(
1051            &second,
1052            formatdoc! {r#"
1053                #!/bin/sh
1054                : > "{marker}"
1055                exec "{target}" "$@"
1056            "#,
1057            marker = marker.path().display(),
1058            target = second_target.display()},
1059        )?;
1060        fs_err::set_permissions(&second, std::os::unix::fs::PermissionsExt::from_mode(0o770))?;
1061
1062        let installation = context.run(|| {
1063            find_python_installation(
1064                &PythonRequest::Default,
1065                EnvironmentPreference::OnlySystem,
1066                PythonPreference::OnlySystem,
1067                None,
1068                &context.cache,
1069            )
1070        })??;
1071
1072        assert_eq!(installation.interpreter().sys_executable(), first);
1073        assert!(
1074            !marker.path().exists(),
1075            "Sequential discovery should not query candidates after finding a match"
1076        );
1077
1078        Ok(())
1079    }
1080
1081    #[test]
1082    fn find_all_python_installations_matches_sequential_discovery() -> Result<()> {
1083        let mut context = TestContext::new()?;
1084        let sequential_cache = Cache::temp()?;
1085        let parallel_cache = Cache::temp()?;
1086
1087        let broken_directory = context.new_search_path_directory("broken")?;
1088        let broken = broken_directory.join(format!("python{}", env::consts::EXE_SUFFIX));
1089        fs_err::write(
1090            &broken,
1091            formatdoc! {r"
1092                #!/bin/sh
1093                echo 'not interpreter metadata'
1094            "},
1095        )?;
1096        fs_err::set_permissions(&broken, std::os::unix::fs::PermissionsExt::from_mode(0o770))?;
1097
1098        let cpython_311_directory = context.new_search_path_directory("cpython-3.11")?;
1099        let cpython_311 = cpython_311_directory.join(format!("python{}", env::consts::EXE_SUFFIX));
1100        TestContext::create_mock_interpreter(
1101            &cpython_311,
1102            &PythonVersion::from_str("3.11.9").expect("Test uses a valid Python version"),
1103            ImplementationName::CPython,
1104            true,
1105            false,
1106        )?;
1107        let cpython_311_target =
1108            cpython_311_directory.join(format!("python-real{}", env::consts::EXE_SUFFIX));
1109        fs_err::rename(&cpython_311, &cpython_311_target)?;
1110        fs_err::write(
1111            &cpython_311,
1112            formatdoc! {r#"
1113                #!/bin/sh
1114                sleep 1
1115                exec "{target}" "$@"
1116            "#,
1117            target = cpython_311_target.display()},
1118        )?;
1119        fs_err::set_permissions(
1120            &cpython_311,
1121            std::os::unix::fs::PermissionsExt::from_mode(0o770),
1122        )?;
1123
1124        let cpython_312_directory = context.new_search_path_directory("cpython-3.12")?;
1125        let cpython_312 = cpython_312_directory.join(format!("python{}", env::consts::EXE_SUFFIX));
1126        TestContext::create_mock_interpreter(
1127            &cpython_312,
1128            &PythonVersion::from_str("3.12.1").expect("Test uses a valid Python version"),
1129            ImplementationName::CPython,
1130            true,
1131            false,
1132        )?;
1133
1134        let pypy_directory = context.new_search_path_directory("pypy-3.10")?;
1135        let pypy = pypy_directory.join(format!("pypy{}", env::consts::EXE_SUFFIX));
1136        TestContext::create_mock_interpreter(
1137            &pypy,
1138            &PythonVersion::from_str("3.10.14").expect("Test uses a valid Python version"),
1139            ImplementationName::PyPy,
1140            true,
1141            false,
1142        )?;
1143
1144        let virtual_environment = context.tempdir.child("virtual-environment");
1145        TestContext::mock_venv(&virtual_environment, "3.12.1")?;
1146
1147        let key = context
1148            .run(|| {
1149                find_python_installation(
1150                    &PythonRequest::File(cpython_312.clone()),
1151                    EnvironmentPreference::OnlySystem,
1152                    PythonPreference::OnlySystem,
1153                    None,
1154                    &context.cache,
1155                )
1156            })??
1157            .key()
1158            .to_string();
1159        let key_request = parse_request(&key);
1160        assert_matches!(
1161            key_request,
1162            PythonRequest::Key(_),
1163            "Expected an installation key request, got {key_request:?}"
1164        );
1165
1166        let requests = [
1167            PythonRequest::Any,
1168            PythonRequest::Default,
1169            parse_request("3.12"),
1170            parse_request("cpython"),
1171            parse_request("pypy@3.10"),
1172            PythonRequest::ExecutableName(format!("pypy{}", env::consts::EXE_SUFFIX)),
1173            PythonRequest::File(cpython_312),
1174            PythonRequest::Directory(virtual_environment.to_path_buf()),
1175            key_request,
1176        ];
1177
1178        for request in requests {
1179            let (sequential, parallel) = context.run(|| {
1180                let mut sequential = Vec::new();
1181                for result in find_python_installations(
1182                    &request,
1183                    EnvironmentPreference::OnlySystem,
1184                    PythonPreference::OnlySystem,
1185                    None,
1186                    &sequential_cache,
1187                ) {
1188                    match result {
1189                        Ok(Ok(installation)) => sequential.push(installation),
1190                        Ok(Err(_)) => {}
1191                        Err(err) if err.is_critical() => return Err(err),
1192                        Err(_) => {}
1193                    }
1194                }
1195
1196                let parallel = find_all_python_installations(
1197                    &request,
1198                    EnvironmentPreference::OnlySystem,
1199                    PythonPreference::OnlySystem,
1200                    None,
1201                    &parallel_cache,
1202                )?;
1203                Ok::<_, discovery::Error>((sequential, parallel))
1204            })?;
1205
1206            let identifiers = |installations: Vec<PythonInstallation>| {
1207                installations
1208                    .into_iter()
1209                    .map(|installation| {
1210                        (
1211                            *installation.source(),
1212                            installation.interpreter().sys_executable().to_path_buf(),
1213                            installation.key().to_string(),
1214                        )
1215                    })
1216                    .collect::<Vec<_>>()
1217            };
1218            assert_eq!(
1219                identifiers(sequential),
1220                identifiers(parallel),
1221                "Sequential and parallel discovery differ for {request}"
1222            );
1223        }
1224
1225        Ok(())
1226    }
1227
1228    #[test]
1229    fn find_python_only_python2_executable() -> Result<()> {
1230        let mut context = TestContext::new()?;
1231        let python = context
1232            .new_search_path_directory("python2")?
1233            .child(format!("python{}", env::consts::EXE_SUFFIX));
1234        TestContext::create_mock_python2_interpreter(&python)?;
1235
1236        let result = context.run(|| {
1237            find_python_installation(
1238                &PythonRequest::Default,
1239                EnvironmentPreference::OnlySystem,
1240                PythonPreference::default(),
1241                None,
1242                &context.cache,
1243            )
1244        });
1245        assert_matches!(
1246            result,
1247            Err(discovery::Error::Query(..)),
1248            "If only Python 2 is available, we should report the interpreter query error; got {result:?}"
1249        );
1250
1251        Ok(())
1252    }
1253
1254    #[test]
1255    fn find_python_skip_python2_executable() -> Result<()> {
1256        let mut context = TestContext::new()?;
1257
1258        let python2 = context
1259            .new_search_path_directory("python2")?
1260            .child(format!("python{}", env::consts::EXE_SUFFIX));
1261        TestContext::create_mock_python2_interpreter(&python2)?;
1262
1263        let python3 = context
1264            .new_search_path_directory("python3")?
1265            .child(format!("python{}", env::consts::EXE_SUFFIX));
1266        TestContext::create_mock_interpreter(
1267            &python3,
1268            &PythonVersion::from_str("3.12.1").unwrap(),
1269            ImplementationName::default(),
1270            true,
1271            false,
1272        )?;
1273
1274        let python = context.run(|| {
1275            find_python_installation(
1276                &PythonRequest::Default,
1277                EnvironmentPreference::OnlySystem,
1278                PythonPreference::default(),
1279                None,
1280                &context.cache,
1281            )
1282        })??;
1283        assert_matches!(
1284            python,
1285            PythonInstallation {
1286                source: PythonSource::SearchPath,
1287                interpreter: _
1288            },
1289            "We should skip the Python 2 installation and find the Python 3 interpreter; got {python:?}"
1290        );
1291        assert_eq!(python.interpreter().sys_executable(), python3.path());
1292
1293        Ok(())
1294    }
1295
1296    #[test]
1297    fn find_python_system_python_allowed() -> Result<()> {
1298        let mut context = TestContext::new()?;
1299        context.add_python_interpreters(&[
1300            (false, ImplementationName::CPython, "python", "3.10.0"),
1301            (true, ImplementationName::CPython, "python", "3.10.1"),
1302        ])?;
1303
1304        let python = context.run(|| {
1305            find_python_installation(
1306                &PythonRequest::Default,
1307                EnvironmentPreference::Any,
1308                PythonPreference::OnlySystem,
1309                None,
1310                &context.cache,
1311            )
1312        })??;
1313        assert_eq!(
1314            python.interpreter().python_full_version().to_string(),
1315            "3.10.0",
1316            "Should find the first interpreter regardless of system"
1317        );
1318
1319        // Reverse the order of the virtual environment and system
1320        context.reset_search_path();
1321        context.add_python_interpreters(&[
1322            (true, ImplementationName::CPython, "python", "3.10.1"),
1323            (false, ImplementationName::CPython, "python", "3.10.0"),
1324        ])?;
1325
1326        let python = context.run(|| {
1327            find_python_installation(
1328                &PythonRequest::Default,
1329                EnvironmentPreference::Any,
1330                PythonPreference::OnlySystem,
1331                None,
1332                &context.cache,
1333            )
1334        })??;
1335        assert_eq!(
1336            python.interpreter().python_full_version().to_string(),
1337            "3.10.1",
1338            "Should find the first interpreter regardless of system"
1339        );
1340
1341        Ok(())
1342    }
1343
1344    #[test]
1345    fn find_python_system_python_required() -> Result<()> {
1346        let mut context = TestContext::new()?;
1347        context.add_python_interpreters(&[
1348            (false, ImplementationName::CPython, "python", "3.10.0"),
1349            (true, ImplementationName::CPython, "python", "3.10.1"),
1350        ])?;
1351
1352        let python = context.run(|| {
1353            find_python_installation(
1354                &PythonRequest::Default,
1355                EnvironmentPreference::OnlySystem,
1356                PythonPreference::OnlySystem,
1357                None,
1358                &context.cache,
1359            )
1360        })??;
1361        assert_eq!(
1362            python.interpreter().python_full_version().to_string(),
1363            "3.10.1",
1364            "Should skip the virtual environment"
1365        );
1366
1367        Ok(())
1368    }
1369
1370    #[test]
1371    fn find_python_system_python_disallowed() -> Result<()> {
1372        let mut context = TestContext::new()?;
1373        context.add_python_interpreters(&[
1374            (true, ImplementationName::CPython, "python", "3.10.0"),
1375            (false, ImplementationName::CPython, "python", "3.10.1"),
1376        ])?;
1377
1378        let python = context.run(|| {
1379            find_python_installation(
1380                &PythonRequest::Default,
1381                EnvironmentPreference::Any,
1382                PythonPreference::OnlySystem,
1383                None,
1384                &context.cache,
1385            )
1386        })??;
1387        assert_eq!(
1388            python.interpreter().python_full_version().to_string(),
1389            "3.10.0",
1390            "Should skip the system Python"
1391        );
1392
1393        Ok(())
1394    }
1395
1396    #[test]
1397    fn find_python_version_minor() -> Result<()> {
1398        let mut context = TestContext::new()?;
1399        context.add_python_versions(&["3.10.1", "3.11.2", "3.12.3"])?;
1400
1401        let python = context.run(|| {
1402            find_python_installation(
1403                &parse_request("3.11"),
1404                EnvironmentPreference::Any,
1405                PythonPreference::OnlySystem,
1406                None,
1407                &context.cache,
1408            )
1409        })??;
1410
1411        assert_matches!(
1412            python,
1413            PythonInstallation {
1414                source: PythonSource::SearchPath,
1415                interpreter: _
1416            },
1417            "We should find a python; got {python:?}"
1418        );
1419        assert_eq!(
1420            &python.interpreter().python_full_version().to_string(),
1421            "3.11.2",
1422            "We should find the correct interpreter for the request"
1423        );
1424
1425        Ok(())
1426    }
1427
1428    #[test]
1429    fn find_python_version_patch() -> Result<()> {
1430        let mut context = TestContext::new()?;
1431        context.add_python_versions(&["3.10.1", "3.11.3", "3.11.2", "3.12.3"])?;
1432
1433        let python = context.run(|| {
1434            find_python_installation(
1435                &parse_request("3.11.2"),
1436                EnvironmentPreference::Any,
1437                PythonPreference::OnlySystem,
1438                None,
1439                &context.cache,
1440            )
1441        })??;
1442
1443        assert_matches!(
1444            python,
1445            PythonInstallation {
1446                source: PythonSource::SearchPath,
1447                interpreter: _
1448            },
1449            "We should find a python; got {python:?}"
1450        );
1451        assert_eq!(
1452            &python.interpreter().python_full_version().to_string(),
1453            "3.11.2",
1454            "We should find the correct interpreter for the request"
1455        );
1456
1457        Ok(())
1458    }
1459
1460    #[test]
1461    fn find_python_version_minor_no_match() -> Result<()> {
1462        let mut context = TestContext::new()?;
1463        context.add_python_versions(&["3.10.1", "3.11.2", "3.12.3"])?;
1464
1465        let result = context.run(|| {
1466            find_python_installation(
1467                &parse_request("3.9"),
1468                EnvironmentPreference::Any,
1469                PythonPreference::OnlySystem,
1470                None,
1471                &context.cache,
1472            )
1473        })?;
1474        assert_matches!(
1475            result,
1476            Err(PythonNotFound { .. }),
1477            "We should not find a python; got {result:?}"
1478        );
1479
1480        Ok(())
1481    }
1482
1483    #[test]
1484    fn find_python_version_patch_no_match() -> Result<()> {
1485        let mut context = TestContext::new()?;
1486        context.add_python_versions(&["3.10.1", "3.11.2", "3.12.3"])?;
1487
1488        let result = context.run(|| {
1489            find_python_installation(
1490                &parse_request("3.11.9"),
1491                EnvironmentPreference::Any,
1492                PythonPreference::OnlySystem,
1493                None,
1494                &context.cache,
1495            )
1496        })?;
1497        assert_matches!(
1498            result,
1499            Err(PythonNotFound { .. }),
1500            "We should not find a python; got {result:?}"
1501        );
1502
1503        Ok(())
1504    }
1505
1506    fn find_best_python_installation_no_download(
1507        request: &PythonRequest,
1508        environments: EnvironmentPreference,
1509        preference: PythonPreference,
1510        arch: Option<PythonArchitecture>,
1511        cache: &Cache,
1512    ) -> Result<PythonInstallation, crate::Error> {
1513        let client_builder = BaseClientBuilder::default();
1514        tokio::runtime::Builder::new_current_thread()
1515            .enable_all()
1516            .build()
1517            .expect("Failed to build runtime")
1518            .block_on(find_best_python_installation(
1519                request,
1520                environments,
1521                preference,
1522                arch,
1523                false,
1524                &client_builder,
1525                cache,
1526                None,
1527                PythonDownloadMirrors::default(),
1528                None,
1529            ))
1530    }
1531
1532    #[test]
1533    fn find_best_python_version_patch_exact() -> Result<()> {
1534        let mut context = TestContext::new()?;
1535        context.add_python_versions(&["3.10.1", "3.11.2", "3.11.4", "3.11.3", "3.12.5"])?;
1536
1537        let python = context.run(|| {
1538            find_best_python_installation_no_download(
1539                &parse_request("3.11.3"),
1540                EnvironmentPreference::Any,
1541                PythonPreference::OnlySystem,
1542                None,
1543                &context.cache,
1544            )
1545        })?;
1546
1547        assert_matches!(
1548            python,
1549            PythonInstallation {
1550                source: PythonSource::SearchPath,
1551                interpreter: _
1552            },
1553            "We should find a python; got {python:?}"
1554        );
1555        assert_eq!(
1556            &python.interpreter().python_full_version().to_string(),
1557            "3.11.3",
1558            "We should prefer the exact request"
1559        );
1560
1561        Ok(())
1562    }
1563
1564    #[test]
1565    fn find_best_python_version_patch_fallback() -> Result<()> {
1566        let mut context = TestContext::new()?;
1567        context.add_python_versions(&["3.10.1", "3.11.2", "3.11.4", "3.11.3", "3.12.5"])?;
1568
1569        let python = context.run(|| {
1570            find_best_python_installation_no_download(
1571                &parse_request("3.11.11"),
1572                EnvironmentPreference::Any,
1573                PythonPreference::OnlySystem,
1574                None,
1575                &context.cache,
1576            )
1577        })?;
1578
1579        assert_matches!(
1580            python,
1581            PythonInstallation {
1582                source: PythonSource::SearchPath,
1583                interpreter: _
1584            },
1585            "We should find a python; got {python:?}"
1586        );
1587        assert_eq!(
1588            &python.interpreter().python_full_version().to_string(),
1589            "3.11.2",
1590            "We should fallback to the first matching minor"
1591        );
1592
1593        Ok(())
1594    }
1595
1596    #[test]
1597    fn find_best_python_skips_source_without_match() -> Result<()> {
1598        let mut context = TestContext::new()?;
1599        let venv = context.tempdir.child(".venv");
1600        TestContext::mock_venv(&venv, "3.12.0")?;
1601        context.add_python_versions(&["3.10.1"])?;
1602
1603        let python =
1604            context.run_with_vars(&[(EnvVars::VIRTUAL_ENV, Some(venv.as_os_str()))], || {
1605                find_best_python_installation_no_download(
1606                    &parse_request("3.10"),
1607                    EnvironmentPreference::Any,
1608                    PythonPreference::OnlySystem,
1609                    None,
1610                    &context.cache,
1611                )
1612            })?;
1613        assert_matches!(
1614            python,
1615            PythonInstallation {
1616                source: PythonSource::SearchPathFirst,
1617                interpreter: _
1618            },
1619            "We should skip the active environment in favor of the requested version; got {python:?}"
1620        );
1621
1622        Ok(())
1623    }
1624
1625    #[test]
1626    fn find_best_python_returns_to_earlier_source_on_fallback() -> Result<()> {
1627        let mut context = TestContext::new()?;
1628        let venv = context.tempdir.child(".venv");
1629        TestContext::mock_venv(&venv, "3.10.1")?;
1630        context.add_python_versions(&["3.10.3"])?;
1631
1632        let python =
1633            context.run_with_vars(&[(EnvVars::VIRTUAL_ENV, Some(venv.as_os_str()))], || {
1634                find_best_python_installation_no_download(
1635                    &parse_request("3.10.2"),
1636                    EnvironmentPreference::Any,
1637                    PythonPreference::OnlySystem,
1638                    None,
1639                    &context.cache,
1640                )
1641            })?;
1642        assert_matches!(
1643            python,
1644            PythonInstallation {
1645                source: PythonSource::ActiveEnvironment,
1646                interpreter: _
1647            },
1648            "We should prefer the active environment after relaxing; got {python:?}"
1649        );
1650        assert_eq!(
1651            python.interpreter().python_full_version().to_string(),
1652            "3.10.1",
1653            "We should prefer the active environment"
1654        );
1655
1656        Ok(())
1657    }
1658
1659    #[test]
1660    fn find_python_from_active_python() -> Result<()> {
1661        let context = TestContext::new()?;
1662        let venv = context.tempdir.child("some-venv");
1663        TestContext::mock_venv(&venv, "3.12.0")?;
1664
1665        let python =
1666            context.run_with_vars(&[(EnvVars::VIRTUAL_ENV, Some(venv.as_os_str()))], || {
1667                find_python_installation(
1668                    &PythonRequest::Default,
1669                    EnvironmentPreference::Any,
1670                    PythonPreference::OnlySystem,
1671                    None,
1672                    &context.cache,
1673                )
1674            })??;
1675        assert_eq!(
1676            python.interpreter().python_full_version().to_string(),
1677            "3.12.0",
1678            "We should prefer the active environment"
1679        );
1680
1681        Ok(())
1682    }
1683
1684    #[test]
1685    fn find_python_from_active_python_prerelease() -> Result<()> {
1686        let mut context = TestContext::new()?;
1687        context.add_python_versions(&["3.12.0"])?;
1688        let venv = context.tempdir.child("some-venv");
1689        TestContext::mock_venv(&venv, "3.13.0rc1")?;
1690
1691        let python =
1692            context.run_with_vars(&[(EnvVars::VIRTUAL_ENV, Some(venv.as_os_str()))], || {
1693                find_python_installation(
1694                    &PythonRequest::Default,
1695                    EnvironmentPreference::Any,
1696                    PythonPreference::OnlySystem,
1697                    None,
1698                    &context.cache,
1699                )
1700            })??;
1701        assert_eq!(
1702            python.interpreter().python_full_version().to_string(),
1703            "3.13.0rc1",
1704            "We should prefer the active environment"
1705        );
1706
1707        Ok(())
1708    }
1709
1710    #[test]
1711    fn find_python_from_conda_prefix() -> Result<()> {
1712        let context = TestContext::new()?;
1713        let condaenv = context.tempdir.child("condaenv");
1714        TestContext::mock_conda_prefix(&condaenv, "3.12.0")?;
1715
1716        let python = context
1717            .run_with_vars(
1718                &[(EnvVars::CONDA_PREFIX, Some(condaenv.as_os_str()))],
1719                || {
1720                    // Note this python is not treated as a system interpreter
1721                    find_python_installation(
1722                        &PythonRequest::Default,
1723                        EnvironmentPreference::OnlyVirtual,
1724                        PythonPreference::OnlySystem,
1725                        None,
1726                        &context.cache,
1727                    )
1728                },
1729            )?
1730            .unwrap();
1731        assert_eq!(
1732            python.interpreter().python_full_version().to_string(),
1733            "3.12.0",
1734            "We should allow the active conda python"
1735        );
1736
1737        let baseenv = context.tempdir.child("conda");
1738        TestContext::mock_conda_prefix(&baseenv, "3.12.1")?;
1739
1740        // But not if it's a base environment
1741        let result = context.run_with_vars_and_preview(
1742            &[
1743                (EnvVars::CONDA_PREFIX, Some(baseenv.as_os_str())),
1744                (EnvVars::CONDA_DEFAULT_ENV, Some(&OsString::from("base"))),
1745                (EnvVars::CONDA_ROOT, None),
1746            ],
1747            &[],
1748            || {
1749                find_python_installation(
1750                    &PythonRequest::Default,
1751                    EnvironmentPreference::OnlyVirtual,
1752                    PythonPreference::OnlySystem,
1753                    None,
1754                    &context.cache,
1755                )
1756            },
1757        )?;
1758
1759        assert_matches!(
1760            result,
1761            Err(PythonNotFound { .. }),
1762            "We should not allow the non-virtual environment; got {result:?}"
1763        );
1764
1765        // Unless, system interpreters are included...
1766        let python = context
1767            .run_with_vars_and_preview(
1768                &[
1769                    (EnvVars::CONDA_PREFIX, Some(baseenv.as_os_str())),
1770                    (EnvVars::CONDA_DEFAULT_ENV, Some(&OsString::from("base"))),
1771                    (EnvVars::CONDA_ROOT, None),
1772                ],
1773                &[],
1774                || {
1775                    find_python_installation(
1776                        &PythonRequest::Default,
1777                        EnvironmentPreference::OnlySystem,
1778                        PythonPreference::OnlySystem,
1779                        None,
1780                        &context.cache,
1781                    )
1782                },
1783            )?
1784            .unwrap();
1785
1786        assert_eq!(
1787            python.interpreter().python_full_version().to_string(),
1788            "3.12.1",
1789            "We should find the base conda environment"
1790        );
1791
1792        // If the environment name doesn't match the default, we should not treat it as system
1793        let python = context
1794            .run_with_vars_and_preview(
1795                &[
1796                    (EnvVars::CONDA_PREFIX, Some(condaenv.as_os_str())),
1797                    (
1798                        EnvVars::CONDA_DEFAULT_ENV,
1799                        Some(&OsString::from("condaenv")),
1800                    ),
1801                ],
1802                &[],
1803                || {
1804                    find_python_installation(
1805                        &PythonRequest::Default,
1806                        EnvironmentPreference::OnlyVirtual,
1807                        PythonPreference::OnlySystem,
1808                        None,
1809                        &context.cache,
1810                    )
1811                },
1812            )?
1813            .unwrap();
1814
1815        assert_eq!(
1816            python.interpreter().python_full_version().to_string(),
1817            "3.12.0",
1818            "We should find the conda environment when name matches"
1819        );
1820
1821        // A special Conda environment name only identifies the base environment when its path
1822        // does not match the environment name.
1823        let result = context.run_with_vars_and_preview(
1824            &[
1825                (EnvVars::CONDA_PREFIX, Some(condaenv.as_os_str())),
1826                (EnvVars::CONDA_DEFAULT_ENV, Some(&OsString::from("base"))),
1827            ],
1828            &[],
1829            || {
1830                find_python_installation(
1831                    &PythonRequest::Default,
1832                    EnvironmentPreference::OnlyVirtual,
1833                    PythonPreference::OnlySystem,
1834                    None,
1835                    &context.cache,
1836                )
1837            },
1838        )?;
1839
1840        assert_matches!(
1841            result,
1842            Err(PythonNotFound { .. }),
1843            "We should not allow the base environment when looking for virtual environments"
1844        );
1845
1846        // When the directory name matches a special Conda environment name, it should be treated
1847        // as a child environment.
1848        for (name, version) in [("base", "3.12.6"), ("root", "3.12.7")] {
1849            let environment = context.tempdir.child(name);
1850            TestContext::mock_conda_prefix(&environment, version)?;
1851            let python = context
1852                .run_with_vars(
1853                    &[
1854                        (EnvVars::CONDA_PREFIX, Some(environment.as_os_str())),
1855                        (EnvVars::CONDA_DEFAULT_ENV, Some(&OsString::from(name))),
1856                        (EnvVars::CONDA_ROOT, None),
1857                    ],
1858                    || {
1859                        find_python_installation(
1860                            &PythonRequest::Default,
1861                            EnvironmentPreference::OnlyVirtual,
1862                            PythonPreference::OnlySystem,
1863                            None,
1864                            &context.cache,
1865                        )
1866                    },
1867                )?
1868                .unwrap();
1869
1870            assert_eq!(
1871                python.interpreter().python_full_version().to_string(),
1872                version,
1873                "We should find the child Conda environment named {name}"
1874            );
1875        }
1876
1877        // When environment name matches directory name, it should be treated as a child environment
1878        let myenv_dir = context.tempdir.child("myenv");
1879        TestContext::mock_conda_prefix(&myenv_dir, "3.12.5")?;
1880        let python = context
1881            .run_with_vars_and_preview(
1882                &[
1883                    (EnvVars::CONDA_PREFIX, Some(myenv_dir.as_os_str())),
1884                    (EnvVars::CONDA_DEFAULT_ENV, Some(&OsString::from("myenv"))),
1885                ],
1886                &[],
1887                || {
1888                    find_python_installation(
1889                        &PythonRequest::Default,
1890                        EnvironmentPreference::OnlyVirtual,
1891                        PythonPreference::OnlySystem,
1892                        None,
1893                        &context.cache,
1894                    )
1895                },
1896            )?
1897            .unwrap();
1898
1899        assert_eq!(
1900            python.interpreter().python_full_version().to_string(),
1901            "3.12.5",
1902            "We should find the child conda environment"
1903        );
1904
1905        // Test _CONDA_ROOT detection of base environment
1906        let conda_root_env = context.tempdir.child("conda-root");
1907        TestContext::mock_conda_prefix(&conda_root_env, "3.12.2")?;
1908
1909        // When _CONDA_ROOT matches CONDA_PREFIX, it should be treated as a base environment
1910        let result = context.run_with_vars(
1911            &[
1912                (EnvVars::CONDA_PREFIX, Some(conda_root_env.as_os_str())),
1913                (EnvVars::CONDA_ROOT, Some(conda_root_env.as_os_str())),
1914                (
1915                    EnvVars::CONDA_DEFAULT_ENV,
1916                    Some(&OsString::from("custom-name")),
1917                ),
1918            ],
1919            || {
1920                find_python_installation(
1921                    &PythonRequest::Default,
1922                    EnvironmentPreference::OnlyVirtual,
1923                    PythonPreference::OnlySystem,
1924                    None,
1925                    &context.cache,
1926                )
1927            },
1928        )?;
1929
1930        assert_matches!(
1931            result,
1932            Err(PythonNotFound { .. }),
1933            "Base environment detected via _CONDA_ROOT should be excluded from virtual environments; got {result:?}"
1934        );
1935
1936        // When _CONDA_ROOT doesn't match CONDA_PREFIX, it should be treated as a regular conda environment
1937        let other_conda_env = context.tempdir.child("other-conda");
1938        TestContext::mock_conda_prefix(&other_conda_env, "3.12.3")?;
1939
1940        let python = context
1941            .run_with_vars_and_preview(
1942                &[
1943                    (EnvVars::CONDA_PREFIX, Some(other_conda_env.as_os_str())),
1944                    (EnvVars::CONDA_ROOT, Some(conda_root_env.as_os_str())),
1945                    (
1946                        EnvVars::CONDA_DEFAULT_ENV,
1947                        Some(&OsString::from("other-conda")),
1948                    ),
1949                ],
1950                &[],
1951                || {
1952                    find_python_installation(
1953                        &PythonRequest::Default,
1954                        EnvironmentPreference::OnlyVirtual,
1955                        PythonPreference::OnlySystem,
1956                        None,
1957                        &context.cache,
1958                    )
1959                },
1960            )?
1961            .unwrap();
1962
1963        assert_eq!(
1964            python.interpreter().python_full_version().to_string(),
1965            "3.12.3",
1966            "Non-base conda environment should be available for virtual environment preference"
1967        );
1968
1969        // When CONDA_PREFIX equals CONDA_DEFAULT_ENV, it should be treated as a virtual environment
1970        let unnamed_env = context.tempdir.child("my-conda-env");
1971        TestContext::mock_conda_prefix(&unnamed_env, "3.12.4")?;
1972        let unnamed_env_path = unnamed_env.to_string_lossy().to_string();
1973
1974        let python = context.run_with_vars(
1975            &[
1976                (EnvVars::CONDA_PREFIX, Some(unnamed_env.as_os_str())),
1977                (
1978                    EnvVars::CONDA_DEFAULT_ENV,
1979                    Some(&OsString::from(&unnamed_env_path)),
1980                ),
1981            ],
1982            || {
1983                find_python_installation(
1984                    &PythonRequest::Default,
1985                    EnvironmentPreference::OnlyVirtual,
1986                    PythonPreference::OnlySystem,
1987                    None,
1988                    &context.cache,
1989                )
1990            },
1991        )??;
1992
1993        assert_eq!(
1994            python.interpreter().python_full_version().to_string(),
1995            "3.12.4",
1996            "We should find the unnamed conda environment"
1997        );
1998
1999        Ok(())
2000    }
2001
2002    #[test]
2003    fn find_python_from_conda_prefix_and_virtualenv() -> Result<()> {
2004        let context = TestContext::new()?;
2005        let venv = context.tempdir.child(".venv");
2006        TestContext::mock_venv(&venv, "3.12.0")?;
2007        let condaenv = context.tempdir.child("condaenv");
2008        TestContext::mock_conda_prefix(&condaenv, "3.12.1")?;
2009
2010        let python = context.run_with_vars(
2011            &[
2012                (EnvVars::VIRTUAL_ENV, Some(venv.as_os_str())),
2013                (EnvVars::CONDA_PREFIX, Some(condaenv.as_os_str())),
2014            ],
2015            || {
2016                find_python_installation(
2017                    &PythonRequest::Default,
2018                    EnvironmentPreference::Any,
2019                    PythonPreference::OnlySystem,
2020                    None,
2021                    &context.cache,
2022                )
2023            },
2024        )??;
2025        assert_eq!(
2026            python.interpreter().python_full_version().to_string(),
2027            "3.12.0",
2028            "We should prefer the non-conda python"
2029        );
2030
2031        // Put a virtual environment in the working directory
2032        let venv = context.workdir.child(".venv");
2033        TestContext::mock_venv(venv, "3.12.2")?;
2034        let python = context.run_with_vars(
2035            &[(EnvVars::CONDA_PREFIX, Some(condaenv.as_os_str()))],
2036            || {
2037                find_python_installation(
2038                    &PythonRequest::Default,
2039                    EnvironmentPreference::Any,
2040                    PythonPreference::OnlySystem,
2041                    None,
2042                    &context.cache,
2043                )
2044            },
2045        )??;
2046        assert_eq!(
2047            python.interpreter().python_full_version().to_string(),
2048            "3.12.1",
2049            "We should prefer the conda python over inactive virtual environments"
2050        );
2051
2052        Ok(())
2053    }
2054
2055    #[test]
2056    fn find_python_from_discovered_python() -> Result<()> {
2057        let mut context = TestContext::new()?;
2058
2059        // Create a virtual environment in a parent of the workdir
2060        let venv = context.tempdir.child(".venv");
2061        TestContext::mock_venv(venv, "3.12.0")?;
2062
2063        let python = context.run(|| {
2064            find_python_installation(
2065                &PythonRequest::Default,
2066                EnvironmentPreference::Any,
2067                PythonPreference::OnlySystem,
2068                None,
2069                &context.cache,
2070            )
2071        })??;
2072
2073        assert_eq!(
2074            python.interpreter().python_full_version().to_string(),
2075            "3.12.0",
2076            "We should find the python"
2077        );
2078
2079        // Add some system versions to ensure we don't use those
2080        context.add_python_versions(&["3.12.1", "3.12.2"])?;
2081        let python = context.run(|| {
2082            find_python_installation(
2083                &PythonRequest::Default,
2084                EnvironmentPreference::Any,
2085                PythonPreference::OnlySystem,
2086                None,
2087                &context.cache,
2088            )
2089        })??;
2090
2091        assert_eq!(
2092            python.interpreter().python_full_version().to_string(),
2093            "3.12.0",
2094            "We should prefer the discovered virtual environment over available system versions"
2095        );
2096
2097        Ok(())
2098    }
2099
2100    #[test]
2101    fn find_python_skips_broken_active_python() -> Result<()> {
2102        let context = TestContext::new()?;
2103        let venv = context.tempdir.child(".venv");
2104        TestContext::mock_venv(&venv, "3.12.0")?;
2105
2106        // Delete the pyvenv cfg to break the virtualenv
2107        fs_err::remove_file(venv.join("pyvenv.cfg"))?;
2108
2109        let python =
2110            context.run_with_vars(&[(EnvVars::VIRTUAL_ENV, Some(venv.as_os_str()))], || {
2111                find_python_installation(
2112                    &PythonRequest::Default,
2113                    EnvironmentPreference::Any,
2114                    PythonPreference::OnlySystem,
2115                    None,
2116                    &context.cache,
2117                )
2118            })??;
2119        assert_eq!(
2120            python.interpreter().python_full_version().to_string(),
2121            "3.12.0",
2122            // TODO(zanieb): We should skip this python, why don't we?
2123            "We should prefer the active environment"
2124        );
2125
2126        Ok(())
2127    }
2128
2129    #[test]
2130    fn find_python_from_parent_interpreter() -> Result<()> {
2131        let mut context = TestContext::new()?;
2132
2133        let parent = context.tempdir.child("python").to_path_buf();
2134        TestContext::create_mock_interpreter(
2135            &parent,
2136            &PythonVersion::from_str("3.12.0").unwrap(),
2137            ImplementationName::CPython,
2138            // Note we mark this as a system interpreter instead of a virtual environment
2139            true,
2140            false,
2141        )?;
2142
2143        let python = context.run_with_vars(
2144            &[(
2145                EnvVars::UV_INTERNAL__PARENT_INTERPRETER,
2146                Some(parent.as_os_str()),
2147            )],
2148            || {
2149                find_python_installation(
2150                    &PythonRequest::Default,
2151                    EnvironmentPreference::Any,
2152                    PythonPreference::OnlySystem,
2153                    None,
2154                    &context.cache,
2155                )
2156            },
2157        )??;
2158        assert_eq!(
2159            python.interpreter().python_full_version().to_string(),
2160            "3.12.0",
2161            "We should find the parent interpreter"
2162        );
2163
2164        // Parent interpreters are preferred over virtual environments and system interpreters
2165        let venv = context.tempdir.child(".venv");
2166        TestContext::mock_venv(&venv, "3.12.2")?;
2167        context.add_python_versions(&["3.12.3"])?;
2168        let python = context.run_with_vars(
2169            &[
2170                (
2171                    EnvVars::UV_INTERNAL__PARENT_INTERPRETER,
2172                    Some(parent.as_os_str()),
2173                ),
2174                (EnvVars::VIRTUAL_ENV, Some(venv.as_os_str())),
2175            ],
2176            || {
2177                find_python_installation(
2178                    &PythonRequest::Default,
2179                    EnvironmentPreference::Any,
2180                    PythonPreference::OnlySystem,
2181                    None,
2182                    &context.cache,
2183                )
2184            },
2185        )??;
2186        assert_eq!(
2187            python.interpreter().python_full_version().to_string(),
2188            "3.12.0",
2189            "We should prefer the parent interpreter"
2190        );
2191
2192        // Test with `EnvironmentPreference::ExplicitSystem`
2193        let python = context.run_with_vars(
2194            &[
2195                (
2196                    EnvVars::UV_INTERNAL__PARENT_INTERPRETER,
2197                    Some(parent.as_os_str()),
2198                ),
2199                (EnvVars::VIRTUAL_ENV, Some(venv.as_os_str())),
2200            ],
2201            || {
2202                find_python_installation(
2203                    &PythonRequest::Default,
2204                    EnvironmentPreference::ExplicitSystem,
2205                    PythonPreference::OnlySystem,
2206                    None,
2207                    &context.cache,
2208                )
2209            },
2210        )??;
2211        assert_eq!(
2212            python.interpreter().python_full_version().to_string(),
2213            "3.12.0",
2214            "We should prefer the parent interpreter"
2215        );
2216
2217        // Test with `EnvironmentPreference::OnlySystem`
2218        let python = context.run_with_vars(
2219            &[
2220                (
2221                    EnvVars::UV_INTERNAL__PARENT_INTERPRETER,
2222                    Some(parent.as_os_str()),
2223                ),
2224                (EnvVars::VIRTUAL_ENV, Some(venv.as_os_str())),
2225            ],
2226            || {
2227                find_python_installation(
2228                    &PythonRequest::Default,
2229                    EnvironmentPreference::OnlySystem,
2230                    PythonPreference::OnlySystem,
2231                    None,
2232                    &context.cache,
2233                )
2234            },
2235        )??;
2236        assert_eq!(
2237            python.interpreter().python_full_version().to_string(),
2238            "3.12.0",
2239            "We should prefer the parent interpreter since it's not virtual"
2240        );
2241
2242        // Test with `EnvironmentPreference::OnlyVirtual`
2243        let python = context.run_with_vars(
2244            &[
2245                (
2246                    EnvVars::UV_INTERNAL__PARENT_INTERPRETER,
2247                    Some(parent.as_os_str()),
2248                ),
2249                (EnvVars::VIRTUAL_ENV, Some(venv.as_os_str())),
2250            ],
2251            || {
2252                find_python_installation(
2253                    &PythonRequest::Default,
2254                    EnvironmentPreference::OnlyVirtual,
2255                    PythonPreference::OnlySystem,
2256                    None,
2257                    &context.cache,
2258                )
2259            },
2260        )??;
2261        assert_eq!(
2262            python.interpreter().python_full_version().to_string(),
2263            "3.12.2",
2264            "We find the virtual environment Python because a system is explicitly not allowed"
2265        );
2266
2267        Ok(())
2268    }
2269
2270    #[test]
2271    fn find_python_from_parent_interpreter_prerelease() -> Result<()> {
2272        let mut context = TestContext::new()?;
2273        context.add_python_versions(&["3.12.0"])?;
2274        let parent = context.tempdir.child("python").to_path_buf();
2275        TestContext::create_mock_interpreter(
2276            &parent,
2277            &PythonVersion::from_str("3.13.0rc2").unwrap(),
2278            ImplementationName::CPython,
2279            // Note we mark this as a system interpreter instead of a virtual environment
2280            true,
2281            false,
2282        )?;
2283
2284        let python = context.run_with_vars(
2285            &[(
2286                EnvVars::UV_INTERNAL__PARENT_INTERPRETER,
2287                Some(parent.as_os_str()),
2288            )],
2289            || {
2290                find_python_installation(
2291                    &PythonRequest::Default,
2292                    EnvironmentPreference::Any,
2293                    PythonPreference::OnlySystem,
2294                    None,
2295                    &context.cache,
2296                )
2297            },
2298        )??;
2299        assert_eq!(
2300            python.interpreter().python_full_version().to_string(),
2301            "3.13.0rc2",
2302            "We should find the parent interpreter"
2303        );
2304
2305        Ok(())
2306    }
2307
2308    #[test]
2309    fn find_python_active_python_skipped_if_system_required() -> Result<()> {
2310        let mut context = TestContext::new()?;
2311        let venv = context.tempdir.child(".venv");
2312        TestContext::mock_venv(&venv, "3.9.0")?;
2313        context.add_python_versions(&["3.10.0", "3.11.1", "3.12.2"])?;
2314
2315        // Without a specific request
2316        let python =
2317            context.run_with_vars(&[(EnvVars::VIRTUAL_ENV, Some(venv.as_os_str()))], || {
2318                find_python_installation(
2319                    &PythonRequest::Default,
2320                    EnvironmentPreference::OnlySystem,
2321                    PythonPreference::OnlySystem,
2322                    None,
2323                    &context.cache,
2324                )
2325            })??;
2326        assert_eq!(
2327            python.interpreter().python_full_version().to_string(),
2328            "3.10.0",
2329            "We should skip the active environment"
2330        );
2331
2332        // With a requested minor version
2333        let python =
2334            context.run_with_vars(&[(EnvVars::VIRTUAL_ENV, Some(venv.as_os_str()))], || {
2335                find_python_installation(
2336                    &parse_request("3.12"),
2337                    EnvironmentPreference::OnlySystem,
2338                    PythonPreference::OnlySystem,
2339                    None,
2340                    &context.cache,
2341                )
2342            })??;
2343        assert_eq!(
2344            python.interpreter().python_full_version().to_string(),
2345            "3.12.2",
2346            "We should skip the active environment"
2347        );
2348
2349        // With a patch version that cannot be python
2350        let result =
2351            context.run_with_vars(&[(EnvVars::VIRTUAL_ENV, Some(venv.as_os_str()))], || {
2352                find_python_installation(
2353                    &parse_request("3.12.3"),
2354                    EnvironmentPreference::OnlySystem,
2355                    PythonPreference::OnlySystem,
2356                    None,
2357                    &context.cache,
2358                )
2359            })?;
2360        assert!(
2361            result.is_err(),
2362            "We should not find an python; got {result:?}"
2363        );
2364
2365        Ok(())
2366    }
2367
2368    #[test]
2369    fn find_python_fails_if_no_virtualenv_and_system_not_allowed() -> Result<()> {
2370        let mut context = TestContext::new()?;
2371        context.add_python_versions(&["3.10.1", "3.11.2"])?;
2372
2373        let result = context.run(|| {
2374            find_python_installation(
2375                &PythonRequest::Default,
2376                EnvironmentPreference::OnlyVirtual,
2377                PythonPreference::OnlySystem,
2378                None,
2379                &context.cache,
2380            )
2381        })?;
2382        assert_matches!(
2383            result,
2384            Err(PythonNotFound { .. }),
2385            "We should not find an python; got {result:?}"
2386        );
2387
2388        // With an invalid virtual environment variable
2389        let result = context.run_with_vars(
2390            &[(EnvVars::VIRTUAL_ENV, Some(context.tempdir.as_os_str()))],
2391            || {
2392                find_python_installation(
2393                    &parse_request("3.12.3"),
2394                    EnvironmentPreference::OnlySystem,
2395                    PythonPreference::OnlySystem,
2396                    None,
2397                    &context.cache,
2398                )
2399            },
2400        )?;
2401        assert_matches!(
2402            result,
2403            Err(PythonNotFound { .. }),
2404            "We should not find an python; got {result:?}"
2405        );
2406        Ok(())
2407    }
2408
2409    #[cfg(unix)]
2410    #[test]
2411    fn find_python_does_not_traverse_broken_child_virtualenv() -> Result<()> {
2412        let context = TestContext::new()?;
2413
2414        let parent_venv = context.tempdir.child(".venv");
2415        TestContext::mock_venv(&parent_venv, "3.12.0")?;
2416        let child_venv = context.workdir.child(".venv");
2417        fs_err::os::unix::fs::symlink(context.workdir.child("missing"), &child_venv)?;
2418
2419        let result = context.run(|| {
2420            find_python_installation(
2421                &PythonRequest::Default,
2422                EnvironmentPreference::OnlyVirtual,
2423                PythonPreference::OnlySystem,
2424                None,
2425                &context.cache,
2426            )
2427        });
2428        assert_matches!(
2429                &result,
2430                Err(discovery::Error::VirtualEnv(
2431                    uv_python_interpreter::VirtualEnvError::MissingPyVenvCfg(path)
2432                )) if path == child_venv.path()
2433            ,
2434            "A broken symlink at `.venv` should be eagerly rejected; got {result:?}"
2435        );
2436
2437        Ok(())
2438    }
2439
2440    #[test]
2441    fn find_python_propagates_virtualenv_metadata_errors() -> Result<()> {
2442        let context = TestContext::new()?;
2443
2444        let permissions = fs_err::metadata(&context.workdir)?.permissions();
2445        fs_err::set_permissions(&context.workdir, Permissions::from_mode(0o000))?;
2446        let result = context.run(|| {
2447            find_python_installation(
2448                &PythonRequest::Default,
2449                EnvironmentPreference::OnlyVirtual,
2450                PythonPreference::OnlySystem,
2451                None,
2452                &context.cache,
2453            )
2454        });
2455        fs_err::set_permissions(&context.workdir, permissions)?;
2456
2457        assert_matches!(
2458                &result,
2459                Err(discovery::Error::VirtualEnv(uv_python_interpreter::VirtualEnvError::Io(error)))
2460                    if error.kind() == io::ErrorKind::PermissionDenied
2461            ,
2462            "A virtual environment metadata error should not be ignored; got {result:?}"
2463        );
2464
2465        Ok(())
2466    }
2467
2468    #[test]
2469    fn find_python_allows_name_in_working_directory() -> Result<()> {
2470        let context = TestContext::new()?;
2471        context.add_python_to_workdir("foobar", "3.10.0")?;
2472
2473        let python = context.run(|| {
2474            find_python_installation(
2475                &parse_request("foobar"),
2476                EnvironmentPreference::Any,
2477                PythonPreference::OnlySystem,
2478                None,
2479                &context.cache,
2480            )
2481        })??;
2482        assert_eq!(
2483            python.interpreter().python_full_version().to_string(),
2484            "3.10.0",
2485            "We should find the named executable"
2486        );
2487
2488        let result = context.run(|| {
2489            find_python_installation(
2490                &PythonRequest::Default,
2491                EnvironmentPreference::Any,
2492                PythonPreference::OnlySystem,
2493                None,
2494                &context.cache,
2495            )
2496        })?;
2497        assert_matches!(
2498            result,
2499            Err(PythonNotFound { .. }),
2500            "We should not find it without a specific request"
2501        );
2502
2503        let result = context.run(|| {
2504            find_python_installation(
2505                &parse_request("3.10.0"),
2506                EnvironmentPreference::Any,
2507                PythonPreference::OnlySystem,
2508                None,
2509                &context.cache,
2510            )
2511        })?;
2512        assert_matches!(
2513            result,
2514            Err(PythonNotFound { .. }),
2515            "We should not find it via a matching version request"
2516        );
2517
2518        Ok(())
2519    }
2520
2521    #[test]
2522    fn find_python_allows_relative_file_path() -> Result<()> {
2523        let mut context = TestContext::new()?;
2524        let python = context.workdir.child("foo").join("bar");
2525        TestContext::create_mock_interpreter(
2526            &python,
2527            &PythonVersion::from_str("3.10.0").unwrap(),
2528            ImplementationName::default(),
2529            true,
2530            false,
2531        )?;
2532
2533        let python = context.run(|| {
2534            find_python_installation(
2535                &parse_request("./foo/bar"),
2536                EnvironmentPreference::Any,
2537                PythonPreference::OnlySystem,
2538                None,
2539                &context.cache,
2540            )
2541        })??;
2542        assert_eq!(
2543            python.interpreter().python_full_version().to_string(),
2544            "3.10.0",
2545            "We should find the `bar` executable"
2546        );
2547
2548        context.add_python_versions(&["3.11.1"])?;
2549        let python = context.run(|| {
2550            find_python_installation(
2551                &parse_request("./foo/bar"),
2552                EnvironmentPreference::Any,
2553                PythonPreference::OnlySystem,
2554                None,
2555                &context.cache,
2556            )
2557        })??;
2558        assert_eq!(
2559            python.interpreter().python_full_version().to_string(),
2560            "3.10.0",
2561            "We should prefer the `bar` executable over the system and virtualenvs"
2562        );
2563
2564        Ok(())
2565    }
2566
2567    #[test]
2568    fn find_python_allows_absolute_file_path() -> Result<()> {
2569        let mut context = TestContext::new()?;
2570        let python_path = context.tempdir.child("foo").join("bar");
2571        TestContext::create_mock_interpreter(
2572            &python_path,
2573            &PythonVersion::from_str("3.10.0").unwrap(),
2574            ImplementationName::default(),
2575            true,
2576            false,
2577        )?;
2578
2579        let python = context.run(|| {
2580            find_python_installation(
2581                &parse_request(python_path.to_str().unwrap()),
2582                EnvironmentPreference::Any,
2583                PythonPreference::OnlySystem,
2584                None,
2585                &context.cache,
2586            )
2587        })??;
2588        assert_eq!(
2589            python.interpreter().python_full_version().to_string(),
2590            "3.10.0",
2591            "We should find the `bar` executable"
2592        );
2593
2594        // With `EnvironmentPreference::ExplicitSystem`
2595        let python = context.run(|| {
2596            find_python_installation(
2597                &parse_request(python_path.to_str().unwrap()),
2598                EnvironmentPreference::ExplicitSystem,
2599                PythonPreference::OnlySystem,
2600                None,
2601                &context.cache,
2602            )
2603        })??;
2604        assert_eq!(
2605            python.interpreter().python_full_version().to_string(),
2606            "3.10.0",
2607            "We should allow the `bar` executable with explicit system"
2608        );
2609
2610        // With `EnvironmentPreference::OnlyVirtual`
2611        let python = context.run(|| {
2612            find_python_installation(
2613                &parse_request(python_path.to_str().unwrap()),
2614                EnvironmentPreference::OnlyVirtual,
2615                PythonPreference::OnlySystem,
2616                None,
2617                &context.cache,
2618            )
2619        })??;
2620        assert_eq!(
2621            python.interpreter().python_full_version().to_string(),
2622            "3.10.0",
2623            "We should allow the `bar` executable and verify it is virtual"
2624        );
2625
2626        context.add_python_versions(&["3.11.1"])?;
2627        let python = context.run(|| {
2628            find_python_installation(
2629                &parse_request(python_path.to_str().unwrap()),
2630                EnvironmentPreference::Any,
2631                PythonPreference::OnlySystem,
2632                None,
2633                &context.cache,
2634            )
2635        })??;
2636        assert_eq!(
2637            python.interpreter().python_full_version().to_string(),
2638            "3.10.0",
2639            "We should prefer the `bar` executable over the system and virtualenvs"
2640        );
2641
2642        Ok(())
2643    }
2644
2645    #[test]
2646    fn find_python_allows_venv_directory_path() -> Result<()> {
2647        let mut context = TestContext::new()?;
2648
2649        let venv = context.tempdir.child("foo").child(".venv");
2650        TestContext::mock_venv(&venv, "3.10.0")?;
2651        let python = context.run(|| {
2652            find_python_installation(
2653                &parse_request("../foo/.venv"),
2654                EnvironmentPreference::Any,
2655                PythonPreference::OnlySystem,
2656                None,
2657                &context.cache,
2658            )
2659        })??;
2660        assert_eq!(
2661            python.interpreter().python_full_version().to_string(),
2662            "3.10.0",
2663            "We should find the relative venv path"
2664        );
2665
2666        let python = context.run(|| {
2667            find_python_installation(
2668                &parse_request(venv.to_str().unwrap()),
2669                EnvironmentPreference::Any,
2670                PythonPreference::OnlySystem,
2671                None,
2672                &context.cache,
2673            )
2674        })??;
2675        assert_eq!(
2676            python.interpreter().python_full_version().to_string(),
2677            "3.10.0",
2678            "We should find the absolute venv path"
2679        );
2680
2681        // We should allow it to be a directory that _looks_ like a virtual environment.
2682        let python_path = context.tempdir.child("bar").join("bin").join("python");
2683        TestContext::create_mock_interpreter(
2684            &python_path,
2685            &PythonVersion::from_str("3.10.0").unwrap(),
2686            ImplementationName::default(),
2687            true,
2688            false,
2689        )?;
2690        let python = context.run(|| {
2691            find_python_installation(
2692                &parse_request(context.tempdir.child("bar").to_str().unwrap()),
2693                EnvironmentPreference::Any,
2694                PythonPreference::OnlySystem,
2695                None,
2696                &context.cache,
2697            )
2698        })??;
2699        assert_eq!(
2700            python.interpreter().python_full_version().to_string(),
2701            "3.10.0",
2702            "We should find the executable in the directory"
2703        );
2704
2705        let other_venv = context.tempdir.child("foobar").child(".venv");
2706        TestContext::mock_venv(&other_venv, "3.11.1")?;
2707        context.add_python_versions(&["3.12.2"])?;
2708        let python = context.run_with_vars(
2709            &[(EnvVars::VIRTUAL_ENV, Some(other_venv.as_os_str()))],
2710            || {
2711                find_python_installation(
2712                    &parse_request(venv.to_str().unwrap()),
2713                    EnvironmentPreference::Any,
2714                    PythonPreference::OnlySystem,
2715                    None,
2716                    &context.cache,
2717                )
2718            },
2719        )??;
2720        assert_eq!(
2721            python.interpreter().python_full_version().to_string(),
2722            "3.10.0",
2723            "We should prefer the requested directory over the system and active virtual environments"
2724        );
2725
2726        Ok(())
2727    }
2728
2729    #[test]
2730    fn find_python_venv_symlink() -> Result<()> {
2731        let context = TestContext::new()?;
2732
2733        let venv = context.tempdir.child("target").child("env");
2734        TestContext::mock_venv(&venv, "3.10.6")?;
2735        let symlink = context.tempdir.child("proj").child(".venv");
2736        context.tempdir.child("proj").create_dir_all()?;
2737        symlink.symlink_to_dir(venv)?;
2738
2739        let python = context.run(|| {
2740            find_python_installation(
2741                &parse_request("../proj/.venv"),
2742                EnvironmentPreference::Any,
2743                PythonPreference::OnlySystem,
2744                None,
2745                &context.cache,
2746            )
2747        })??;
2748        assert_eq!(
2749            python.interpreter().python_full_version().to_string(),
2750            "3.10.6",
2751            "We should find the symlinked venv"
2752        );
2753        Ok(())
2754    }
2755
2756    #[test]
2757    fn find_python_treats_missing_file_path_as_file() -> Result<()> {
2758        let context = TestContext::new()?;
2759        context.workdir.child("foo").create_dir_all()?;
2760
2761        let result = context.run(|| {
2762            find_python_installation(
2763                &parse_request("./foo/bar"),
2764                EnvironmentPreference::Any,
2765                PythonPreference::OnlySystem,
2766                None,
2767                &context.cache,
2768            )
2769        })?;
2770        assert_matches!(
2771            result,
2772            Err(PythonNotFound { .. }),
2773            "We should not find the file; got {result:?}"
2774        );
2775
2776        Ok(())
2777    }
2778
2779    #[test]
2780    fn find_python_executable_name_in_search_path() -> Result<()> {
2781        let mut context = TestContext::new()?;
2782        let python = context.tempdir.child("foo").join("bar");
2783        TestContext::create_mock_interpreter(
2784            &python,
2785            &PythonVersion::from_str("3.10.0").unwrap(),
2786            ImplementationName::default(),
2787            true,
2788            false,
2789        )?;
2790        context.add_to_search_path(context.tempdir.child("foo").to_path_buf());
2791
2792        let python = context.run(|| {
2793            find_python_installation(
2794                &parse_request("bar"),
2795                EnvironmentPreference::Any,
2796                PythonPreference::OnlySystem,
2797                None,
2798                &context.cache,
2799            )
2800        })??;
2801        assert_eq!(
2802            python.interpreter().python_full_version().to_string(),
2803            "3.10.0",
2804            "We should find the `bar` executable"
2805        );
2806
2807        // With [`EnvironmentPreference::OnlyVirtual`], we should not allow the interpreter
2808        let result = context.run(|| {
2809            find_python_installation(
2810                &parse_request("bar"),
2811                EnvironmentPreference::ExplicitSystem,
2812                PythonPreference::OnlySystem,
2813                None,
2814                &context.cache,
2815            )
2816        })?;
2817        assert_matches!(
2818            result,
2819            Err(PythonNotFound { .. }),
2820            "We should not allow a system interpreter; got {result:?}"
2821        );
2822
2823        // Unless it's a virtual environment interpreter
2824        let mut context = TestContext::new()?;
2825        let python = context.tempdir.child("foo").join("bar");
2826        TestContext::create_mock_interpreter(
2827            &python,
2828            &PythonVersion::from_str("3.10.0").unwrap(),
2829            ImplementationName::default(),
2830            false, // Not a system interpreter
2831            false,
2832        )?;
2833        context.add_to_search_path(context.tempdir.child("foo").to_path_buf());
2834
2835        let python = context
2836            .run(|| {
2837                find_python_installation(
2838                    &parse_request("bar"),
2839                    EnvironmentPreference::ExplicitSystem,
2840                    PythonPreference::OnlySystem,
2841                    None,
2842                    &context.cache,
2843                )
2844            })
2845            .unwrap()
2846            .unwrap();
2847        assert_eq!(
2848            python.interpreter().python_full_version().to_string(),
2849            "3.10.0",
2850            "We should find the `bar` executable"
2851        );
2852
2853        Ok(())
2854    }
2855
2856    #[test]
2857    fn find_python_pypy() -> Result<()> {
2858        let mut context = TestContext::new()?;
2859
2860        context.add_python_interpreters(&[(true, ImplementationName::PyPy, "pypy", "3.10.0")])?;
2861        let result = context.run(|| {
2862            find_python_installation(
2863                &PythonRequest::Default,
2864                EnvironmentPreference::Any,
2865                PythonPreference::OnlySystem,
2866                None,
2867                &context.cache,
2868            )
2869        })?;
2870        assert_matches!(
2871            result,
2872            Err(PythonNotFound { .. }),
2873            "We should not find the pypy interpreter if not named `python` or requested; got {result:?}"
2874        );
2875
2876        // But we should find it
2877        context.reset_search_path();
2878        context.add_python_interpreters(&[(true, ImplementationName::PyPy, "python", "3.10.1")])?;
2879        let python = context.run(|| {
2880            find_python_installation(
2881                &PythonRequest::Default,
2882                EnvironmentPreference::Any,
2883                PythonPreference::OnlySystem,
2884                None,
2885                &context.cache,
2886            )
2887        })??;
2888        assert_eq!(
2889            python.interpreter().python_full_version().to_string(),
2890            "3.10.1",
2891            "We should find the pypy interpreter if it's the only one"
2892        );
2893
2894        let python = context.run(|| {
2895            find_python_installation(
2896                &parse_request("pypy"),
2897                EnvironmentPreference::Any,
2898                PythonPreference::OnlySystem,
2899                None,
2900                &context.cache,
2901            )
2902        })??;
2903        assert_eq!(
2904            python.interpreter().python_full_version().to_string(),
2905            "3.10.1",
2906            "We should find the pypy interpreter if it's requested"
2907        );
2908
2909        Ok(())
2910    }
2911
2912    #[test]
2913    fn find_python_pypy_request_ignores_cpython() -> Result<()> {
2914        let mut context = TestContext::new()?;
2915        context.add_python_interpreters(&[
2916            (true, ImplementationName::CPython, "python", "3.10.0"),
2917            (true, ImplementationName::PyPy, "pypy", "3.10.1"),
2918        ])?;
2919
2920        let python = context.run(|| {
2921            find_python_installation(
2922                &parse_request("pypy"),
2923                EnvironmentPreference::Any,
2924                PythonPreference::OnlySystem,
2925                None,
2926                &context.cache,
2927            )
2928        })??;
2929        assert_eq!(
2930            python.interpreter().python_full_version().to_string(),
2931            "3.10.1",
2932            "We should skip the CPython interpreter"
2933        );
2934
2935        let python = context.run(|| {
2936            find_python_installation(
2937                &PythonRequest::Default,
2938                EnvironmentPreference::Any,
2939                PythonPreference::OnlySystem,
2940                None,
2941                &context.cache,
2942            )
2943        })??;
2944        assert_eq!(
2945            python.interpreter().python_full_version().to_string(),
2946            "3.10.0",
2947            "We should take the first interpreter without a specific request"
2948        );
2949
2950        Ok(())
2951    }
2952
2953    #[test]
2954    fn find_python_pypy_request_skips_wrong_versions() -> Result<()> {
2955        let mut context = TestContext::new()?;
2956        context.add_python_interpreters(&[
2957            (true, ImplementationName::PyPy, "pypy", "3.9"),
2958            (true, ImplementationName::PyPy, "pypy", "3.10.1"),
2959        ])?;
2960
2961        let python = context.run(|| {
2962            find_python_installation(
2963                &parse_request("pypy3.10"),
2964                EnvironmentPreference::Any,
2965                PythonPreference::OnlySystem,
2966                None,
2967                &context.cache,
2968            )
2969        })??;
2970        assert_eq!(
2971            python.interpreter().python_full_version().to_string(),
2972            "3.10.1",
2973            "We should skip the first interpreter"
2974        );
2975
2976        Ok(())
2977    }
2978
2979    #[test]
2980    fn find_python_pypy_finds_executable_with_version_name() -> Result<()> {
2981        let mut context = TestContext::new()?;
2982        context.add_python_interpreters(&[
2983            (true, ImplementationName::PyPy, "pypy3.9", "3.10.0"), // We don't consider this one because of the executable name
2984            (true, ImplementationName::PyPy, "pypy3.10", "3.10.1"),
2985            (true, ImplementationName::PyPy, "pypy", "3.10.2"),
2986        ])?;
2987
2988        let python = context.run(|| {
2989            find_python_installation(
2990                &parse_request("pypy@3.10"),
2991                EnvironmentPreference::Any,
2992                PythonPreference::OnlySystem,
2993                None,
2994                &context.cache,
2995            )
2996        })??;
2997        assert_eq!(
2998            python.interpreter().python_full_version().to_string(),
2999            "3.10.1",
3000            "We should find the requested interpreter version"
3001        );
3002
3003        Ok(())
3004    }
3005
3006    #[test]
3007    fn find_python_all_minors() -> Result<()> {
3008        let mut context = TestContext::new()?;
3009        context.add_python_interpreters(&[
3010            (true, ImplementationName::CPython, "python", "3.10.0"),
3011            (true, ImplementationName::CPython, "python3", "3.10.0"),
3012            (true, ImplementationName::CPython, "python3.12", "3.12.0"),
3013        ])?;
3014
3015        let python = context.run(|| {
3016            find_python_installation(
3017                &parse_request(">= 3.11"),
3018                EnvironmentPreference::Any,
3019                PythonPreference::OnlySystem,
3020                None,
3021                &context.cache,
3022            )
3023        })??;
3024        assert_eq!(
3025            python.interpreter().python_full_version().to_string(),
3026            "3.12.0",
3027            "We should find matching minor version even if they aren't called `python` or `python3`"
3028        );
3029
3030        Ok(())
3031    }
3032
3033    #[test]
3034    fn find_python_all_minors_prerelease() -> Result<()> {
3035        let mut context = TestContext::new()?;
3036        context.add_python_interpreters(&[
3037            (true, ImplementationName::CPython, "python", "3.10.0"),
3038            (true, ImplementationName::CPython, "python3", "3.10.0"),
3039            (true, ImplementationName::CPython, "python3.11", "3.11.0b0"),
3040        ])?;
3041
3042        let python = context.run(|| {
3043            find_python_installation(
3044                &parse_request(">= 3.11"),
3045                EnvironmentPreference::Any,
3046                PythonPreference::OnlySystem,
3047                None,
3048                &context.cache,
3049            )
3050        })??;
3051        assert_eq!(
3052            python.interpreter().python_full_version().to_string(),
3053            "3.11.0b0",
3054            "We should find the 3.11 prerelease even though >=3.11 would normally exclude prereleases"
3055        );
3056
3057        Ok(())
3058    }
3059
3060    #[test]
3061    fn find_python_all_minors_prerelease_next() -> Result<()> {
3062        let mut context = TestContext::new()?;
3063        context.add_python_interpreters(&[
3064            (true, ImplementationName::CPython, "python", "3.10.0"),
3065            (true, ImplementationName::CPython, "python3", "3.10.0"),
3066            (true, ImplementationName::CPython, "python3.12", "3.12.0b0"),
3067        ])?;
3068
3069        let python = context.run(|| {
3070            find_python_installation(
3071                &parse_request(">= 3.11"),
3072                EnvironmentPreference::Any,
3073                PythonPreference::OnlySystem,
3074                None,
3075                &context.cache,
3076            )
3077        })??;
3078        assert_eq!(
3079            python.interpreter().python_full_version().to_string(),
3080            "3.12.0b0",
3081            "We should find the 3.12 prerelease"
3082        );
3083
3084        Ok(())
3085    }
3086
3087    #[test]
3088    fn find_python_graalpy() -> Result<()> {
3089        let mut context = TestContext::new()?;
3090
3091        context.add_python_interpreters(&[(
3092            true,
3093            ImplementationName::GraalPy,
3094            "graalpy",
3095            "3.10.0",
3096        )])?;
3097        let result = context.run(|| {
3098            find_python_installation(
3099                &PythonRequest::Default,
3100                EnvironmentPreference::Any,
3101                PythonPreference::OnlySystem,
3102                None,
3103                &context.cache,
3104            )
3105        })?;
3106        assert_matches!(
3107            result,
3108            Err(PythonNotFound { .. }),
3109            "We should not the graalpy interpreter if not named `python` or requested; got {result:?}"
3110        );
3111
3112        // But we should find it
3113        context.reset_search_path();
3114        context.add_python_interpreters(&[(
3115            true,
3116            ImplementationName::GraalPy,
3117            "python",
3118            "3.10.1",
3119        )])?;
3120        let python = context.run(|| {
3121            find_python_installation(
3122                &PythonRequest::Default,
3123                EnvironmentPreference::Any,
3124                PythonPreference::OnlySystem,
3125                None,
3126                &context.cache,
3127            )
3128        })??;
3129        assert_eq!(
3130            python.interpreter().python_full_version().to_string(),
3131            "3.10.1",
3132            "We should find the graalpy interpreter if it's the only one"
3133        );
3134
3135        let python = context.run(|| {
3136            find_python_installation(
3137                &parse_request("graalpy"),
3138                EnvironmentPreference::Any,
3139                PythonPreference::OnlySystem,
3140                None,
3141                &context.cache,
3142            )
3143        })??;
3144        assert_eq!(
3145            python.interpreter().python_full_version().to_string(),
3146            "3.10.1",
3147            "We should find the graalpy interpreter if it's requested"
3148        );
3149
3150        Ok(())
3151    }
3152
3153    #[test]
3154    fn find_python_graalpy_request_ignores_cpython() -> Result<()> {
3155        let mut context = TestContext::new()?;
3156        context.add_python_interpreters(&[
3157            (true, ImplementationName::CPython, "python", "3.10.0"),
3158            (true, ImplementationName::GraalPy, "graalpy", "3.10.1"),
3159        ])?;
3160
3161        let python = context.run(|| {
3162            find_python_installation(
3163                &parse_request("graalpy"),
3164                EnvironmentPreference::Any,
3165                PythonPreference::OnlySystem,
3166                None,
3167                &context.cache,
3168            )
3169        })??;
3170        assert_eq!(
3171            python.interpreter().python_full_version().to_string(),
3172            "3.10.1",
3173            "We should skip the CPython interpreter"
3174        );
3175
3176        let python = context.run(|| {
3177            find_python_installation(
3178                &PythonRequest::Default,
3179                EnvironmentPreference::Any,
3180                PythonPreference::OnlySystem,
3181                None,
3182                &context.cache,
3183            )
3184        })??;
3185        assert_eq!(
3186            python.interpreter().python_full_version().to_string(),
3187            "3.10.0",
3188            "We should take the first interpreter without a specific request"
3189        );
3190
3191        Ok(())
3192    }
3193
3194    #[test]
3195    fn find_python_executable_name_preference() -> Result<()> {
3196        let mut context = TestContext::new()?;
3197        TestContext::create_mock_interpreter(
3198            &context.tempdir.join("pypy3.10"),
3199            &PythonVersion::from_str("3.10.0").unwrap(),
3200            ImplementationName::PyPy,
3201            true,
3202            false,
3203        )?;
3204        TestContext::create_mock_interpreter(
3205            &context.tempdir.join("pypy"),
3206            &PythonVersion::from_str("3.10.1").unwrap(),
3207            ImplementationName::PyPy,
3208            true,
3209            false,
3210        )?;
3211        context.add_to_search_path(context.tempdir.to_path_buf());
3212
3213        let python = context
3214            .run(|| {
3215                find_python_installation(
3216                    &parse_request("pypy@3.10"),
3217                    EnvironmentPreference::Any,
3218                    PythonPreference::OnlySystem,
3219                    None,
3220                    &context.cache,
3221                )
3222            })
3223            .unwrap()
3224            .unwrap();
3225        assert_eq!(
3226            python.interpreter().python_full_version().to_string(),
3227            "3.10.0",
3228            "We should prefer the versioned one when a version is requested"
3229        );
3230
3231        let python = context
3232            .run(|| {
3233                find_python_installation(
3234                    &parse_request("pypy"),
3235                    EnvironmentPreference::Any,
3236                    PythonPreference::OnlySystem,
3237                    None,
3238                    &context.cache,
3239                )
3240            })
3241            .unwrap()
3242            .unwrap();
3243        assert_eq!(
3244            python.interpreter().python_full_version().to_string(),
3245            "3.10.1",
3246            "We should prefer the generic one when no version is requested"
3247        );
3248
3249        let mut context = TestContext::new()?;
3250        TestContext::create_mock_interpreter(
3251            &context.tempdir.join("python3.10"),
3252            &PythonVersion::from_str("3.10.0").unwrap(),
3253            ImplementationName::PyPy,
3254            true,
3255            false,
3256        )?;
3257        TestContext::create_mock_interpreter(
3258            &context.tempdir.join("pypy"),
3259            &PythonVersion::from_str("3.10.1").unwrap(),
3260            ImplementationName::PyPy,
3261            true,
3262            false,
3263        )?;
3264        TestContext::create_mock_interpreter(
3265            &context.tempdir.join("python"),
3266            &PythonVersion::from_str("3.10.2").unwrap(),
3267            ImplementationName::PyPy,
3268            true,
3269            false,
3270        )?;
3271        context.add_to_search_path(context.tempdir.to_path_buf());
3272
3273        let python = context
3274            .run(|| {
3275                find_python_installation(
3276                    &parse_request("pypy@3.10"),
3277                    EnvironmentPreference::Any,
3278                    PythonPreference::OnlySystem,
3279                    None,
3280                    &context.cache,
3281                )
3282            })
3283            .unwrap()
3284            .unwrap();
3285        assert_eq!(
3286            python.interpreter().python_full_version().to_string(),
3287            "3.10.1",
3288            "We should prefer the implementation name over the generic name"
3289        );
3290
3291        let python = context
3292            .run(|| {
3293                find_python_installation(
3294                    &parse_request("default"),
3295                    EnvironmentPreference::Any,
3296                    PythonPreference::OnlySystem,
3297                    None,
3298                    &context.cache,
3299                )
3300            })
3301            .unwrap()
3302            .unwrap();
3303        assert_eq!(
3304            python.interpreter().python_full_version().to_string(),
3305            "3.10.2",
3306            "We should prefer the generic name over the implementation name, but not the versioned name"
3307        );
3308
3309        // We prefer `python` executables over `graalpy` executables in the same directory
3310        // if they are both GraalPy
3311        let mut context = TestContext::new()?;
3312        TestContext::create_mock_interpreter(
3313            &context.tempdir.join("python"),
3314            &PythonVersion::from_str("3.10.0").unwrap(),
3315            ImplementationName::GraalPy,
3316            true,
3317            false,
3318        )?;
3319        TestContext::create_mock_interpreter(
3320            &context.tempdir.join("graalpy"),
3321            &PythonVersion::from_str("3.10.1").unwrap(),
3322            ImplementationName::GraalPy,
3323            true,
3324            false,
3325        )?;
3326        context.add_to_search_path(context.tempdir.to_path_buf());
3327
3328        let python = context
3329            .run(|| {
3330                find_python_installation(
3331                    &parse_request("graalpy@3.10"),
3332                    EnvironmentPreference::Any,
3333                    PythonPreference::OnlySystem,
3334                    None,
3335                    &context.cache,
3336                )
3337            })
3338            .unwrap()
3339            .unwrap();
3340        assert_eq!(
3341            python.interpreter().python_full_version().to_string(),
3342            "3.10.1",
3343        );
3344
3345        // And `python` executables earlier in the search path will take precedence
3346        context.reset_search_path();
3347        context.add_python_interpreters(&[
3348            (true, ImplementationName::GraalPy, "python", "3.10.2"),
3349            (true, ImplementationName::GraalPy, "graalpy", "3.10.3"),
3350        ])?;
3351        let python = context
3352            .run(|| {
3353                find_python_installation(
3354                    &parse_request("graalpy@3.10"),
3355                    EnvironmentPreference::Any,
3356                    PythonPreference::OnlySystem,
3357                    None,
3358                    &context.cache,
3359                )
3360            })
3361            .unwrap()
3362            .unwrap();
3363        assert_eq!(
3364            python.interpreter().python_full_version().to_string(),
3365            "3.10.2",
3366        );
3367
3368        // And `graalpy` executables earlier in the search path will take precedence
3369        context.reset_search_path();
3370        context.add_python_interpreters(&[
3371            (true, ImplementationName::GraalPy, "graalpy", "3.10.3"),
3372            (true, ImplementationName::GraalPy, "python", "3.10.2"),
3373        ])?;
3374        let python = context
3375            .run(|| {
3376                find_python_installation(
3377                    &parse_request("graalpy@3.10"),
3378                    EnvironmentPreference::Any,
3379                    PythonPreference::OnlySystem,
3380                    None,
3381                    &context.cache,
3382                )
3383            })
3384            .unwrap()
3385            .unwrap();
3386        assert_eq!(
3387            python.interpreter().python_full_version().to_string(),
3388            "3.10.3",
3389        );
3390
3391        Ok(())
3392    }
3393
3394    #[test]
3395    fn find_python_version_free_threaded() -> Result<()> {
3396        let mut context = TestContext::new()?;
3397
3398        TestContext::create_mock_interpreter(
3399            &context.tempdir.join("python"),
3400            &PythonVersion::from_str("3.13.1").unwrap(),
3401            ImplementationName::CPython,
3402            true,
3403            false,
3404        )?;
3405        TestContext::create_mock_interpreter(
3406            &context.tempdir.join("python3.13t"),
3407            &PythonVersion::from_str("3.13.0").unwrap(),
3408            ImplementationName::CPython,
3409            true,
3410            true,
3411        )?;
3412        context.add_to_search_path(context.tempdir.to_path_buf());
3413
3414        let python = context.run(|| {
3415            find_python_installation(
3416                &parse_request("3.13t"),
3417                EnvironmentPreference::Any,
3418                PythonPreference::OnlySystem,
3419                None,
3420                &context.cache,
3421            )
3422        })??;
3423
3424        assert_matches!(
3425            python,
3426            PythonInstallation {
3427                source: PythonSource::SearchPathFirst,
3428                interpreter: _
3429            },
3430            "We should find a python; got {python:?}"
3431        );
3432        assert_eq!(
3433            &python.interpreter().python_full_version().to_string(),
3434            "3.13.0",
3435            "We should find the correct interpreter for the request"
3436        );
3437        assert!(
3438            &python.interpreter().gil_disabled(),
3439            "We should find a python without the GIL"
3440        );
3441
3442        Ok(())
3443    }
3444
3445    #[test]
3446    fn find_python_version_prefer_non_free_threaded() -> Result<()> {
3447        let mut context = TestContext::new()?;
3448
3449        TestContext::create_mock_interpreter(
3450            &context.tempdir.join("python"),
3451            &PythonVersion::from_str("3.13.0").unwrap(),
3452            ImplementationName::CPython,
3453            true,
3454            false,
3455        )?;
3456        TestContext::create_mock_interpreter(
3457            &context.tempdir.join("python3.13t"),
3458            &PythonVersion::from_str("3.13.0").unwrap(),
3459            ImplementationName::CPython,
3460            true,
3461            true,
3462        )?;
3463        context.add_to_search_path(context.tempdir.to_path_buf());
3464
3465        let python = context.run(|| {
3466            find_python_installation(
3467                &parse_request("3.13"),
3468                EnvironmentPreference::Any,
3469                PythonPreference::OnlySystem,
3470                None,
3471                &context.cache,
3472            )
3473        })??;
3474
3475        assert_matches!(
3476            python,
3477            PythonInstallation {
3478                source: PythonSource::SearchPathFirst,
3479                interpreter: _
3480            },
3481            "We should find a python; got {python:?}"
3482        );
3483        assert_eq!(
3484            &python.interpreter().python_full_version().to_string(),
3485            "3.13.0",
3486            "We should find the correct interpreter for the request"
3487        );
3488        assert!(
3489            !&python.interpreter().gil_disabled(),
3490            "We should prefer a python with the GIL"
3491        );
3492
3493        Ok(())
3494    }
3495
3496    #[test]
3497    fn find_python_pyodide() -> Result<()> {
3498        let mut context = TestContext::new()?;
3499
3500        context.add_pyodide_version("3.13.2")?;
3501
3502        // We should not find the Pyodide interpreter by default
3503        let result = context.run(|| {
3504            find_python_installation(
3505                &PythonRequest::Default,
3506                EnvironmentPreference::Any,
3507                PythonPreference::OnlySystem,
3508                None,
3509                &context.cache,
3510            )
3511        })?;
3512        assert!(
3513            result.is_err(),
3514            "We should not find an python; got {result:?}"
3515        );
3516
3517        // With `Any`, it should be discoverable
3518        let python = context.run(|| {
3519            find_python_installation(
3520                &PythonRequest::Any,
3521                EnvironmentPreference::Any,
3522                PythonPreference::OnlySystem,
3523                None,
3524                &context.cache,
3525            )
3526        })??;
3527        assert_eq!(
3528            python.interpreter().python_full_version().to_string(),
3529            "3.13.2"
3530        );
3531        assert!(
3532            python
3533                .interpreter()
3534                .matches_request(&PythonRequest::parse("pyodide"), &context.cache)
3535        );
3536        assert!(
3537            python
3538                .interpreter()
3539                .matches_request(&PythonRequest::parse("pyodide@3.13"), &context.cache)
3540        );
3541        assert!(
3542            !python
3543                .interpreter()
3544                .matches_request(&PythonRequest::parse("pyodide@3.12"), &context.cache)
3545        );
3546
3547        // We should prefer the native Python to the Pyodide Python
3548        context.add_python_versions(&["3.15.7"])?;
3549
3550        let python = context.run(|| {
3551            find_python_installation(
3552                &PythonRequest::Default,
3553                EnvironmentPreference::Any,
3554                PythonPreference::OnlySystem,
3555                None,
3556                &context.cache,
3557            )
3558        })??;
3559        assert_eq!(
3560            python.interpreter().python_full_version().to_string(),
3561            "3.15.7"
3562        );
3563        assert!(
3564            !python
3565                .interpreter()
3566                .matches_request(&PythonRequest::parse("pyodide"), &context.cache)
3567        );
3568        assert!(
3569            !python
3570                .interpreter()
3571                .matches_request(&PythonRequest::parse("pyodide@3.15"), &context.cache)
3572        );
3573
3574        Ok(())
3575    }
3576}