Skip to content

Commit 2ad0d93

Browse files
authored
env: remove entry in envs.toml if the venv does not exist anymore (#9286)
This helps to avoid inconsistent entries when recreating the venv with another Python patch version.
1 parent 0d7604a commit 2ad0d93

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/poetry/utils/env/env_manager.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,7 @@ def get(self, reload: bool = False) -> Env:
276276
).to_string()
277277

278278
env = None
279+
envs = None
279280
if self.envs_file.exists():
280281
envs = self.envs_file.read()
281282
env = envs.get(self.base_env_name)
@@ -310,6 +311,9 @@ def get(self, reload: bool = False) -> Env:
310311
venv = venv_path / name
311312

312313
if not venv.exists():
314+
if env and envs:
315+
del envs[self.base_env_name]
316+
self.envs_file.write(envs)
313317
return self.get_system_env()
314318

315319
return VirtualEnv(venv)

tests/utils/env/test_env_manager.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1237,6 +1237,49 @@ def mock_check_output(cmd: str, *args: Any, **kwargs: Any) -> str:
12371237
)
12381238

12391239

1240+
@pytest.mark.parametrize("is_inconsistent_entry", [False, True])
1241+
def test_create_venv_does_not_keep_inconsistent_envs_entry(
1242+
tmp_path: Path,
1243+
manager: EnvManager,
1244+
poetry: Poetry,
1245+
config: Config,
1246+
mocker: MockerFixture,
1247+
venv_name: str,
1248+
is_inconsistent_entry: bool,
1249+
) -> None:
1250+
if "VIRTUAL_ENV" in os.environ:
1251+
del os.environ["VIRTUAL_ENV"]
1252+
1253+
# There is an entry in the envs.toml file but the venv does not exist
1254+
envs_file = TOMLFile(tmp_path / "envs.toml")
1255+
doc = tomlkit.document()
1256+
if is_inconsistent_entry:
1257+
doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"}
1258+
doc["other"] = {"minor": "3.7", "patch": "3.7.0"}
1259+
envs_file.write(doc)
1260+
1261+
config.merge({"virtualenvs": {"path": str(tmp_path)}})
1262+
1263+
mocker.patch("shutil.which", side_effect=lambda py: f"/usr/bin/{py}")
1264+
mocker.patch(
1265+
"subprocess.check_output",
1266+
side_effect=check_output_wrapper(),
1267+
)
1268+
m = mocker.patch(
1269+
"poetry.utils.env.EnvManager.build_venv", side_effect=lambda *args, **kwargs: ""
1270+
)
1271+
1272+
manager.create_venv()
1273+
1274+
m.assert_called()
1275+
1276+
assert envs_file.exists()
1277+
envs: dict[str, Any] = envs_file.read()
1278+
assert venv_name not in envs
1279+
assert envs["other"]["minor"] == "3.7"
1280+
assert envs["other"]["patch"] == "3.7.0"
1281+
1282+
12401283
def test_build_venv_does_not_change_loglevel(
12411284
tmp_path: Path, manager: EnvManager, caplog: LogCaptureFixture
12421285
) -> None:

0 commit comments

Comments
 (0)