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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
12 changes: 10 additions & 2 deletions src/pytest_env/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion tox.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down