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

Fixture that provides the same interface to functions in the mock module, ensuring that they are uninstalled at the end of each test.

MockerFixture(config: Any)
 90    def __init__(self, config: Any) -> None:
 91        self._mock_cache: MockCache = MockCache()
 92        self.mock_module = mock_module = get_mock_module(config)
 93        self.patch = self._Patcher(self._mock_cache, mock_module)  # type: MockerFixture._Patcher
 94        # aliases for convenience
 95        self.Mock = mock_module.Mock
 96        self.MagicMock = mock_module.MagicMock
 97        self.NonCallableMock = mock_module.NonCallableMock
 98        self.NonCallableMagicMock = mock_module.NonCallableMagicMock
 99        self.PropertyMock = mock_module.PropertyMock
100        if hasattr(mock_module, "AsyncMock"):
101            self.AsyncMock = mock_module.AsyncMock
102        self.call = mock_module.call
103        self.ANY = mock_module.ANY
104        self.DEFAULT = mock_module.DEFAULT
105        self.sentinel = mock_module.sentinel
106        self.mock_open = mock_module.mock_open
107        if hasattr(mock_module, "seal"):
108            self.seal = mock_module.seal
patch
Mock
MagicMock
NonCallableMock
NonCallableMagicMock
PropertyMock
call
ANY
DEFAULT
sentinel
mock_open
def create_autospec( self, spec: Any, spec_set: bool = False, instance: bool = False, **kwargs: Any) -> Union[unittest.mock.MagicMock, unittest.mock.AsyncMock, unittest.mock.NonCallableMagicMock]:
110    def create_autospec(
111        self, spec: Any, spec_set: bool = False, instance: bool = False, **kwargs: Any
112    ) -> MockType:
113        m: MockType = self.mock_module.create_autospec(
114            spec, spec_set, instance, **kwargs
115        )
116        self._mock_cache.add(m)
117        return m
def resetall(self, *, return_value: bool = False, side_effect: bool = False) -> None:
119    def resetall(
120        self, *, return_value: bool = False, side_effect: bool = False
121    ) -> None:
122        """
123        Call reset_mock() on all patchers started by this fixture.
124
125        :param bool return_value: Reset the return_value of mocks.
126        :param bool side_effect: Reset the side_effect of mocks.
127        """
128        supports_reset_mock_with_args: Tuple[Type[Any], ...]
129        if hasattr(self, "AsyncMock"):
130            supports_reset_mock_with_args = (self.Mock, self.AsyncMock)
131        else:
132            supports_reset_mock_with_args = (self.Mock,)
133
134        for mock_item in self._mock_cache:
135            # See issue #237.
136            if not hasattr(mock_item.mock, "reset_mock"):
137                continue
138            # NOTE: The mock may be a dictionary
139            if hasattr(mock_item.mock, "spy_return_list"):
140                mock_item.mock.spy_return_list = []
141            if isinstance(mock_item.mock, supports_reset_mock_with_args):
142                mock_item.mock.reset_mock(
143                    return_value=return_value, side_effect=side_effect
144                )
145            else:
146                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.
def stopall(self) -> None:
148    def stopall(self) -> None:
149        """
150        Stop all patchers started by this fixture. Can be safely called multiple
151        times.
152        """
153        self._mock_cache.clear()

Stop all patchers started by this fixture. Can be safely called multiple times.

def stop(self, mock: unittest.mock.MagicMock) -> None:
155    def stop(self, mock: unittest.mock.MagicMock) -> None:
156        """
157        Stops a previous patch or spy call by passing the ``MagicMock`` object
158        returned by it.
159        """
160        self._mock_cache.remove(mock)

Stops a previous patch or spy call by passing the MagicMock object returned by it.

def spy( self, obj: object, name: str) -> Union[unittest.mock.MagicMock, unittest.mock.AsyncMock, unittest.mock.NonCallableMagicMock]:
162    def spy(self, obj: object, name: str) -> MockType:
163        """
164        Create a spy of method. It will run method normally, but it is now
165        possible to use `mock` call features with it, like call count.
166
167        :param obj: An object.
168        :param name: A method in object.
169        :return: Spy object.
170        """
171        method = getattr(obj, name)
172
173        def wrapper(*args, **kwargs):
174            spy_obj.spy_return = None
175            spy_obj.spy_exception = None
176            try:
177                r = method(*args, **kwargs)
178            except BaseException as e:
179                spy_obj.spy_exception = e
180                raise
181            else:
182                spy_obj.spy_return = r
183                spy_obj.spy_return_list.append(r)
184            return r
185
186        async def async_wrapper(*args, **kwargs):
187            spy_obj.spy_return = None
188            spy_obj.spy_exception = None
189            try:
190                r = await method(*args, **kwargs)
191            except BaseException as e:
192                spy_obj.spy_exception = e
193                raise
194            else:
195                spy_obj.spy_return = r
196                spy_obj.spy_return_list.append(r)
197            return r
198
199        if inspect.iscoroutinefunction(method):
200            wrapped = functools.update_wrapper(async_wrapper, method)
201        else:
202            wrapped = functools.update_wrapper(wrapper, method)
203
204        autospec = inspect.ismethod(method) or inspect.isfunction(method)
205
206        spy_obj = self.patch.object(obj, name, side_effect=wrapped, autospec=autospec)
207        spy_obj.spy_return = None
208        spy_obj.spy_return_list = []
209        spy_obj.spy_exception = None
210        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.

