@@ -49,33 +49,37 @@ class MockCacheItem:
49
49
50
50
@dataclass
51
51
class MockCache :
52
+ """
53
+ Cache MagicMock and Patcher instances so we can undo them later.
54
+ """
55
+
52
56
cache : List [MockCacheItem ] = field (default_factory = list )
53
57
54
- def find (self , mock : MockType ) -> MockCacheItem :
55
- the_mock = next (
56
- (mock_item for mock_item in self .cache if mock_item .mock == mock ), None
57
- )
58
- if the_mock is None :
59
- raise ValueError ("This mock object is not registered" )
60
- return the_mock
58
+ def _find (self , mock : MockType ) -> MockCacheItem :
59
+ for mock_item in self .cache :
60
+ if mock_item .mock is mock :
61
+ return mock_item
62
+ raise ValueError ("This mock object is not registered" )
61
63
62
64
def add (self , mock : MockType , ** kwargs : Any ) -> MockCacheItem :
63
65
self .cache .append (MockCacheItem (mock = mock , ** kwargs ))
64
66
return self .cache [- 1 ]
65
67
66
68
def remove (self , mock : MockType ) -> None :
67
- mock_item = self .find (mock )
69
+ mock_item = self ._find (mock )
70
+ if mock_item .patch :
71
+ mock_item .patch .stop ()
68
72
self .cache .remove (mock_item )
69
73
70
74
def clear (self ) -> None :
75
+ for mock_item in reversed (self .cache ):
76
+ if mock_item .patch is not None :
77
+ mock_item .patch .stop ()
71
78
self .cache .clear ()
72
79
73
80
def __iter__ (self ) -> Iterator [MockCacheItem ]:
74
81
return iter (self .cache )
75
82
76
- def __reversed__ (self ) -> Iterator [MockCacheItem ]:
77
- return reversed (self .cache )
78
-
79
83
80
84
class MockerFixture :
81
85
"""
@@ -146,19 +150,13 @@ def stopall(self) -> None:
146
150
Stop all patchers started by this fixture. Can be safely called multiple
147
151
times.
148
152
"""
149
- for mock_item in reversed (self ._mock_cache ):
150
- if mock_item .patch is not None :
151
- mock_item .patch .stop ()
152
153
self ._mock_cache .clear ()
153
154
154
155
def stop (self , mock : unittest .mock .MagicMock ) -> None :
155
156
"""
156
157
Stops a previous patch or spy call by passing the ``MagicMock`` object
157
158
returned by it.
158
159
"""
159
- mock_item = self ._mock_cache .find (mock )
160
- if mock_item .patch :
161
- mock_item .patch .stop ()
162
160
self ._mock_cache .remove (mock )
163
161
164
162
def spy (self , obj : object , name : str ) -> MockType :
0 commit comments