diff --git a/src/pyproject_hooks/_in_process/_in_process.py b/src/pyproject_hooks/_in_process/_in_process.py index 49c4203..0645b0c 100644 --- a/src/pyproject_hooks/_in_process/_in_process.py +++ b/src/pyproject_hooks/_in_process/_in_process.py @@ -348,6 +348,13 @@ def main(): control_dir = sys.argv[2] if hook_name not in HOOK_NAMES: sys.exit("Unknown hook: %s" % hook_name) + + # Remove the parent directory from sys.path to avoid polluting the backend + # import namespace with this directory. + here = os.path.dirname(__file__) + if here in sys.path: + sys.path.remove(here) + hook = globals()[hook_name] hook_input = read_json(pjoin(control_dir, "input.json")) diff --git a/tests/samples/path-pollution/setup.py b/tests/samples/path-pollution/setup.py index 34347b2..dc4bd76 100644 --- a/tests/samples/path-pollution/setup.py +++ b/tests/samples/path-pollution/setup.py @@ -1,12 +1,12 @@ import json import sys -from os import environ, listdir, path +from os import environ, path from setuptools import setup -children = listdir(sys.path[0]) +captured_sys_path = sys.path out = path.join(environ["TEST_POLLUTION_OUTDIR"], "out.json") with open(out, "w") as f: - json.dump(children, f) + json.dump(captured_sys_path, f) setup() diff --git a/tests/test_call_hooks.py b/tests/test_call_hooks.py index da410b0..d92669e 100644 --- a/tests/test_call_hooks.py +++ b/tests/test_call_hooks.py @@ -16,6 +16,7 @@ UnsupportedOperation, default_subprocess_runner, ) +from pyproject_hooks._in_process import _in_proc_script_path as in_proc_script_path from tests.compat import tomllib SAMPLES_DIR = pjoin(dirname(abspath(__file__)), "samples") @@ -196,14 +197,11 @@ def test_path_pollution(): ): hooks.get_requires_for_build_wheel({}) with open(pjoin(outdir, "out.json")) as f: - children = json.load(f) - assert set(children) <= { - "__init__.py", - "__init__.pyc", - "_in_process.py", - "_in_process.pyc", - "__pycache__", - } + captured_sys_path = json.load(f) + + with in_proc_script_path() as path: + assert os.path.dirname(path) not in captured_sys_path + assert captured_sys_path[0] == BUILDSYS_PKGS def test_setup_py():