Skip to content

Commit

Permalink
tests: fix environment not being replaced soon enough (#126)
Browse files Browse the repository at this point in the history
* tests: fix environment not being replaced soon enough

* fix(tests): only clear modmail specific environment variables

* chore: remove unneccessary bug comment

Co-authored-by: Shivansh-007 <[email protected]>

Co-authored-by: Shivansh-007 <[email protected]>
  • Loading branch information
onerandomusername and Shivansh-007 authored Apr 21, 2022
1 parent 8ba34ba commit df5dbb9
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions tests/modmail/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

_ORIG_ENVIRON = None

_modmail_env_prefix = "MODMAIL_"


def pytest_report_header(config) -> str:
"""Pytest headers."""
Expand All @@ -26,17 +28,35 @@ def _get_env():
return pathlib.Path(__file__).parent / "test.env"


def _get_env_vars() -> dict:
result = {}
for key, value in os.environ.items():
# not using upper() since the config system is case sensitive
if key.startswith(_modmail_env_prefix):
result[key] = value
return result


def pytest_configure():
"""Load the test specific environment file, exit if it does not exist."""
global _ORIG_ENVIRON
env = _get_env()
if not env.is_file():
pytest.exit(f"Testing specific {env} does not exist. Cancelling test run.", 2)
os.environ.clear()
_ORIG_ENVIRON = _get_env_vars()
for key in _ORIG_ENVIRON:
del os.environ[key]

dotenv.load_dotenv(_get_env(), override=True)


def pytest_unconfigure():
"""Reset os.environ to the original environment before the run."""
if _ORIG_ENVIRON is not None:
os.environ.clear()
os.environ.update(**_ORIG_ENVIRON)
global _ORIG_ENVIRON
if _ORIG_ENVIRON is None:
return

for key in _get_env_vars():
del os.environ[key]
os.environ.update(**_ORIG_ENVIRON)
_ORIG_ENVIRON = None

0 comments on commit df5dbb9

Please sign in to comment.