diff --git a/README.md b/README.md index 0a450a3..f12caa9 100644 --- a/README.md +++ b/README.md @@ -244,6 +244,8 @@ API_KEY=${FALLBACK_KEY:-default_key} ``` Missing `.env` files from configuration are silently skipped. Paths are resolved relative to the project root. +An explicit `env_files = []` in native TOML configuration disables INI-style `env_files` fallback; omitting the key +preserves that fallback. CLI `--envfile` paths still load in either case. ### CLI options diff --git a/src/pytest_env/plugin.py b/src/pytest_env/plugin.py index 2a19e14..f6ef8fb 100644 --- a/src/pytest_env/plugin.py +++ b/src/pytest_env/plugin.py @@ -65,7 +65,7 @@ def pytest_load_initial_conftests( verbose = getattr(early_config.known_args_namespace, "pytest_env_verbose", False) actions: list[tuple[str, str, str, str]] = [] - env_files_list: list[str] = [] + env_files_list: list[str] | None = None env_files_skip_if_set: bool | None = None if toml_config := _find_toml_config(early_config): env_files_list, _, env_files_skip_if_set = _load_toml_config(toml_config) @@ -87,7 +87,7 @@ def pytest_load_initial_conftests( def _apply_env_files( early_config: pytest.Config, - env_files_list: list[str], + env_files_list: list[str] | None, actions: list[tuple[str, str, str, str]] | None, *, skip_if_set: bool = False, @@ -181,7 +181,7 @@ def _config_source(early_config: pytest.Config) -> str: return "config" # pragma: no cover -def _load_toml_config(config_path: Path) -> tuple[list[str], list[Entry], bool | None]: +def _load_toml_config(config_path: Path) -> tuple[list[str] | None, list[Entry], bool | None]: """Load env_files and entries from TOML config file.""" with config_path.open("rb") as file_handler: config = tomllib.load(file_handler) @@ -191,10 +191,10 @@ def _load_toml_config(config_path: Path) -> tuple[list[str], list[Entry], bool | pytest_env_config = config.get("pytest_env", {}) if not pytest_env_config: - return [], [], None + return None, [], None raw_env_files = pytest_env_config.get("env_files") - env_files = [str(f) for f in raw_env_files] if isinstance(raw_env_files, list) else [] + env_files = [str(f) for f in raw_env_files] if isinstance(raw_env_files, list) else None raw_skip = pytest_env_config.get("env_files_skip_if_set") env_files_skip_if_set = raw_skip if isinstance(raw_skip, bool) else None @@ -202,14 +202,15 @@ def _load_toml_config(config_path: Path) -> tuple[list[str], list[Entry], bool | return env_files, entries, env_files_skip_if_set -def _load_env_files(early_config: pytest.Config, env_files: list[str]) -> Generator[Path, None, None]: +def _load_env_files(early_config: pytest.Config, env_files: list[str] | None) -> Generator[Path, None, None]: """Resolve and yield existing env files, with CLI option taking precedence.""" + configured_env_files = env_files if env_files is not None else list(early_config.getini("env_files")) if cli_envfile := getattr(early_config.known_args_namespace, "envfile", None): if cli_envfile.startswith("+"): if not (resolved := early_config.rootpath / cli_envfile[1:]).is_file(): msg = f"Environment file not found: {cli_envfile[1:]}" raise FileNotFoundError(msg) - for env_file_str in env_files or list(early_config.getini("env_files")): + for env_file_str in configured_env_files: if (config_resolved := early_config.rootpath / env_file_str).is_file(): yield config_resolved yield resolved @@ -220,7 +221,7 @@ def _load_env_files(early_config: pytest.Config, env_files: list[str]) -> Genera yield resolved return - for env_file_str in env_files or list(early_config.getini("env_files")): + for env_file_str in configured_env_files: if (resolved := early_config.rootpath / env_file_str).is_file(): yield resolved diff --git a/tests/test_env.py b/tests/test_env.py index beef6ef..8c541c3 100644 --- a/tests/test_env.py +++ b/tests/test_env.py @@ -764,3 +764,51 @@ def child(pytester: pytest.Pytester, mocker: MockerFixture) -> Path: child: Final[Path] = pytester.path / "child" child.mkdir() return child + + +@pytest.mark.parametrize( + "config_name", + [ + pytest.param("pytest.toml", id="pytest-toml"), + pytest.param(".pytest.toml", id="hidden-pytest-toml"), + pytest.param("pyproject.toml", id="pyproject-toml"), + ], +) +@pytest.mark.parametrize( + "empty_env_files", + [pytest.param(False, id="omitted"), pytest.param(True, id="empty")], +) +@pytest.mark.parametrize( + "extend", + [pytest.param(False, id="config-only"), pytest.param(True, id="cli-extend")], +) +def test_native_env_files_override_ini( + pytester: pytest.Pytester, config_name: str, empty_env_files: bool, extend: bool +) -> None: + (pytester.path / "fallback.env").write_text("INHERITED=from_ini\n", encoding="utf-8") + (pytester.path / "cli.env").write_text("FROM_CLI=from_cli\n", encoding="utf-8") + section = "tool.pytest_env" if config_name == "pyproject.toml" else "pytest_env" + native = f"[{section}]\n" + ("env_files = []\n" if empty_env_files else "") + if config_name == "pyproject.toml": + pytester.makeini("[pytest]\nenv_files = fallback.env\n") + else: + native += '\n[pytest]\nenv_files = ["fallback.env"]\n' + (pytester.path / config_name).write_text(native, encoding="utf-8") + expected_inherited = None if empty_env_files else "from_ini" + expected_cli = "from_cli" if extend else None + pytester.makepyfile( + test_env=dedent(f"""\ + import os + + def test_env() -> None: + assert (os.environ.get("INHERITED"), os.environ.get("FROM_CLI")) == ( + {expected_inherited!r}, {expected_cli!r} + ) + """), + ) + new_env = {"PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1", "PYTEST_PLUGINS": "pytest_env.plugin"} + args = ["--envfile", "+cli.env"] if extend else [] + with mock.patch.dict(os.environ, new_env, clear=True): + result = pytester.runpytest_subprocess(*args) + result.assert_outcomes(passed=1) + assert result.ret == pytest.ExitCode.OK