python
runtime_error
ai_generated
true
AssertionError: 预期 'mock_method' 被调用一次。实际调用 2 次。
AssertionError: Expected 'mock_method' to be called once. Called 2 times.
ID: python/pytest-mock-reset-between-tests
80%修复率
90%置信度
0证据数
2024-06-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
mock 在测试之间未重置,因此前一个测试的调用仍被记录。这通常在使用模块级 mock 时发生。
English
The mock was not reset between tests, so calls from a previous test are still recorded. This often happens when using a module-level mock.
解决方案
-
98% 成功率
def test_foo(mocker): mock = mocker.patch('module.func') # mocker automatically resets after test -
95% 成功率
@pytest.fixture def mock_func(): with patch('module.func') as m: yield m
无效尝试
常见但无效的做法:
-
60% 失败
This works but is error-prone and must be remembered for every test.
-
70% 失败
If the mock is patching a module, it must be created in a fixture.