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

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-05-19First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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

  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

Common approaches that don't work:

  1. 75% fail

    Doesn't restore the original value; subsequent tests see a missing variable.

  2. 60% fail

    Pollutes the whole session and hides order-dependent bugs.