Skip to content

✅ test(plugin): verify env vars available during conftest imports#194

Merged
gaborbernat merged 1 commit intopytest-dev:mainfrom
gaborbernat:184
Feb 11, 2026
Merged

✅ test(plugin): verify env vars available during conftest imports#194
gaborbernat merged 1 commit intopytest-dev:mainfrom
gaborbernat:184

Conversation

@gaborbernat
Copy link
Collaborator

There was a concern that if conftest.py contains top-level imports of modules that read environment variables at import time, pytest-env's plugin mechanism might set those variables too late. This could cause KeyError crashes during conftest loading before the test session even begins.

Investigation of pytest's hook execution order confirmed that the current @pytest.hookimpl(tryfirst=True) on pytest_load_initial_conftests is correct — pytest's own conftest-loading implementation uses trylast=True, so pytest-env always sets variables before any conftest is imported. 🔍 This PR adds a regression test to codify that guarantee across all three config formats (ini, pyproject.toml, pytest.toml).

The test creates a module that reads os.environ['MAGIC'] at import time, a conftest.py that imports it at the top level, and verifies the value is available. The environment is cleared via mock.patch.dict with clear=True to ensure the only source of the variable is pytest-env.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Signed-off-by: Bernát Gábor <bgabor8@bloomberg.net>
@gaborbernat gaborbernat merged commit 59db65e into pytest-dev:main Feb 11, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant