Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.d/+env-files-skip-first-wins.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
With `env_files_skip_if_set = true`, variables set by an earlier `env_files` entry count as existing when later files
load: the first file wins, and `${VAR}` references expand to the kept value.
3 changes: 2 additions & 1 deletion src/pytest_env/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,9 @@ def pytest_load_initial_conftests(
if env_files_skip_if_set is None:
env_files_skip_if_set = _get_option(early_config, "env_files_skip_if_set", bool)

preexisting = dict(os.environ) if env_files_skip_if_set else {}
for env_file in _load_env_files(early_config, env_files_list):
# Each file counts variables set by earlier files as existing, so the first file wins.
preexisting = dict(os.environ) if env_files_skip_if_set else {}
_apply_env_file(early_config, env_file, actions, preexisting, skip_if_set=env_files_skip_if_set)
_apply_entries(early_config, actions)

Expand Down
26 changes: 26 additions & 0 deletions tests/test_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,32 @@ def test_envfile_cli_skip_if_set(pytester: pytest.Pytester, env_test_template: s
pytester.runpytest("--envfile", "cli.env").assert_outcomes(passed=1)


def test_env_files_skip_if_set_first_file_wins(
pytester: pytest.Pytester, env_test_template: str, mocker: MockerFixture
) -> None:
(pytester.path / "test_multi_skip.py").write_text(env_test_template, encoding="utf-8")
(pytester.path / ".env").write_text("MAGIC=from_first\n", encoding="utf-8")
(pytester.path / ".env.test").write_text("MAGIC=from_second\nEXPANDED=${MAGIC}_suffix\n", encoding="utf-8")
(pytester.path / "pyproject.toml").write_text(
dedent("""\
[tool.pytest_env]
env_files = [".env", ".env.test"]
env_files_skip_if_set = true
"""),
encoding="utf-8",
)

expected_env = {"MAGIC": "from_first", "EXPANDED": "from_first_suffix"}
new_env = {
"_TEST_ENV": repr(expected_env),
"PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",
"PYTEST_PLUGINS": "pytest_env.plugin",
}

mocker.patch.dict(os.environ, new_env, clear=True)
pytester.runpytest().assert_outcomes(passed=1)


@pytest.mark.parametrize(
"cli_arg",
[
Expand Down