diff --git a/README.md b/README.md index 2c7d166..372c261 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,8 @@ pytest-env: ### Load variables from `.env` files +Install the plugin with the `[envfile]` extra to enable `.env` file support. + Specify `.env` files in your configuration: ```toml diff --git a/pyproject.toml b/pyproject.toml index bea77bb..14fd55a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,9 +38,11 @@ dynamic = [ ] dependencies = [ "pytest>=9.0.2", - "python-dotenv>=1.2.1", "tomli>=2.4; python_version<'3.11'", ] +optional-dependencies.envfile = [ + "python-dotenv>=1.2.1", +] optional-dependencies.testing = [ "covdefaults>=2.3", "coverage>=7.13.4", diff --git a/src/pytest_env/plugin.py b/src/pytest_env/plugin.py index 1777d12..0d25f8f 100644 --- a/src/pytest_env/plugin.py +++ b/src/pytest_env/plugin.py @@ -8,7 +8,6 @@ from typing import TYPE_CHECKING, Any import pytest -from dotenv import dotenv_values if TYPE_CHECKING: from collections.abc import Generator, Iterator @@ -75,13 +74,22 @@ def pytest_load_initial_conftests( early_config.stash[_env_actions_key] = _format_actions(actions) +def _dotenv_values(env_file: Path) -> dict[str, str | None]: + try: + from dotenv import dotenv_values # noqa: PLC0415 (late import on purpose) + except ModuleNotFoundError: + msg = "python-dotenv is required for env file support; install pytest-env[envfile]" + raise ImportError(msg) from None + return dotenv_values(env_file) + + def _apply_env_files( early_config: pytest.Config, env_files_list: list[str], actions: list[tuple[str, str, str, str]] | None, ) -> None: for env_file in _load_env_files(early_config, env_files_list): - for key, value in dotenv_values(env_file).items(): + for key, value in _dotenv_values(env_file).items(): if value is not None: os.environ[key] = value if actions is not None: diff --git a/tox.toml b/tox.toml index fe2a872..d9df43b 100644 --- a/tox.toml +++ b/tox.toml @@ -2,7 +2,7 @@ description = "run the tests with pytest" package = "wheel" wheel_build_env = ".pkg" -extras = [ "testing" ] +extras = [ "testing", "envfile" ] pass_env = [ "DIFF_AGAINST", "PYTEST_*" ] set_env.COVERAGE_FILE = "{env:COVERAGE_FILE:{toxworkdir}{/}.coverage.{envname}}" commands = [