| 1 |
"""Generic mock functions for unit-tests. |
| 2 |
|
| 3 |
Use `check_call` as a context manager to mock calls and their return values as |
| 4 |
well to check if the method was called (or not). |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import contextlib |
| 10 |
from typing import TYPE_CHECKING, Any, overload |
| 11 |
|
| 12 |
from _pytest.monkeypatch import MonkeyPatch |
| 13 |
|
| 14 |
if TYPE_CHECKING: |
| 15 |
from collections.abc import Generator |
| 16 |
from types import ModuleType |
| 17 |
|
| 18 |
Call = tuple[tuple[Any, ...], dict[str, Any]] |
| 19 |
CallList = list[Call] |
| 20 |
|
| 21 |
|
| 22 |
@overload |
| 23 |
@contextlib.contextmanager |
| 24 |
def _mp_call( |
| 25 |
monkeypatch: MonkeyPatch, |
| 26 |
mock_class: type[Any] | ModuleType, |
| 27 |
method: str, |
| 28 |
return_value: Any, # noqa: ANN401 |
| 29 |
as_property: bool, |
| 30 |
) -> CallList: ... |
| 31 |
|
| 32 |
|
| 33 |
@overload |
| 34 |
@contextlib.contextmanager |
| 35 |
def _mp_call( |
| 36 |
monkeypatch: MonkeyPatch, |
| 37 |
mock_class: str, |
| 38 |
method: Any, # return value in this case # noqa: ANN401 |
| 39 |
return_value: bool, # as_property in this case |
| 40 |
) -> CallList: ... |
| 41 |
|
| 42 |
|
| 43 |
def _mp_call( |
| 44 |
monkeypatch: MonkeyPatch, |
| 45 |
mock_class: type[Any] | ModuleType | str, |
| 46 |
method: str | Any, |
| 47 |
return_value: Any, |
| 48 |
as_property: bool = False, |
| 49 |
) -> CallList: |
| 50 |
"""Mock a method in a class and record the calls to it. |
| 51 |
|
| 52 |
If the given return_value is an Exception, it will be raised. |
| 53 |
If not, the value will be returned from the mocked function/method. |
| 54 |
""" |
| 55 |
calls: CallList = [] |
| 56 |
|
| 57 |
def func_call(*a: Any, **k: Any) -> Any: # noqa: ANN401 |
| 58 |
"""Mock the function call.""" |
| 59 |
calls.append((a, k)) |
| 60 |
if isinstance(return_value, Exception): |
| 61 |
# bug in pylint https://www.logilab.org/ticket/3207 |
| 62 |
raise return_value # pylint: disable-msg=raising-bad-type |
| 63 |
if callable(return_value): |
| 64 |
# Handle the case that a function was passed |
| 65 |
return return_value(*a, **k) |
| 66 |
return return_value |
| 67 |
|
| 68 |
# first case handles class + method, second one mock as str |
| 69 |
if as_property or (isinstance(mock_class, str) and return_value): |
| 70 |
callback = property(func_call) |
| 71 |
else: |
| 72 |
callback = func_call |
| 73 |
|
| 74 |
if isinstance(mock_class, str): |
| 75 |
return_value = method |
| 76 |
monkeypatch.setattr(mock_class, callback) |
| 77 |
else: |
| 78 |
monkeypatch.setattr(mock_class, method, callback) |
| 79 |
return calls |
| 80 |
|
| 81 |
|
| 82 |
@contextlib.contextmanager |
| 83 |
def check_call( # pylint: disable=too-many-arguments |
| 84 |
mock_class: type[Any] | ModuleType, |
| 85 |
method: str, |
| 86 |
return_value: Any = None, # noqa: ANN401 |
| 87 |
call_args_list: None | list[tuple[Any, ...]] = None, |
| 88 |
call_kwargs_list: None | list[dict[str, Any]] = None, |
| 89 |
call_count: int = 1, |
| 90 |
as_property: bool = False, |
| 91 |
) -> Generator[CallList, None, None]: |
| 92 |
"""Context manager for mocking and checking a call to a method. |
| 93 |
|
| 94 |
If called is greater 0, and call_args and call_kwargs are given, the context manager |
| 95 |
will check that the mocked method was called with those arguments. Also, it will |
| 96 |
assert that the mock was called exactly once. |
| 97 |
|
| 98 |
If called is False, it will assert that the mock was not called. |
| 99 |
|
| 100 |
If a return_value is given, the mock will return this value. One can pass an |
| 101 |
exception that will be raised by the mocked method instead of returning a value. |
| 102 |
If a Callable is passed, it will be called and its return value returned. |
| 103 |
""" |
| 104 |
assert (call_args_list is not None and call_kwargs_list is not None) or ( # noqa: S101 |
| 105 |
call_args_list is None and call_kwargs_list is None |
| 106 |
), "call_args and call_kwargs must be None or have a value (list/dict if empty)" |
| 107 |
monkeypatch = MonkeyPatch() |
| 108 |
calls = _mp_call(monkeypatch, mock_class, method, return_value, as_property) |
| 109 |
try: |
| 110 |
yield calls |
| 111 |
finally: |
| 112 |
m_name = f"{mock_class.__name__}.{method}" |
| 113 |
monkeypatch.undo() |
| 114 |
assert_calls(call_count, call_args_list, call_kwargs_list, calls, m_name) |
| 115 |
|
| 116 |
|
| 117 |
# Duplicate the code because overloading is a mess due to this bug: |
| 118 |
# https://github.com/python/mypy/issues/11373 |
| 119 |
@contextlib.contextmanager |
| 120 |
def check_call_str( # pylint: disable=too-many-arguments |
| 121 |
mock_class: str, |
| 122 |
return_value: Any = None, # noqa: ANN401 |
| 123 |
call_args_list: None | list[tuple[Any, ...]] = None, |
| 124 |
call_kwargs_list: None | list[dict[str, Any]] = None, |
| 125 |
call_count: int = 1, |
| 126 |
as_property: bool = False, |
| 127 |
) -> Generator[CallList, None, None]: |
| 128 |
"""Context manager for mocking and checking a call to a method. |
| 129 |
|
| 130 |
See `check_call` documentation. |
| 131 |
""" |
| 132 |
assert (call_args_list is not None and call_kwargs_list is not None) or ( # noqa: S101 |
| 133 |
call_args_list is None and call_kwargs_list is None |
| 134 |
), "call_args and call_kwargs must be None or have a value (list/dict if empty)" |
| 135 |
monkeypatch = MonkeyPatch() |
| 136 |
calls = _mp_call(monkeypatch, mock_class, return_value, as_property) |
| 137 |
yield calls |
| 138 |
m_name = mock_class |
| 139 |
monkeypatch.undo() |
| 140 |
assert_calls(call_count, call_args_list, call_kwargs_list, calls, m_name) |
| 141 |
|
| 142 |
|
| 143 |
def assert_calls( |
| 144 |
call_count: int, |
| 145 |
call_args_list: None | list[tuple[Any, ...]], |
| 146 |
call_kwargs_list: None | list[dict[str, Any]], |
| 147 |
calls: CallList, |
| 148 |
m_name: str, |
| 149 |
) -> None: |
| 150 |
"""Check that the calls made to the mocked function are correct.""" |
| 151 |
if call_count != -1: |
| 152 |
assert len(calls) == call_count, ( # noqa: S101 |
| 153 |
f"Expected {call_count} calls to {m_name} but got: {len(calls)}" |
| 154 |
) |
| 155 |
if call_args_list and call_kwargs_list: |
| 156 |
for idx, call_args in enumerate(call_args_list): |
| 157 |
assert call_args == calls[idx][0], ( # noqa: S101 |
| 158 |
f"Args to {m_name}: {call_args} expected: {call_args}" |
| 159 |
) |
| 160 |
for idx, call_kwargs in enumerate(call_kwargs_list): |
| 161 |
assert call_kwargs == calls[idx][1], ( # noqa: S101 |
| 162 |
f"Kwargs to {m_name}: {call_kwargs} expected: {call_kwargs}" |
| 163 |
) |