python runtime_error ai_generated true

AssertionError: Expected 'mock_method' to be called once. Called 2 times.

ID: python/pytest-mock-reset-between-tests

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.12 active

Root Cause

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.

generic

中文

mock 在测试之间未重置,因此前一个测试的调用仍被记录。这通常在使用模块级 mock 时发生。

Workarounds

  1. 98% success
    def test_foo(mocker):
        mock = mocker.patch('module.func')
        # mocker automatically resets after test
  2. 95% success
    @pytest.fixture
    def mock_func():
        with patch('module.func') as m:
            yield m

Dead Ends

Common approaches that don't work:

  1. 60% fail

    This works but is error-prone and must be remembered for every test.

  2. 70% fail

    If the mock is patching a module, it must be created in a fixture.