Skip to content

Commit 3d5de99

Browse files
authored
GH-128779: add test for venv --system-site-packages (#129462)
1 parent 1b72935 commit 3d5de99

1 file changed

Lines changed: 42 additions & 1 deletion

File tree

‎Lib/test/test_site.py‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,13 @@
1414
from test.support import captured_stderr
1515
from test.support.os_helper import TESTFN, EnvironmentVarGuard
1616
from test.support.script_helper import spawn_python, kill_python
17+
from test.support.venv import VirtualEnvironmentMixin
1718
import ast
1819
import builtins
1920
import contextlib
2021
import glob
2122
import io
23+
import json
2224
import os
2325
import re
2426
import shutil
@@ -29,6 +31,7 @@
2931
import tempfile
3032
from textwrap import dedent
3133
from types import SimpleNamespace
34+
import textwrap
3235
import urllib.error
3336
import urllib.request
3437
from unittest import mock
@@ -485,7 +488,7 @@ def cleanup(self, prep=False):
485488
os.rmdir(self.bad_dir_path)
486489

487490

488-
class ImportSideEffectTests(unittest.TestCase):
491+
class ImportSideEffectTests(unittest.TestCase, VirtualEnvironmentMixin):
489492
"""Test side-effects from importing 'site'."""
490493

491494
def setUp(self):
@@ -604,6 +607,44 @@ def test_lazy_imports(self):
604607
"textwrap",
605608
])
606609

610+
@support.requires_subprocess()
611+
def test_system_site_packages(self):
612+
script = textwrap.dedent("""
613+
import sys, json
614+
615+
print(json.dumps(
616+
sys.path,
617+
indent=2,
618+
))
619+
""")
620+
621+
# Use _get_preferred_schemes to find the system scheme, in case we are in a virtual environment
622+
system_scheme_name = sysconfig._get_preferred_schemes()['prefix']
623+
system_paths = sysconfig.get_paths(system_scheme_name)
624+
625+
with self.venv(system_site_packages=False) as venv:
626+
sys_path = json.loads(venv.run('-c', script).stdout)
627+
self.assertNotIn(system_paths['purelib'], sys_path)
628+
self.assertNotIn(system_paths['platlib'], sys_path)
629+
630+
# site.py only adds site directories that exist on disk
631+
# (addsitedir guards on os.path.isdir), so the system
632+
# site-packages can only be detected when the directories exist,
633+
# e.g. with an installed Python. Skip on in-tree builds where the
634+
# nominal install directories were never created (gh-128779).
635+
system_site_packages = {system_paths['purelib'],
636+
system_paths['platlib']}
637+
if not all(map(os.path.isdir, system_site_packages)):
638+
self.skipTest(
639+
f"system site-packages directories do not exist: "
640+
f"{sorted(system_site_packages)}"
641+
)
642+
643+
with self.venv(system_site_packages=True) as venv:
644+
sys_path = json.loads(venv.run('-c', script).stdout)
645+
self.assertIn(system_paths['purelib'], sys_path)
646+
self.assertIn(system_paths['platlib'], sys_path)
647+
607648

608649
class StartupImportTests(unittest.TestCase):
609650

0 commit comments

Comments
 (0)