pytest_mock
1from pytest_mock.plugin import AsyncMockType 2from pytest_mock.plugin import MockerFixture 3from pytest_mock.plugin import MockType 4from pytest_mock.plugin import PytestMockWarning 5from pytest_mock.plugin import class_mocker 6from pytest_mock.plugin import mocker 7from pytest_mock.plugin import module_mocker 8from pytest_mock.plugin import package_mocker 9from pytest_mock.plugin import pytest_addoption 10from pytest_mock.plugin import pytest_configure 11from pytest_mock.plugin import session_mocker 12 13MockFixture = MockerFixture # backward-compatibility only (#204) 14 15__all__ = [ 16 "AsyncMockType", 17 "MockerFixture", 18 "MockFixture", 19 "MockType", 20 "PytestMockWarning", 21 "pytest_addoption", 22 "pytest_configure", 23 "session_mocker", 24 "package_mocker", 25 "module_mocker", 26 "class_mocker", 27 "mocker", 28]
85class MockerFixture: 86 """ 87 Fixture that provides the same interface to functions in the mock module, 88 ensuring that they are uninstalled at the end of each test. 89 """ 90 91 def __init__(self, config: Any) -> None: 92 self._mock_cache: MockCache = MockCache() 93 self.mock_module = mock_module = get_mock_module(config) 94 self.patch = self._Patcher(self._mock_cache, mock_module) # type: MockerFixture._Patcher 95 # aliases for convenience 96 self.Mock = mock_module.Mock 97 self.MagicMock = mock_module.MagicMock 98 self.NonCallableMock = mock_module.NonCallableMock 99 self.NonCallableMagicMock = mock_module.NonCallableMagicMock 100 self.PropertyMock = mock_module.PropertyMock 101 if hasattr(mock_module, "AsyncMock"): 102 self.AsyncMock = mock_module.AsyncMock 103 self.call = mock_module.call 104 self.ANY = mock_module.ANY 105 self.DEFAULT = mock_module.DEFAULT 106 self.sentinel = mock_module.sentinel 107 self.mock_open = mock_module.mock_open 108 if hasattr(mock_module, "seal"): 109 self.seal = mock_module.seal 110 111 def create_autospec( 112 self, spec: Any, spec_set: bool = False, instance: bool = False, **kwargs: Any 113 ) -> MockType: 114 m: MockType = self.mock_module.create_autospec( 115 spec, spec_set, instance, **kwargs 116 ) 117 self._mock_cache.add(m) 118 return m 119 120 def resetall( 121 self, *, return_value: bool = False, side_effect: bool = False 122 ) -> None: 123 """ 124 Call reset_mock() on all patchers started by this fixture. 125 126 :param bool return_value: Reset the return_value of mocks. 127 :param bool side_effect: Reset the side_effect of mocks. 128 """ 129 supports_reset_mock_with_args: Tuple[Type[Any], ...] 130 if hasattr(self, "AsyncMock"): 131 supports_reset_mock_with_args = (self.Mock, self.AsyncMock) 132 else: 133 supports_reset_mock_with_args = (self.Mock,) 134 135 for mock_item in self._mock_cache: 136 # See issue #237. 137 if not hasattr(mock_item.mock, "reset_mock"): 138 continue 139 # NOTE: The mock may be a dictionary 140 if hasattr(mock_item.mock, "spy_return_list"): 141 mock_item.mock.spy_return_list = [] 142 if isinstance(mock_item.mock, supports_reset_mock_with_args): 143 mock_item.mock.reset_mock( 144 return_value=return_value, side_effect=side_effect 145 ) 146 else: 147 mock_item.mock.reset_mock() 148 149 def stopall(self) -> None: 150 """ 151 Stop all patchers started by this fixture. Can be safely called multiple 152 times. 153 """ 154 self._mock_cache.clear() 155 156 def stop(self, mock: unittest.mock.MagicMock) -> None: 157 """ 158 Stops a previous patch or spy call by passing the ``MagicMock`` object 159 returned by it. 160 """ 161 self._mock_cache.remove(mock) 162 163 def spy(self, obj: object, name: str) -> MockType: 164 """ 165 Create a spy of method. It will run method normally, but it is now 166 possible to use `mock` call features with it, like call count. 167 168 :param obj: An object. 169 :param name: A method in object. 170 :return: Spy object. 171 """ 172 method = getattr(obj, name) 173 174 def wrapper(*args, **kwargs): 175 spy_obj.spy_return = None 176 spy_obj.spy_exception = None 177 try: 178 r = method(*args, **kwargs) 179 except BaseException as e: 180 spy_obj.spy_exception = e 181 raise 182 else: 183 spy_obj.spy_return = r 184 spy_obj.spy_return_list.append(r) 185 return r 186 187 async def async_wrapper(*args, **kwargs): 188 spy_obj.spy_return = None 189 spy_obj.spy_exception = None 190 try: 191 r = await method(*args, **kwargs) 192 except BaseException as e: 193 spy_obj.spy_exception = e 194 raise 195 else: 196 spy_obj.spy_return = r 197 spy_obj.spy_return_list.append(r) 198 return r 199 200 if asyncio.iscoroutinefunction(method): 201 wrapped = functools.update_wrapper(async_wrapper, method) 202 else: 203 wrapped = functools.update_wrapper(wrapper, method) 204 205 autospec = inspect.ismethod(method) or inspect.isfunction(method) 206 207 spy_obj = self.patch.object(obj, name, side_effect=wrapped, autospec=autospec) 208 spy_obj.spy_return = None 209 spy_obj.spy_return_list = [] 210 spy_obj.spy_exception = None 211 return spy_obj 212 213 def stub(self, name: Optional[str] = None) -> unittest.mock.MagicMock: 214 """ 215 Create a stub method. It accepts any arguments. Ideal to register to 216 callbacks in tests. 217 218 :param name: the constructed stub's name as used in repr 219 :return: Stub object. 220 """ 221 return cast( 222 unittest.mock.MagicMock, 223 self.mock_module.MagicMock(spec=lambda *args, **kwargs: None, name=name), 224 ) 225 226 def async_stub(self, name: Optional[str] = None) -> AsyncMockType: 227 """ 228 Create a async stub method. It accepts any arguments. Ideal to register to 229 callbacks in tests. 230 231 :param name: the constructed stub's name as used in repr 232 :return: Stub object. 233 """ 234 return cast( 235 AsyncMockType, 236 self.mock_module.AsyncMock(spec=lambda *args, **kwargs: None, name=name), 237 ) 238 239 class _Patcher: 240 """ 241 Object to provide the same interface as mock.patch, mock.patch.object, 242 etc. We need this indirection to keep the same API of the mock package. 243 """ 244 245 DEFAULT = object() 246 247 def __init__(self, mock_cache, mock_module): 248 self.__mock_cache = mock_cache 249 self.mock_module = mock_module 250 251 def _start_patch( 252 self, mock_func: Any, warn_on_mock_enter: bool, *args: Any, **kwargs: Any 253 ) -> MockType: 254 """Patches something by calling the given function from the mock 255 module, registering the patch to stop it later and returns the 256 mock object resulting from the mock call. 257 """ 258 p = mock_func(*args, **kwargs) 259 mocked: MockType = p.start() 260 self.__mock_cache.add(mock=mocked, patch=p) 261 if hasattr(mocked, "reset_mock"): 262 # check if `mocked` is actually a mock object, as depending on autospec or target 263 # parameters `mocked` can be anything 264 if hasattr(mocked, "__enter__") and warn_on_mock_enter: 265 mocked.__enter__.side_effect = lambda: warnings.warn( 266 "Mocks returned by pytest-mock do not need to be used as context managers. " 267 "The mocker fixture automatically undoes mocking at the end of a test. " 268 "This warning can be ignored if it was triggered by mocking a context manager. " 269 "https://pytest-mock.readthedocs.io/en/latest/remarks.html#usage-as-context-manager", 270 PytestMockWarning, 271 stacklevel=5, 272 ) 273 return mocked 274 275 def object( 276 self, 277 target: object, 278 attribute: str, 279 new: object = DEFAULT, 280 spec: Optional[object] = None, 281 create: bool = False, 282 spec_set: Optional[object] = None, 283 autospec: Optional[object] = None, 284 new_callable: object = None, 285 **kwargs: Any, 286 ) -> MockType: 287 """API to mock.patch.object""" 288 if new is self.DEFAULT: 289 new = self.mock_module.DEFAULT 290 return self._start_patch( 291 self.mock_module.patch.object, 292 True, 293 target, 294 attribute, 295 new=new, 296 spec=spec, 297 create=create, 298 spec_set=spec_set, 299 autospec=autospec, 300 new_callable=new_callable, 301 **kwargs, 302 ) 303 304 def context_manager( 305 self, 306 target: builtins.object, 307 attribute: str, 308 new: builtins.object = DEFAULT, 309 spec: Optional[builtins.object] = None, 310 create: bool = False, 311 spec_set: Optional[builtins.object] = None, 312 autospec: Optional[builtins.object] = None, 313 new_callable: builtins.object = None, 314 **kwargs: Any, 315 ) -> MockType: 316 """This is equivalent to mock.patch.object except that the returned mock 317 does not issue a warning when used as a context manager.""" 318 if new is self.DEFAULT: 319 new = self.mock_module.DEFAULT 320 return self._start_patch( 321 self.mock_module.patch.object, 322 False, 323 target, 324 attribute, 325 new=new, 326 spec=spec, 327 create=create, 328 spec_set=spec_set, 329 autospec=autospec, 330 new_callable=new_callable, 331 **kwargs, 332 ) 333 334 def multiple( 335 self, 336 target: builtins.object, 337 spec: Optional[builtins.object] = None, 338 create: bool = False, 339 spec_set: Optional[builtins.object] = None, 340 autospec: Optional[builtins.object] = None, 341 new_callable: Optional[builtins.object] = None, 342 **kwargs: Any, 343 ) -> Dict[str, MockType]: 344 """API to mock.patch.multiple""" 345 return self._start_patch( 346 self.mock_module.patch.multiple, 347 True, 348 target, 349 spec=spec, 350 create=create, 351 spec_set=spec_set, 352 autospec=autospec, 353 new_callable=new_callable, 354 **kwargs, 355 ) 356 357 def dict( 358 self, 359 in_dict: Union[Mapping[Any, Any], str], 360 values: Union[Mapping[Any, Any], Iterable[Tuple[Any, Any]]] = (), 361 clear: bool = False, 362 **kwargs: Any, 363 ) -> Any: 364 """API to mock.patch.dict""" 365 return self._start_patch( 366 self.mock_module.patch.dict, 367 True, 368 in_dict, 369 values=values, 370 clear=clear, 371 **kwargs, 372 ) 373 374 @overload 375 def __call__( 376 self, 377 target: str, 378 new: None = ..., 379 spec: Optional[builtins.object] = ..., 380 create: bool = ..., 381 spec_set: Optional[builtins.object] = ..., 382 autospec: Optional[builtins.object] = ..., 383 new_callable: None = ..., 384 **kwargs: Any, 385 ) -> MockType: ... 386 387 @overload 388 def __call__( 389 self, 390 target: str, 391 new: _T, 392 spec: Optional[builtins.object] = ..., 393 create: bool = ..., 394 spec_set: Optional[builtins.object] = ..., 395 autospec: Optional[builtins.object] = ..., 396 new_callable: None = ..., 397 **kwargs: Any, 398 ) -> _T: ... 399 400 @overload 401 def __call__( 402 self, 403 target: str, 404 new: None, 405 spec: Optional[builtins.object], 406 create: bool, 407 spec_set: Optional[builtins.object], 408 autospec: Optional[builtins.object], 409 new_callable: Callable[[], _T], 410 **kwargs: Any, 411 ) -> _T: ... 412 413 @overload 414 def __call__( 415 self, 416 target: str, 417 new: None = ..., 418 spec: Optional[builtins.object] = ..., 419 create: bool = ..., 420 spec_set: Optional[builtins.object] = ..., 421 autospec: Optional[builtins.object] = ..., 422 *, 423 new_callable: Callable[[], _T], 424 **kwargs: Any, 425 ) -> _T: ... 426 427 def __call__( 428 self, 429 target: str, 430 new: builtins.object = DEFAULT, 431 spec: Optional[builtins.object] = None, 432 create: bool = False, 433 spec_set: Optional[builtins.object] = None, 434 autospec: Optional[builtins.object] = None, 435 new_callable: Optional[Callable[[], Any]] = None, 436 **kwargs: Any, 437 ) -> Any: 438 """API to mock.patch""" 439 if new is self.DEFAULT: 440 new = self.mock_module.DEFAULT 441 return self._start_patch( 442 self.mock_module.patch, 443 True, 444 target, 445 new=new, 446 spec=spec, 447 create=create, 448 spec_set=spec_set, 449 autospec=autospec, 450 new_callable=new_callable, 451 **kwargs, 452 )
Fixture that provides the same interface to functions in the mock module, ensuring that they are uninstalled at the end of each test.
91 def __init__(self, config: Any) -> None: 92 self._mock_cache: MockCache = MockCache() 93 self.mock_module = mock_module = get_mock_module(config) 94 self.patch = self._Patcher(self._mock_cache, mock_module) # type: MockerFixture._Patcher 95 # aliases for convenience 96 self.Mock = mock_module.Mock 97 self.MagicMock = mock_module.MagicMock 98 self.NonCallableMock = mock_module.NonCallableMock 99 self.NonCallableMagicMock = mock_module.NonCallableMagicMock 100 self.PropertyMock = mock_module.PropertyMock 101 if hasattr(mock_module, "AsyncMock"): 102 self.AsyncMock = mock_module.AsyncMock 103 self.call = mock_module.call 104 self.ANY = mock_module.ANY 105 self.DEFAULT = mock_module.DEFAULT 106 self.sentinel = mock_module.sentinel 107 self.mock_open = mock_module.mock_open 108 if hasattr(mock_module, "seal"): 109 self.seal = mock_module.seal
120 def resetall( 121 self, *, return_value: bool = False, side_effect: bool = False 122 ) -> None: 123 """ 124 Call reset_mock() on all patchers started by this fixture. 125 126 :param bool return_value: Reset the return_value of mocks. 127 :param bool side_effect: Reset the side_effect of mocks. 128 """ 129 supports_reset_mock_with_args: Tuple[Type[Any], ...] 130 if hasattr(self, "AsyncMock"): 131 supports_reset_mock_with_args = (self.Mock, self.AsyncMock) 132 else: 133 supports_reset_mock_with_args = (self.Mock,) 134 135 for mock_item in self._mock_cache: 136 # See issue #237. 137 if not hasattr(mock_item.mock, "reset_mock"): 138 continue 139 # NOTE: The mock may be a dictionary 140 if hasattr(mock_item.mock, "spy_return_list"): 141 mock_item.mock.spy_return_list = [] 142 if isinstance(mock_item.mock, supports_reset_mock_with_args): 143 mock_item.mock.reset_mock( 144 return_value=return_value, side_effect=side_effect 145 ) 146 else: 147 mock_item.mock.reset_mock()
Call reset_mock() on all patchers started by this fixture.
Parameters
- bool return_value: Reset the return_value of mocks.
- bool side_effect: Reset the side_effect of mocks.
149 def stopall(self) -> None: 150 """ 151 Stop all patchers started by this fixture. Can be safely called multiple 152 times. 153 """ 154 self._mock_cache.clear()
Stop all patchers started by this fixture. Can be safely called multiple times.
156 def stop(self, mock: unittest.mock.MagicMock) -> None: 157 """ 158 Stops a previous patch or spy call by passing the ``MagicMock`` object 159 returned by it. 160 """ 161 self._mock_cache.remove(mock)
Stops a previous patch or spy call by passing the MagicMock
object
returned by it.
163 def spy(self, obj: object, name: str) -> MockType: 164 """ 165 Create a spy of method. It will run method normally, but it is now 166 possible to use `mock` call features with it, like call count. 167 168 :param obj: An object. 169 :param name: A method in object. 170 :return: Spy object. 171 """ 172 method = getattr(obj, name) 173 174 def wrapper(*args, **kwargs): 175 spy_obj.spy_return = None 176 spy_obj.spy_exception = None 177 try: 178 r = method(*args, **kwargs) 179 except BaseException as e: 180 spy_obj.spy_exception = e 181 raise 182 else: 183 spy_obj.spy_return = r 184 spy_obj.spy_return_list.append(r) 185 return r 186 187 async def async_wrapper(*args, **kwargs): 188 spy_obj.spy_return = None 189 spy_obj.spy_exception = None 190 try: 191 r = await method(*args, **kwargs) 192 except BaseException as e: 193 spy_obj.spy_exception = e 194 raise 195 else: 196 spy_obj.spy_return = r 197 spy_obj.spy_return_list.append(r) 198 return r 199 200 if asyncio.iscoroutinefunction(method): 201 wrapped = functools.update_wrapper(async_wrapper, method) 202 else: 203 wrapped = functools.update_wrapper(wrapper, method) 204 205 autospec = inspect.ismethod(method) or inspect.isfunction(method) 206 207 spy_obj = self.patch.object(obj, name, side_effect=wrapped, autospec=autospec) 208 spy_obj.spy_return = None 209 spy_obj.spy_return_list = [] 210 spy_obj.spy_exception = None 211 return spy_obj
Create a spy of method. It will run method normally, but it is now
possible to use mock
call features with it, like call count.
Parameters
- obj: An object.
- name: A method in object.
Returns
Spy object.
213 def stub(self, name: Optional[str] = None) -> unittest.mock.MagicMock: 214 """ 215 Create a stub method. It accepts any arguments. Ideal to register to 216 callbacks in tests. 217 218 :param name: the constructed stub's name as used in repr 219 :return: Stub object. 220 """ 221 return cast( 222 unittest.mock.MagicMock, 223 self.mock_module.MagicMock(spec=lambda *args, **kwargs: None, name=name), 224 )
Create a stub method. It accepts any arguments. Ideal to register to callbacks in tests.
Parameters
- name: the constructed stub's name as used in repr
Returns
Stub object.
226 def async_stub(self, name: Optional[str] = None) -> AsyncMockType: 227 """ 228 Create a async stub method. It accepts any arguments. Ideal to register to 229 callbacks in tests. 230 231 :param name: the constructed stub's name as used in repr 232 :return: Stub object. 233 """ 234 return cast( 235 AsyncMockType, 236 self.mock_module.AsyncMock(spec=lambda *args, **kwargs: None, name=name), 237 )
Create a async stub method. It accepts any arguments. Ideal to register to callbacks in tests.
Parameters
- name: the constructed stub's name as used in repr
Returns
Stub object.
41class PytestMockWarning(UserWarning): 42 """Base class for all warnings emitted by pytest-mock."""
Base class for all warnings emitted by pytest-mock.
Inherited Members
- builtins.UserWarning
- UserWarning
- builtins.BaseException
- with_traceback
- add_note
- args
697def pytest_addoption(parser: Any) -> None: 698 parser.addini( 699 "mock_traceback_monkeypatch", 700 "Monkeypatch the mock library to improve reporting of the " 701 "assert_called_... methods", 702 default=True, 703 ) 704 parser.addini( 705 "mock_use_standalone_module", 706 'Use standalone "mock" (from PyPI) instead of builtin "unittest.mock" ' 707 "on Python 3", 708 default=False, 709 )
455def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]: 456 """ 457 Return an object that has the same interface to the `mock` module, but 458 takes care of automatically undoing all patches after each test method. 459 """ 460 result = MockerFixture(pytestconfig) 461 yield result 462 result.stopall()
Return an object that has the same interface to the mock
module, but
takes care of automatically undoing all patches after each test method.
455def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]: 456 """ 457 Return an object that has the same interface to the `mock` module, but 458 takes care of automatically undoing all patches after each test method. 459 """ 460 result = MockerFixture(pytestconfig) 461 yield result 462 result.stopall()
Return an object that has the same interface to the mock
module, but
takes care of automatically undoing all patches after each test method.
455def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]: 456 """ 457 Return an object that has the same interface to the `mock` module, but 458 takes care of automatically undoing all patches after each test method. 459 """ 460 result = MockerFixture(pytestconfig) 461 yield result 462 result.stopall()
Return an object that has the same interface to the mock
module, but
takes care of automatically undoing all patches after each test method.
455def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]: 456 """ 457 Return an object that has the same interface to the `mock` module, but 458 takes care of automatically undoing all patches after each test method. 459 """ 460 result = MockerFixture(pytestconfig) 461 yield result 462 result.stopall()
Return an object that has the same interface to the mock
module, but
takes care of automatically undoing all patches after each test method.
455def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]: 456 """ 457 Return an object that has the same interface to the `mock` module, but 458 takes care of automatically undoing all patches after each test method. 459 """ 460 result = MockerFixture(pytestconfig) 461 yield result 462 result.stopall()
Return an object that has the same interface to the mock
module, but
takes care of automatically undoing all patches after each test method.