def stub(self, name: Optional[str] = None) -> unittest.mock.MagicMock:
212    def stub(self, name: Optional[str] = None) -> unittest.mock.MagicMock:
213        """
214        Create a stub method. It accepts any arguments. Ideal to register to
215        callbacks in tests.
216
217        :param name: the constructed stub's name as used in repr
218        :return: Stub object.
219        """
220        return cast(
221            unittest.mock.MagicMock,
222            self.mock_module.MagicMock(spec=lambda *args, **kwargs: None, name=name),
223        )

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.

def async_stub(self, name: Optional[str] = None) -> unittest.mock.AsyncMock:
225    def async_stub(self, name: Optional[str] = None) -> AsyncMockType:
226        """
227        Create a async stub method. It accepts any arguments. Ideal to register to
228        callbacks in tests.
229
230        :param name: the constructed stub's name as used in repr
231        :return: Stub object.
232        """
233        return cast(
234            AsyncMockType,
235            self.mock_module.AsyncMock(spec=lambda *args, **kwargs: None, name=name),
236        )

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.

MockFixture = <class 'MockerFixture'>
MockType = typing.Union[unittest.mock.MagicMock, unittest.mock.AsyncMock, unittest.mock.NonCallableMagicMock]
class PytestMockWarning(builtins.UserWarning):
40class PytestMockWarning(UserWarning):
41    """Base class for all warnings emitted by pytest-mock."""

Base class for all warnings emitted by pytest-mock.

def pytest_addoption(parser: Any) -> None:
696def pytest_addoption(parser: Any) -> None:
697    parser.addini(
698        "mock_traceback_monkeypatch",
699        "Monkeypatch the mock library to improve reporting of the "
700        "assert_called_... methods",
701        default=True,
702    )
703    parser.addini(
704        "mock_use_standalone_module",
705        'Use standalone "mock" (from PyPI) instead of builtin "unittest.mock" '
706        "on Python 3",
707        default=False,
708    )
def pytest_configure(config: Any) -> None:
711def pytest_configure(config: Any) -> None:
712    tb = config.getoption("--tb", default="auto")
713    if (
714        parse_ini_boolean(config.getini("mock_traceback_monkeypatch"))
715        and tb != "native"
716    ):
717        wrap_assert_methods(config)
def session_mocker( pytestconfig: Any) -> Generator[MockerFixture, NoneType, NoneType]:
454def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]:
455    """
456    Return an object that has the same interface to the `mock` module, but
457    takes care of automatically undoing all patches after each test method.
458    """
459    result = MockerFixture(pytestconfig)
460    yield result
461    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.

def package_mocker( pytestconfig: Any) -> Generator[MockerFixture, NoneType, NoneType]:
454def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]:
455    """
456    Return an object that has the same interface to the `mock` module, but
457    takes care of automatically undoing all patches after each test method.
458    """
459    result = MockerFixture(pytestconfig)
460    yield result
461    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.

def module_mocker( pytestconfig: Any) -> Generator[MockerFixture, NoneType, NoneType]:
454def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]:
455    """
456    Return an object that has the same interface to the `mock` module, but
457    takes care of automatically undoing all patches after each test method.
458    """
459    result = MockerFixture(pytestconfig)
460    yield result
461    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.

def class_mocker( pytestconfig: Any) -> Generator[MockerFixture, NoneType, NoneType]:
454def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]:
455    """
456    Return an object that has the same interface to the `mock` module, but
457    takes care of automatically undoing all patches after each test method.
458    """
459    result = MockerFixture(pytestconfig)
460    yield result
461    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.

def mocker( pytestconfig: Any) -> Generator[MockerFixture, NoneType, NoneType]:
454def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]:
455    """
456    Return an object that has the same interface to the `mock` module, but
457    takes care of automatically undoing all patches after each test method.
458    """
459    result = MockerFixture(pytestconfig)
460    yield result
461    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.