diff --git a/docs/changelog.d/+backend-path-pythonpath.bugfix.rst b/docs/changelog.d/+backend-path-pythonpath.bugfix.rst new file mode 100644 index 0000000..dc68633 --- /dev/null +++ b/docs/changelog.d/+backend-path-pythonpath.bugfix.rst @@ -0,0 +1,2 @@ +Keep the caller's ``PYTHONPATH`` importable when ``SubprocessFrontend`` starts a backend that sets +``build-system.backend-path``; the in-tree paths now come first instead of replacing it. diff --git a/src/pyproject_api/_via_fresh_subprocess.py b/src/pyproject_api/_via_fresh_subprocess.py index e8b754a..a14606e 100644 --- a/src/pyproject_api/_via_fresh_subprocess.py +++ b/src/pyproject_api/_via_fresh_subprocess.py @@ -47,7 +47,8 @@ def __init__( def _send_msg(self, cmd: str, result_file: Path, msg: str) -> Generator[SubprocessCmdStatus, None, None]: # ruff:ignore[unused-method-argument] # mirrors the Frontend._send_msg signature env = os.environ.copy() if backend := os.pathsep.join(str(i) for i in self._backend_paths): - env["PYTHONPATH"] = backend + # backend-path goes first (PEP 517), but what the caller already put on PYTHONPATH must stay importable + env["PYTHONPATH"] = os.pathsep.join(filter(None, (backend, env.get("PYTHONPATH")))) process = Popen( # ruff:ignore[subprocess-without-shell-equals-true] # fixed argv, no shell args=[self.executable, *self.backend_args], stdout=PIPE, diff --git a/tests/pyproject_api/test_via_fresh_subprocess.py b/tests/pyproject_api/test_via_fresh_subprocess.py index 264c0b2..81fa566 100644 --- a/tests/pyproject_api/test_via_fresh_subprocess.py +++ b/tests/pyproject_api/test_via_fresh_subprocess.py @@ -56,3 +56,31 @@ def build_wheel(wheel_directory, config_settings=None, metadata_directory=None): # A failed cleanup test must not leave a live child process. process.kill() process.wait(timeout=10) + + +def test_backend_path_keeps_existing_pythonpath(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + deps: Final = tmp_path / "deps" + deps.mkdir() + (deps / "helper.py").write_text('NAME = "demo-1.0.tar.gz"\n', encoding="utf-8") + # same name as the in-tree backend, so it would shadow it if PYTHONPATH came before backend-path + (deps / "build_tester.py").write_text('raise ImportError("PYTHONPATH shadowed backend-path")\n', encoding="utf-8") + project: Final = tmp_path / "project" + (project / "_build").mkdir(parents=True) + (project / "pyproject.toml").write_text( + '[build-system]\nrequires=[]\nbuild-backend = "build_tester"\nbackend-path=["_build"]', encoding="utf-8" + ) + (project / "_build" / "build_tester.py").write_text( + dedent("""\ + import helper + + def build_sdist(sdist_directory, config_settings=None): + return helper.NAME + """), + encoding="utf-8", + ) + monkeypatch.setenv("PYTHONPATH", str(deps)) + + frontend: Final = SubprocessFrontend(*SubprocessFrontend.create_args_from_folder(project)[:-1]) + result: Final = frontend.build_sdist(tmp_path / "dist") + + assert result.sdist == tmp_path / "dist" / "demo-1.0.tar.gz"