# KeyError: 'API_KEY'
During handling of the above exception, another exception occurred:
AssertionError: assert 'test-key' == os.environ['API_KEY']

- **ID:** `python/pytest-monkeypatch-env-not-restored`
- **Domain:** python
- **Category:** config_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

Test mutated os.environ directly (os.environ['API_KEY']='...') instead of using monkeypatch.setenv. Changes leak between tests, and teardown in another test deletes the key.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 7.x | active | — | — |
| 8.x | active | — | — |

## Workarounds

1. **** (98% success)
   ```
   Use monkeypatch:
  def test_x(monkeypatch):
      monkeypatch.setenv('API_KEY', 'test-key')
      ...
monkeypatch auto-restores on teardown.
   ```
2. **** (95% success)
   ```
   Use monkeypatch.delenv with raising=False for removal tests:
  monkeypatch.delenv('API_KEY', raising=False)
   ```

## Dead Ends

- **** — Doesn't restore the original value; subsequent tests see a missing variable. (75% fail)
- **** — Pollutes the whole session and hides order-dependent bugs. (60% fail)
