python config_error ai_generated true

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-05-19首次发现

版本兼容性

版本状态引入弃用备注
7.x active — — —
8.x active — — —

根因分析

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

English

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

解决方案

  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)

无效尝试

常见但无效的做法:

  1. 75% 失败

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

  2. 60% 失败

    Pollutes the whole session and hides order-dependent bugs.