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
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ HOME = "~/tmp"
RUN_ENV = 1
TRANSFORMED = { value = "{USER}/alpha", transform = true }
SKIP_IF_SET = { value = "on", skip_if_set = true }
DATABASE_URL = { unset = true }
```

In `pytest.toml` (or `.pytest.toml`):
Expand All @@ -41,13 +42,14 @@ HOME = "~/tmp"
RUN_ENV = 1
TRANSFORMED = { value = "{USER}/alpha", transform = true }
SKIP_IF_SET = { value = "on", skip_if_set = true }
DATABASE_URL = { unset = true }
```

The `tool.pytest_env` (`pytest_env` in `pytest.toml` and `.pytest.toml`) tables keys are the environment variables keys
to set. The right hand side of the assignment:

- if an inline table you can set options via the `transform` or `skip_if_set` keys, while the `value` key holds the
value to set (or transform before setting). For transformation the variables you can use is other environment
- if an inline table you can set options via the `transform`, `skip_if_set` or `unset` keys, while the `value` key holds
the value to set (or transform before setting). For transformation the variables you can use is other environment
variable,
- otherwise the value to set for the environment variable to set (casted to a string).

Expand Down Expand Up @@ -122,3 +124,14 @@ env =
R:RUN_PATH=/run/path/{USER}
R:D:RUN_PATH_IF_NOT_SET=/run/path/{USER}
```

### Unsetting variables

You can use `U:` (unset) as prefix to remove an environment variable. This differs from setting a variable to an empty
string — the variable will be completely removed from `os.environ`:

```ini
[pytest]
env =
U:DATABASE_URL
```
21 changes: 14 additions & 7 deletions src/pytest_env/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class Entry:
value: str
transform: bool
skip_if_set: bool
unset: bool = False


@pytest.hookimpl(tryfirst=True)
Expand All @@ -43,20 +44,24 @@ def pytest_load_initial_conftests(
) -> None:
"""Load environment variables from configuration files."""
for entry in _load_values(early_config):
if entry.skip_if_set and entry.key in os.environ:
if entry.unset:
os.environ.pop(entry.key, None)
elif entry.skip_if_set and entry.key in os.environ:
continue
# transformation -> replace environment variables, e.g. TEST_DIR={USER}/repo_test_dir.
os.environ[entry.key] = entry.value.format(**os.environ) if entry.transform else entry.value
else:
# transformation -> replace environment variables, e.g. TEST_DIR={USER}/repo_test_dir.
os.environ[entry.key] = entry.value.format(**os.environ) if entry.transform else entry.value


def _parse_toml_config(config: dict[str, Any]) -> Generator[Entry, None, None]:
for key, entry in config.items():
if isinstance(entry, dict):
value = str(entry["value"])
unset = bool(entry.get("unset"))
value = str(entry.get("value", "")) if not unset else ""
transform, skip_if_set = bool(entry.get("transform")), bool(entry.get("skip_if_set"))
else:
value, transform, skip_if_set = str(entry), False, False
yield Entry(key, value, transform, skip_if_set)
value, transform, skip_if_set, unset = str(entry), False, False, False
yield Entry(key, value, transform, skip_if_set, unset=unset)


def _load_values(early_config: pytest.Config) -> Iterator[Entry]:
Expand Down Expand Up @@ -91,6 +96,8 @@ def _load_values(early_config: pytest.Config) -> Iterator[Entry]:
transform = "R" not in flags
# 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
unset = "U" in flags
key = ini_key_parts[-1].strip()
value = parts[2].strip()
yield Entry(key, value, transform, skip_if_set)
yield Entry(key, value, transform, skip_if_set, unset=unset)
5 changes: 4 additions & 1 deletion tests/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,7 @@

def test_env() -> None:
for key, value in ast.literal_eval(os.environ["_TEST_ENV"]).items():
assert os.environ[key] == value, key
if value is None:
assert key not in os.environ, f"{key} should be unset"
else:
assert os.environ[key] == value, key
36 changes: 36 additions & 0 deletions tests/test_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,24 @@
{"MAGIC": "zero"},
id="empty ini works",
),
pytest.param(
{"MAGIC": "alpha"},
"[pytest]\nenv = U:MAGIC",
{"MAGIC": None},
id="U flag - unset existing var",
),
pytest.param(
{},
"[pytest]\nenv = U:MAGIC",
{"MAGIC": None},
id="U flag - unset non-existing var",
),
pytest.param(
{"MAGIC": "alpha"},
"[pytest]\nenv = U:MAGIC\n MAGIC=beta",
{"MAGIC": "beta"},
id="U flag then set - var is set",
),
],
)
def test_env_via_pytest(
Expand Down Expand Up @@ -229,6 +247,24 @@ def test_env_via_pytest(
"pytest.toml",
id="pytest toml over pyproject toml",
),
pytest.param(
{"MAGIC": "alpha"},
"[tool.pytest_env]\nMAGIC = {unset = true}",
"",
"",
{"MAGIC": None},
None,
id="pyproject toml unset",
),
pytest.param(
{},
"[tool.pytest_env]\nMAGIC = {unset = true}",
"",
"",
{"MAGIC": None},
None,
id="pyproject toml unset non-existing",
),
],
)
def test_env_via_toml( # noqa: PLR0913, PLR0917
Expand Down