Blob Blame History Raw
From 58ff51c482ed40a6b38766c90954d7d3edcaa0fb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Miro=20Hron=C4=8Dok?= <miro@hroncok.cz>
Date: Mon, 8 Nov 2021 15:54:18 +0100
Subject: [PATCH] Fix test_custom_venv_install_scheme_is_prefered mocking if
 "venv" install scheme actually exists

The error this prevents was:

        """distutils.command.install

        Implements the Distutils 'install' command."""

        ...

        # Copy from sysconfig._INSTALL_SCHEMES
        for key in SCHEME_KEYS:
            for distutils_scheme_name, sys_scheme_name in (
                    ("unix_prefix", "posix_prefix"), ("unix_home", "posix_home"),
                    ("nt", "nt")):
                sys_key = key
    >           sys_scheme = sysconfig._INSTALL_SCHEMES[sys_scheme_name]
    E           KeyError: 'posix_home'
---
 tests/unit/discovery/py_info/test_py_info.py | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/tests/unit/discovery/py_info/test_py_info.py b/tests/unit/discovery/py_info/test_py_info.py
index 053a6f906..d4c4bba25 100644
--- a/tests/unit/discovery/py_info/test_py_info.py
+++ b/tests/unit/discovery/py_info/test_py_info.py
@@ -349,7 +349,6 @@ def test_custom_venv_install_scheme_is_prefered(mocker):
 
     if sys.version_info[0] == 2:
         sysconfig_install_schemes = _stringify_schemes_dict(sysconfig_install_schemes)
-    mocker.patch("sysconfig._INSTALL_SCHEMES", sysconfig_install_schemes)
 
     # On Python < 3.10, the distutils schemes are not derived from sysconfig schemes
     # So we mock them as well to assert the custom "venv" install scheme has priority
@@ -367,7 +366,15 @@ def test_custom_venv_install_scheme_is_prefered(mocker):
 
     if sys.version_info[0] == 2:
         distutils_schemes = _stringify_schemes_dict(distutils_schemes)
+
+    # We need to mock distutils first, so they don't see the mocked sysconfig,
+    # if imported for the first time.
+    # That can happen if the actual interpreter has the "venv" INSTALL_SCHEME
+    # and hence this is the first time we are touching distutils in this process.
+    # If distutils saw our mocked sysconfig INSTALL_SCHEMES, we would need
+    # to define all install schemes.
     mocker.patch("distutils.command.install.INSTALL_SCHEMES", distutils_schemes)
+    mocker.patch("sysconfig._INSTALL_SCHEMES", sysconfig_install_schemes)
 
     pyinfo = PythonInfo()
     pyver = "{}.{}".format(pyinfo.version_info.major, pyinfo.version_info.minor)