Skip to content

Commit

Permalink
tests: isolate python env vars
Browse files Browse the repository at this point in the history
  • Loading branch information
abn committed May 11, 2022
1 parent d607020 commit 2e6ae2a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 15 deletions.
23 changes: 8 additions & 15 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from tests.helpers import TestLocker
from tests.helpers import TestRepository
from tests.helpers import get_package
from tests.helpers import isolated_environment
from tests.helpers import mock_clone
from tests.helpers import mock_download

Expand Down Expand Up @@ -246,27 +247,19 @@ def _pep517_metadata(cls: PackageInfo, path: Path) -> PackageInfo:

@pytest.fixture
def environ() -> Iterator[None]:
original_environ = dict(os.environ)

yield

os.environ.clear()
os.environ.update(original_environ)
with isolated_environment():
yield


@pytest.fixture(autouse=True)
def isolate_environ() -> Iterator[None]:
"""Ensure the environment is isolated from user configuration."""
original_environ = dict(os.environ)

for var in os.environ:
if var.startswith("POETRY_"):
del os.environ[var]

yield
with isolated_environment():
for var in os.environ:
if var.startswith("POETRY_") or var in {"PYTHONPATH", "VIRTUAL_ENV"}:
del os.environ[var]

os.environ.clear()
os.environ.update(original_environ)
yield


@pytest.fixture(autouse=True)
Expand Down
20 changes: 20 additions & 0 deletions tests/helpers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import contextlib
import os
import re
import shutil
Expand All @@ -9,6 +10,7 @@
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
from typing import Iterator

from poetry.core.masonry.utils.helpers import escape_name
from poetry.core.masonry.utils.helpers import escape_version
Expand Down Expand Up @@ -230,3 +232,21 @@ def find_links_for_package(self, package: Package) -> list[Link]:
f"-{escape_version(package.version.text)}-py2.py3-none-any.whl"
)
]


@contextlib.contextmanager
def isolated_environment(
environ: dict[str, Any] | None = None, clear: bool = False
) -> Iterator[None]:
original_environ = dict(os.environ)

if clear:
os.environ.clear()

if environ:
os.environ.update(environ)

yield

os.environ.clear()
os.environ.update(original_environ)

0 comments on commit 2e6ae2a

Please sign in to comment.