Skip to content

Commit

Permalink
Fix regression with mocker.patch not being undone correctly
Browse files Browse the repository at this point in the history
The problem was introduced due to a bug in #417 which escaped review: we should always add a mock object to the cache, even if a similar one already exists.

Fix #420
  • Loading branch information
nicoddemus committed Mar 21, 2024
1 parent 6bd8712 commit 4faf92a
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ UNRELEASED

* `#415 <https://github.com/pytest-dev/pytest-mock/pull/415>`_: ``MockType`` and ``AsyncMockType`` can be imported from ``pytest_mock`` for type annotation purposes.

* `#420 <https://github.com/pytest-dev/pytest-mock/issues/420>`_: Fixed a regression which would cause ``mocker.patch.object`` to not being properly cleared between tests.


3.13.0 (2024-03-21)
-------------------
Expand Down
7 changes: 2 additions & 5 deletions src/pytest_mock/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,8 @@ def find(self, mock: MockType) -> MockCacheItem:
return the_mock

def add(self, mock: MockType, **kwargs: Any) -> MockCacheItem:
try:
return self.find(mock)
except ValueError:
self.cache.append(MockCacheItem(mock=mock, **kwargs))
return self.cache[-1]
self.cache.append(MockCacheItem(mock=mock, **kwargs))
return self.cache[-1]

def remove(self, mock: MockType) -> None:
mock_item = self.find(mock)
Expand Down
25 changes: 25 additions & 0 deletions tests/test_pytest_mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1264,3 +1264,28 @@ def foo(self):
mocker.stop(spy)
assert un_spy.foo() == 42
assert spy.call_count == 1


def test_stop_multiple_patches(mocker: MockerFixture) -> None:
"""Regression for #420."""

class Class1:
@staticmethod
def get():
return 1

class Class2:
@staticmethod
def get():
return 2

def handle_get():
return 3

mocker.patch.object(Class1, "get", handle_get)
mocker.patch.object(Class2, "get", handle_get)

mocker.stopall()

assert Class1.get() == 1
assert Class2.get() == 2

0 comments on commit 4faf92a

Please sign in to comment.