# KeyError: 'API_KEY'
处理上述异常时又出现另一个异常:
AssertionError: assert 'test-key' == os.environ['API_KEY']

- **ID:** `python/pytest-monkeypatch-env-not-restored`
- **领域:** python
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

测试直接修改了 os.environ（os.environ['API_KEY']='...'）而非使用 monkeypatch.setenv。改动在测试间泄漏，另一个测试的 teardown 删除了该键。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 7.x | active | — | — |
| 8.x | active | — | — |

## 解决方案

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

## 无效尝试

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