python
data_error
ai_generated
true
AssertionError: Expected 'mock_method' to be called once. Called 2 times.
ID: python/pytest-mock-not-reset-between-tests
80%Fix Rate
88%Confidence
0Evidence
2024-09-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
A mock object was not reset between tests, so call counts accumulated from previous tests. This happens when mocks are defined at module level or shared via class attributes.
generic中文
mock 对象在测试之间未重置,因此调用计数从先前测试累积。这发生在 mock 定义在模块级别或通过类属性共享时。
Workarounds
-
95% success
@pytest.fixture def mock_service(): return MagicMock() def test_one(mock_service): mock_service.method() mock_service.method.assert_called_once() -
93% success
def test_one(mocker): mock = mocker.patch('module.func') mock() mock.assert_called_once()
Dead Ends
Common approaches that don't work:
-
75% fail
If a test fails before reaching the reset line, the mock remains dirty for the next test. Also error-prone to maintain.
-
85% fail
This changes the assertion but does not fix the accumulated call count. The assertion will still fail.