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