Rule idea: Prefer `monkeypatch.setenv` over direct `os.environ` mutation in tests
- Dominant language
- Rust
- Stars
- 49.6k
- Forks
- 2.4k
- Avg merge
- 1d 21h
- Merged PRs (30d)
- 435
Description
### Summary
Directly mutating `os.environ` in tests can leak state across test cases and cause order-dependent failures. Use pytest’s `monkeypatch.setenv`, which automatically restores environment variables after the test completes, ensuring proper isolation and reproducibility.
### Example
```python
import os
import pytest
def foo() -> str:
return os.environ.get("ENV_VAR", "default_value")
# Bad
def test_bad():
os.environ["ENV_VAR"] = "value"
assert foo() == "value"
# Good
def test_good(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv("ENV_VAR", "value")
assert foo() == "value"
```
Contributor guide
Research direction
The issue names pytest's monkeypatch.setenv and direct os.environ mutation but no repository files or tests. Start by locating Ruff's existing rule definitions and test cases for Python environment-variable usage, then determine how the rule should identify the mutation and verify that compliant monkeypatch.setenv usage is accepted.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python, rust
- Domain
- testing, tooling
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100