Skip to content

Commit 4faf92a

Browse files
committed
Fix regression with mocker.patch not being undone correctly
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
1 parent 6bd8712 commit 4faf92a

File tree

3 files changed

+29
-5
lines changed

3 files changed

+29
-5
lines changed

CHANGELOG.rst

+2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ UNRELEASED
66

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

9+
* `#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.
10+
911

1012
3.13.0 (2024-03-21)
1113
-------------------

src/pytest_mock/plugin.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -60,11 +60,8 @@ def find(self, mock: MockType) -> MockCacheItem:
6060
return the_mock
6161

6262
def add(self, mock: MockType, **kwargs: Any) -> MockCacheItem:
63-
try:
64-
return self.find(mock)
65-
except ValueError:
66-
self.cache.append(MockCacheItem(mock=mock, **kwargs))
67-
return self.cache[-1]
63+
self.cache.append(MockCacheItem(mock=mock, **kwargs))
64+
return self.cache[-1]
6865

6966
def remove(self, mock: MockType) -> None:
7067
mock_item = self.find(mock)

tests/test_pytest_mock.py

+25
Original file line numberDiff line numberDiff line change
@@ -1264,3 +1264,28 @@ def foo(self):
12641264
mocker.stop(spy)
12651265
assert un_spy.foo() == 42
12661266
assert spy.call_count == 1
1267+
1268+
1269+
def test_stop_multiple_patches(mocker: MockerFixture) -> None:
1270+
"""Regression for #420."""
1271+
1272+
class Class1:
1273+
@staticmethod
1274+
def get():
1275+
return 1
1276+
1277+
class Class2:
1278+
@staticmethod
1279+
def get():
1280+
return 2
1281+
1282+
def handle_get():
1283+
return 3
1284+
1285+
mocker.patch.object(Class1, "get", handle_get)
1286+
mocker.patch.object(Class2, "get", handle_get)
1287+
1288+
mocker.stopall()
1289+
1290+
assert Class1.get() == 1
1291+
assert Class2.get() == 2

0 commit comments

Comments
 (0)