Skip to content
Merged
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
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ configuration files. It can also load variables from `.env` files.
- [Load variables from `.env` files](#load-variables-from-env-files)
- [Control variable behavior](#control-variable-behavior)
- [Set different environments for test suites](#set-different-environments-for-test-suites)
- [Share variables across a monorepo](#share-variables-across-a-monorepo)
- [Reference](#reference)
- [TOML configuration format](#toml-configuration-format)
- [INI configuration format](#ini-configuration-format)
Expand Down Expand Up @@ -148,6 +149,39 @@ project/
Running `pytest tests_integration/` uses the subdirectory configuration. The plugin walks up the directory tree and
stops at the first file containing a `pytest_env` section, so subdirectory configs naturally override parent configs.

### Share variables across a monorepo

A subdirectory config replaces the parent one. To keep the parent's variables and add or override a few per subproject,
set `merge_nested = true` in the table pytest-env finds first, at or above pytest's configuration directory:

```
repo/
├── pyproject.toml # [tool.pytest] ... and [tool.pytest_env] merge_nested = true, APP_ENV = "test"
└── packages/
├── storage/
│ └── pyproject.toml # [tool.pytest_env] SOME_ENV_VAR = "A"
└── logic/
└── pyproject.toml # [tool.pytest_env] SOME_ENV_VAR = "B"
```

`pytest packages/storage` sees `APP_ENV=test` and `SOME_ENV_VAR=A`, and `pytest packages/logic` sees `APP_ENV=test` and
`SOME_ENV_VAR=B`. The plugin reads every table between that file and each path given on the command line (or the current
directory when none is given; `testpaths` is not read, so run `pytest packages/storage` rather than a bare `pytest` from
the root) and merges them from the top down:

- a nested entry replaces the parent's entry for the same variable, including its `transform`, `skip_if_set` and `unset`
keys;
- a `{VAR}` template applies after the variables it names, whichever table sets them, so a root
`DB_URL = { value = "pg://db/{DB_NAME}", transform = true }` uses the `DB_NAME` a subproject sets; templates that name
each other in a cycle stop pytest with a usage error. A template therefore sees the value the tables give a variable,
not the one it had before pytest started, unless it refers to itself, as in `PATH = "{PATH}:/opt/bin"`;
- nested `env_files` load after the parent's and resolve from the directory of their own file; like every `.env` file,
they do not override variables set in a table;
- a nested `env_files_skip_if_set` replaces the parent's.

All tests in a run share one environment, so paths that would read different tables
(`pytest packages/storage packages/logic`) stop pytest with a usage error; run them separately.

## Reference

### TOML configuration format
Expand All @@ -166,6 +200,10 @@ REMOVED = { unset = true }

A TOML file with another name selected with `-c` is read like `pytest.toml`, from its `[pytest_env]` table.

Besides variables, the table accepts `env_files` (a list of `.env` files), `env_files_skip_if_set` (a boolean), and
`merge_nested` (a boolean, read from the root table only; see
[Share variables across a monorepo](#share-variables-across-a-monorepo)).

Each key is the environment variable name. Values can be plain values (cast to string) or inline tables with the
following keys:

Expand Down Expand Up @@ -337,6 +375,8 @@ checks `pytest.toml`, `.pytest.toml`, and `pyproject.toml` in order, stopping at
A TOML file with another name selected with `-c` is checked before the walk and is read like `pytest.toml`. This means
subdirectory configurations take precedence over parent configurations, allowing different settings for integration
tests versus unit tests. A file on that path that is not valid TOML stops pytest with a usage error naming the file.
With `merge_nested = true` in the file found this way, the plugin also reads the files below it, down to each tested
path, and merges them into it.

### Choosing a configuration format

Expand Down
2 changes: 2 additions & 0 deletions changelog.d/+merge-nested.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Merge the `pytest_env` tables of subprojects into the root one when the root table sets `merge_nested = true`, for
monorepos where one pytest configuration serves several packages. A nested value wins for the same variable.
188 changes: 137 additions & 51 deletions src/pytest_env/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@
from __future__ import annotations

__lazy_modules__ = [
"graphlib",
"string",
"tomllib",
]

import os
import tomllib
from dataclasses import dataclass
from dataclasses import dataclass, replace
from datetime import datetime
from graphlib import CycleError, TopologicalSorter
from string import Formatter
from typing import TYPE_CHECKING, Final, TypeAlias, TypeVar

import pytest
Expand Down Expand Up @@ -65,8 +69,7 @@ def pytest_load_initial_conftests(

env_files_list: list[str] | None = None
env_files_skip_if_set: bool | None = None
if toml_config := _find_toml_config(early_config):
toml = _load_toml_config(toml_config)
if (toml := _toml_config(early_config)) is not None:
env_files_list, env_files_skip_if_set = toml.env_files, toml.env_files_skip_if_set

if env_files_skip_if_set is None:
Expand All @@ -75,24 +78,38 @@ def pytest_load_initial_conftests(
preexisting = dict(os.environ) if env_files_skip_if_set else {}
for env_file in _load_env_files(early_config, env_files_list):
_apply_env_file(early_config, env_file, actions, preexisting, skip_if_set=env_files_skip_if_set)
_apply_entries(early_config, actions)
_apply_entries(early_config, toml, actions)

if verbose and actions:
early_config.stash[_ENV_ACTIONS_KEY] = _format_actions(actions)


def _toml_config(early_config: pytest.Config) -> _TomlConfig | None:
if (root := _find_toml_config(early_config)) is None:
return None
config = _load_toml_config(root)
if not config.merge_nested:
return config
tables = {target: _nested_tables(root.parent.resolve(), target) for target in _target_dirs(early_config)}
# Every tested path shares one process environment, so they must agree on the tables to merge.
if len(chains := set(tables.values())) > 1:
msg = (
f"pytest-env: with merge_nested, {', '.join(map(str, tables))} read different pytest_env tables, "
"run them separately"
)
raise pytest.UsageError(msg)
for nested in chains.pop():
config = config.merged(_load_toml_config(nested), nested.parent)
return replace(config, entries=_in_dependency_order(config.entries))


def _find_toml_config(early_config: pytest.Config) -> Path | None:
# Find TOML config file by checking inipath first, then walking up the tree.
if early_config.inipath and early_config.inipath.suffix == ".toml" and _has_env_section(early_config.inipath):
return early_config.inipath

start_path = early_config.inipath.parent if early_config.inipath is not None else early_config.rootpath
for current_path in [start_path, *start_path.parents]:
for toml_name in ("pytest.toml", ".pytest.toml", "pyproject.toml"):
toml_file = current_path / toml_name
if toml_file.is_file() and _has_env_section(toml_file):
return toml_file
return None
return next(filter(None, map(_env_table_file, [start_path, *start_path.parents])), None)


def _has_env_section(config_path: Path) -> bool:
Expand All @@ -109,6 +126,13 @@ def _has_env_section(config_path: Path) -> bool:
return isinstance(config.get("pytest_env"), dict)


def _env_table_file(directory: Path) -> Path | None:
for toml_name in ("pytest.toml", ".pytest.toml", "pyproject.toml"):
if (toml_file := directory / toml_name).is_file() and _has_env_section(toml_file):
return toml_file
return None


def _load_toml_config(config_path: Path) -> _TomlConfig:
# Load env_files and entries from TOML config file.
with config_path.open("rb") as file_handler:
Expand All @@ -119,18 +143,21 @@ def _load_toml_config(config_path: Path) -> _TomlConfig:

pytest_env_config = config.get("pytest_env", {})
if not pytest_env_config:
return _TomlConfig(env_files=None, entries=[], env_files_skip_if_set=None)
return _TomlConfig(env_files=None, entries=[], env_files_skip_if_set=None, merge_nested=False)

raw_env_files = pytest_env_config.get("env_files")
env_files: Final[list[str] | None] = [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")
if raw_skip is not None and not isinstance(raw_skip, bool):
msg = f"{config_path}: env_files_skip_if_set must be true or false"
raise pytest.UsageError(msg)
raw_merge = pytest_env_config.get("merge_nested", False)
for name, raw in (("env_files_skip_if_set", raw_skip), ("merge_nested", raw_merge)):
if raw is not None and not isinstance(raw, bool):
msg = f"{config_path}: {name} must be true or false"
raise pytest.UsageError(msg)
return _TomlConfig(
env_files=env_files,
entries=list(_parse_toml_config(pytest_env_config)),
entries=list(_parse_toml_config(pytest_env_config, str(config_path))),
env_files_skip_if_set=raw_skip,
merge_nested=raw_merge,
)


Expand All @@ -139,21 +166,48 @@ class _TomlConfig:
env_files: list[str] | None
entries: list[Entry]
env_files_skip_if_set: bool | None
merge_nested: bool

def merged(self, nested: _TomlConfig, directory: Path) -> _TomlConfig:
# A nested entry replaces the parent's entry for the same variable, and its env files resolve from its own
# directory.
env_files = (
None
if self.env_files is None and nested.env_files is None
else [*(self.env_files or ()), *(str(directory / name) for name in nested.env_files or ())]
)
return _TomlConfig(
env_files=env_files,
entries=list(
(
{_env_key(entry.key): entry for entry in self.entries}
| {_env_key(entry.key): entry for entry in nested.entries}
).values()
),
env_files_skip_if_set=(
self.env_files_skip_if_set if nested.env_files_skip_if_set is None else nested.env_files_skip_if_set
),
merge_nested=True,
)


def _parse_toml_config(config: dict[str, _TomlValue]) -> Generator[Entry, None, None]:
def _env_key(key: str) -> str:
return key.upper() if os.name == "nt" else key


def _parse_toml_config(config: dict[str, _TomlValue], source: str) -> Generator[Entry, None, None]:
for key, entry in config.items():
if key == "env_files" and isinstance(entry, list):
continue
if key == "env_files_skip_if_set":
if key in {"env_files_skip_if_set", "merge_nested"}:
continue
if isinstance(entry, dict):
yield _parse_toml_table(key, entry)
yield _parse_toml_table(key, entry, source)
else:
yield Entry(key=key, value=str(entry), transform=False, skip_if_set=False, unset=False)
yield Entry(key=key, value=str(entry), transform=False, skip_if_set=False, unset=False, source=source)


def _parse_toml_table(key: str, entry: dict[str, _TomlValue]) -> Entry:
def _parse_toml_table(key: str, entry: dict[str, _TomlValue], source: str) -> Entry:
if unknown := sorted(entry.keys() - {"value", "transform", "skip_if_set", "unset"}):
msg = f"pytest-env: entry {key!r} has unknown key {unknown[0]!r}"
raise pytest.UsageError(msg)
Expand All @@ -172,6 +226,7 @@ def _parse_toml_table(key: str, entry: dict[str, _TomlValue]) -> Entry:
transform=bool(entry.get("transform")),
skip_if_set=bool(entry.get("skip_if_set")),
unset=unset,
source=source,
)


Expand All @@ -183,7 +238,44 @@ class Entry:
value: str
transform: bool
skip_if_set: bool
unset: bool = False
unset: bool
source: str


def _nested_tables(root_dir: Path, target: Path) -> tuple[Path, ...]:
if not target.is_relative_to(root_dir):
return ()
below_root = [target, *target.parents][: len(target.relative_to(root_dir).parts)]
return tuple(filter(None, map(_env_table_file, reversed(below_root))))


def _target_dirs(early_config: pytest.Config) -> list[Path]:
invocation = early_config.invocation_params.dir
# A node id such as tests/test_a.py::test_b names a file before its first ::.
paths = [invocation / arg.partition("::")[0] for arg in early_config.known_args_namespace.file_or_dir or ()]
return [(path if path.is_dir() else path.parent).resolve() for path in paths or [invocation]]


def _in_dependency_order(entries: list[Entry]) -> list[Entry]:
# Merged tables lose any single file order, so each {VAR} template applies after the variables it names.
by_key = {_env_key(entry.key): entry for entry in entries}
graph = {key: _template_names(entry) & by_key.keys() - {key} for key, entry in by_key.items()}
try:
return [by_key[key] for key in TopologicalSorter(graph).static_order()]
except CycleError as error:
msg = f"pytest-env: {{VAR}} templates refer to each other in a cycle: {' -> '.join(error.args[1])}"
raise pytest.UsageError(msg) from None


def _template_names(entry: Entry) -> set[str]:
if not entry.transform:
return set()
try:
fields = [field for _, field, _, _ in Formatter().parse(entry.value) if field]
except ValueError:
# Expanding the malformed template reports it.
return set()
return {_env_key(field.partition(".")[0].partition("[")[0]) for field in fields}


def _get_option(config: pytest.Config, name: str, kind: type[_Option]) -> _Option:
Expand Down Expand Up @@ -299,52 +391,39 @@ def _expand_env_file_value(value: str, environment: dict[str, str | None]) -> st
return "".join(parts)


def _env_key(key: str) -> str:
return key.upper() if os.name == "nt" else key


def _set_variable(key: str, value: str, source: Path | pytest.Config) -> None:
def _set_variable(key: str, value: str, source: Path | str) -> None:
try:
os.environ[key] = value
except (OSError, ValueError):
location = _config_source(source) if isinstance(source, pytest.Config) else source
# A malformed key may contain an entire assignment.
msg = f"pytest-env: cannot set environment variable {key.partition('=')[0]!r} from {location}"
msg = f"pytest-env: cannot set environment variable {key.partition('=')[0]!r} from {source}"
raise pytest.UsageError(msg) from None


def _config_source(early_config: pytest.Config) -> str:
# Describe the configuration source for verbose output.
if (toml_path := _find_toml_config(early_config)) and _load_toml_config(toml_path).entries:
return str(toml_path)
if any(item.startswith("env=") for item in early_config.known_args_namespace.override_ini or ()):
return "-o env"
return str(early_config.inipath) if early_config.inipath else "config"


def _apply_entries(early_config: pytest.Config, actions: list[tuple[str, str, str, str]] | None) -> None:
source = _config_source(early_config) if actions is not None else ""
for entry in _load_values(early_config):
def _apply_entries(
early_config: pytest.Config, toml: _TomlConfig | None, actions: list[tuple[str, str, str, str]] | None
) -> None:
# TOML entries take precedence over INI ones.
for entry in _ini_entries(early_config) if toml is None else toml.entries:
if entry.skip_if_set and entry.key in os.environ:
if actions is not None:
actions.append(("SKIP", entry.key, os.environ[entry.key], source))
actions.append(("SKIP", entry.key, os.environ[entry.key], entry.source))
elif entry.unset:
os.environ.pop(entry.key, None)
if actions is not None:
actions.append(("UNSET", entry.key, "", source))
actions.append(("UNSET", entry.key, "", entry.source))
else:
final = _expand_value(entry)
_set_variable(entry.key, final, early_config)
_set_variable(entry.key, final, entry.source)
if actions is not None:
actions.append(("SET", entry.key, final, source))

actions.append(("SET", entry.key, final, entry.source))

def _load_values(early_config: pytest.Config) -> Iterator[Entry]:
# Load env entries from config, preferring TOML over INI.
if toml_config := _find_toml_config(early_config):
yield from _load_toml_config(toml_config).entries
return

def _ini_entries(early_config: pytest.Config) -> Iterator[Entry]:
if any(item.startswith("env=") for item in early_config.known_args_namespace.override_ini or ()):
source = "-o env"
else:
source = str(early_config.inipath) if early_config.inipath else "config"
for index, line in enumerate(_get_option(early_config, "env", list[str]), start=1):
# INI lines e.g. D:R:NAME=VAL has two flags (R and D), NAME key, and VAL value
parts = line.partition("=")
Expand All @@ -363,7 +442,14 @@ def _load_values(early_config: pytest.Config) -> Iterator[Entry]:
# D: is a way to mark the value to be set only if it does not exist yet
skip_if_set = "D" in flags
# U: is a way to unset (remove) an environment variable
yield Entry(key=key, value=parts[2].strip(), transform=transform, skip_if_set=skip_if_set, unset="U" in flags)
yield Entry(
key=key,
value=parts[2].strip(),
transform=transform,
skip_if_set=skip_if_set,
unset="U" in flags,
source=source,
)


def _expand_value(entry: Entry) -> str:
Expand Down
Loading