Repository navigation
Description
pytest --envfile ../ci.env, run from a project directory, loads ci.env from two directories up instead of one. The tests pass with variables from a file the command line did not name. --envfile=../ci.env loads the named file.
Affected code
plugin.py#L172:_load_env_filesjoins the--envfilevalue toearly_config.rootpath.
Mechanism
pytest selects the rootdir from the arguments it cannot attribute to an option, and it does so before it loads plugin entry points. At that point --envfile is unknown, so ../ci.env counts as a path argument. get_dirs_from_args keeps the directory of every argument that exists, and when no configuration file is found from there, determine_setup roots the session at the common ancestor of that directory and the invocation directory, which is the parent of the project. The project's own configuration file is not selected in that run either; that part happens in pytest, before pytest-env runs.
pytest-env then joins the same relative value to the rootdir, which resolves ../ci.env against the parent and opens the file one level above it. With --envfile=../ci.env the value stays attached to the option, the rootdir stays in the project, and the join gives the named file.
Reproduction
repro.sh
tmp="$(mktemp -d)"
mkdir -p "$tmp/work/project"
echo 'WHICH=one-level-too-high' > "$tmp/ci.env"
echo 'WHICH=named-on-the-command-line' > "$tmp/work/ci.env"
cd "$tmp/work/project"
printf '[pytest]\n' > pytest.ini
printf 'import os\n\n\ndef test_which() -> None:\n print(os.environ.get("WHICH"))\n' > test_which.py
pytest -q -s --envfile ../ci.env
pytest -q -s --envfile=../ci.envRun with sh repro.sh at 3ebb6b4872fd0e450b6670d529e375e11c218e61, with pytest 9.2.0, python-dotenv 1.2.4 and CPython 3.14 on Linux:
one-level-too-high
.
1 passed in 0.00s
named-on-the-command-line
.
1 passed in 0.00s
Expected: both spellings load work/ci.env, the file ../ci.env names from the invocation directory.
Impact
The session runs with variables from a file nobody selected, or stops with Environment file not found: ../ci.env when no file of that name exists higher up.
- Reproducibility: moderate. The value has to be its own argument, on the command line or in
PYTEST_ADDOPTS, and has to point outside the invocation directory, with no-c. - Real-world exposure: niche. The README's
--envfile .env.localexample stays inside the project and is not affected; a shared file kept beside several projects is.
Credits
Reported by Anthropic's OSS Scanner: ANT-2026-ZUMAZHJI.
Activity