python
config_error
ai_generated
true
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
80%Fix Rate
90%Confidence
0Evidence
2024-05-19First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
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.
generic中文
测试直接修改了 os.environ(os.environ['API_KEY']='...')而非使用 monkeypatch.setenv。改动在测试间泄漏,另一个测试的 teardown 删除了该键。
Workarounds
-
98% success
Use monkeypatch: def test_x(monkeypatch): monkeypatch.setenv('API_KEY', 'test-key') ... monkeypatch auto-restores on teardown. -
95% success
Use monkeypatch.delenv with raising=False for removal tests: monkeypatch.delenv('API_KEY', raising=False)
Dead Ends
Common approaches that don't work:
-
75% fail
Doesn't restore the original value; subsequent tests see a missing variable.
-
60% fail
Pollutes the whole session and hides order-dependent bugs.