Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1 | # mock.py |
| 2 | # Test tools for mocking and patching. |
Michael Foord | c17adf4 | 2012-03-14 13:30:29 -0700 | [diff] [blame] | 3 | # Maintained by Michael Foord |
| 4 | # Backport for other versions of Python available from |
Ned Deily | 9d6d06e | 2018-06-11 00:45:50 -0400 | [diff] [blame] | 5 | # https://pypi.org/project/mock |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 6 | |
| 7 | __all__ = ( |
| 8 | 'Mock', |
| 9 | 'MagicMock', |
| 10 | 'patch', |
| 11 | 'sentinel', |
| 12 | 'DEFAULT', |
| 13 | 'ANY', |
| 14 | 'call', |
| 15 | 'create_autospec', |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 16 | 'AsyncMock', |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 17 | 'FILTER_DIR', |
| 18 | 'NonCallableMock', |
| 19 | 'NonCallableMagicMock', |
| 20 | 'mock_open', |
| 21 | 'PropertyMock', |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 22 | 'seal', |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 23 | ) |
| 24 | |
| 25 | |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 26 | import asyncio |
Xtreak | 436c2b0 | 2019-05-28 12:37:39 +0530 | [diff] [blame] | 27 | import contextlib |
Rémi Lapeyre | 11a8832 | 2019-05-07 12:48:36 +0200 | [diff] [blame] | 28 | import io |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 29 | import inspect |
| 30 | import pprint |
| 31 | import sys |
Michael Foord | fddcfa2 | 2014-04-14 16:25:20 -0400 | [diff] [blame] | 32 | import builtins |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 33 | from types import CodeType, ModuleType, MethodType |
Petter Strandmark | 47d9424 | 2018-10-28 21:37:10 +0100 | [diff] [blame] | 34 | from unittest.util import safe_repr |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 35 | from functools import wraps, partial |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 36 | |
| 37 | |
Michael Foord | fddcfa2 | 2014-04-14 16:25:20 -0400 | [diff] [blame] | 38 | _builtins = {name for name in dir(builtins) if not name.startswith('_')} |
| 39 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 40 | FILTER_DIR = True |
| 41 | |
Nick Coghlan | 0b43bcf | 2012-05-27 18:17:07 +1000 | [diff] [blame] | 42 | # Workaround for issue #12370 |
| 43 | # Without this, the __class__ properties wouldn't be set correctly |
| 44 | _safe_super = super |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 45 | |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 46 | def _is_async_obj(obj): |
Lisa Roach | f1a297a | 2019-09-10 12:18:40 +0100 | [diff] [blame] | 47 | if _is_instance_mock(obj) and not isinstance(obj, AsyncMock): |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 48 | return False |
Lisa Roach | f1a297a | 2019-09-10 12:18:40 +0100 | [diff] [blame] | 49 | return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj) |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 50 | |
| 51 | |
Xtreak | ff6b2e6 | 2019-05-27 18:26:23 +0530 | [diff] [blame] | 52 | def _is_async_func(func): |
| 53 | if getattr(func, '__code__', None): |
| 54 | return asyncio.iscoroutinefunction(func) |
| 55 | else: |
| 56 | return False |
| 57 | |
| 58 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 59 | def _is_instance_mock(obj): |
| 60 | # can't use isinstance on Mock objects because they override __class__ |
| 61 | # The base class for all mocks is NonCallableMock |
| 62 | return issubclass(type(obj), NonCallableMock) |
| 63 | |
| 64 | |
| 65 | def _is_exception(obj): |
| 66 | return ( |
Chris Withers | 49e27f0 | 2019-05-01 08:48:44 +0100 | [diff] [blame] | 67 | isinstance(obj, BaseException) or |
| 68 | isinstance(obj, type) and issubclass(obj, BaseException) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 69 | ) |
| 70 | |
| 71 | |
Xtreak | 7397cda | 2019-07-22 13:08:22 +0530 | [diff] [blame] | 72 | def _extract_mock(obj): |
| 73 | # Autospecced functions will return a FunctionType with "mock" attribute |
| 74 | # which is the actual mock object that needs to be used. |
| 75 | if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'): |
| 76 | return obj.mock |
| 77 | else: |
| 78 | return obj |
| 79 | |
| 80 | |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 81 | def _get_signature_object(func, as_instance, eat_self): |
| 82 | """ |
| 83 | Given an arbitrary, possibly callable object, try to create a suitable |
| 84 | signature object. |
| 85 | Return a (reduced func, signature) tuple, or None. |
| 86 | """ |
| 87 | if isinstance(func, type) and not as_instance: |
| 88 | # If it's a type and should be modelled as a type, use __init__. |
Chris Withers | adbf178 | 2019-05-01 23:04:04 +0100 | [diff] [blame] | 89 | func = func.__init__ |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 90 | # Skip the `self` argument in __init__ |
| 91 | eat_self = True |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 92 | elif not isinstance(func, FunctionTypes): |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 93 | # If we really want to model an instance of the passed type, |
| 94 | # __call__ should be looked up, not __init__. |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 95 | try: |
| 96 | func = func.__call__ |
| 97 | except AttributeError: |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 98 | return None |
| 99 | if eat_self: |
| 100 | sig_func = partial(func, None) |
| 101 | else: |
| 102 | sig_func = func |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 103 | try: |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 104 | return func, inspect.signature(sig_func) |
| 105 | except ValueError: |
| 106 | # Certain callable types are not supported by inspect.signature() |
| 107 | return None |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 108 | |
| 109 | |
| 110 | def _check_signature(func, mock, skipfirst, instance=False): |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 111 | sig = _get_signature_object(func, instance, skipfirst) |
| 112 | if sig is None: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 113 | return |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 114 | func, sig = sig |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 115 | def checksig(self, /, *args, **kwargs): |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 116 | sig.bind(*args, **kwargs) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 117 | _copy_func_details(func, checksig) |
| 118 | type(mock)._mock_check_sig = checksig |
Xtreak | f7fa62e | 2018-12-12 13:24:54 +0530 | [diff] [blame] | 119 | type(mock).__signature__ = sig |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 120 | |
| 121 | |
| 122 | def _copy_func_details(func, funcopy): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 123 | # we explicitly don't copy func.__dict__ into this copy as it would |
| 124 | # expose original attributes that should be mocked |
Berker Peksag | 161a4dd | 2016-12-15 05:21:44 +0300 | [diff] [blame] | 125 | for attribute in ( |
| 126 | '__name__', '__doc__', '__text_signature__', |
| 127 | '__module__', '__defaults__', '__kwdefaults__', |
| 128 | ): |
| 129 | try: |
| 130 | setattr(funcopy, attribute, getattr(func, attribute)) |
| 131 | except AttributeError: |
| 132 | pass |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 133 | |
| 134 | |
| 135 | def _callable(obj): |
| 136 | if isinstance(obj, type): |
| 137 | return True |
Xtreak | 9b21856 | 2019-04-22 08:00:23 +0530 | [diff] [blame] | 138 | if isinstance(obj, (staticmethod, classmethod, MethodType)): |
| 139 | return _callable(obj.__func__) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 140 | if getattr(obj, '__call__', None) is not None: |
| 141 | return True |
| 142 | return False |
| 143 | |
| 144 | |
| 145 | def _is_list(obj): |
| 146 | # checks for list or tuples |
| 147 | # XXXX badly named! |
| 148 | return type(obj) in (list, tuple) |
| 149 | |
| 150 | |
| 151 | def _instance_callable(obj): |
| 152 | """Given an object, return True if the object is callable. |
| 153 | For classes, return True if instances would be callable.""" |
| 154 | if not isinstance(obj, type): |
| 155 | # already an instance |
| 156 | return getattr(obj, '__call__', None) is not None |
| 157 | |
Michael Foord | a74b3aa | 2012-03-14 14:40:22 -0700 | [diff] [blame] | 158 | # *could* be broken by a class overriding __mro__ or __dict__ via |
| 159 | # a metaclass |
| 160 | for base in (obj,) + obj.__mro__: |
| 161 | if base.__dict__.get('__call__') is not None: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 162 | return True |
| 163 | return False |
| 164 | |
| 165 | |
| 166 | def _set_signature(mock, original, instance=False): |
| 167 | # creates a function with signature (*args, **kwargs) that delegates to a |
| 168 | # mock. It still does signature checking by calling a lambda with the same |
| 169 | # signature as the original. |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 170 | |
| 171 | skipfirst = isinstance(original, type) |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 172 | result = _get_signature_object(original, instance, skipfirst) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 173 | if result is None: |
Aaron Gallagher | 856cbcc | 2017-07-19 17:01:14 -0700 | [diff] [blame] | 174 | return mock |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 175 | func, sig = result |
| 176 | def checksig(*args, **kwargs): |
| 177 | sig.bind(*args, **kwargs) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 178 | _copy_func_details(func, checksig) |
| 179 | |
| 180 | name = original.__name__ |
| 181 | if not name.isidentifier(): |
| 182 | name = 'funcopy' |
Michael Foord | 313f85f | 2012-03-25 18:16:07 +0100 | [diff] [blame] | 183 | context = {'_checksig_': checksig, 'mock': mock} |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 184 | src = """def %s(*args, **kwargs): |
Michael Foord | 313f85f | 2012-03-25 18:16:07 +0100 | [diff] [blame] | 185 | _checksig_(*args, **kwargs) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 186 | return mock(*args, **kwargs)""" % name |
| 187 | exec (src, context) |
| 188 | funcopy = context[name] |
Xtreak | f7fa62e | 2018-12-12 13:24:54 +0530 | [diff] [blame] | 189 | _setup_func(funcopy, mock, sig) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 190 | return funcopy |
| 191 | |
| 192 | |
Xtreak | f7fa62e | 2018-12-12 13:24:54 +0530 | [diff] [blame] | 193 | def _setup_func(funcopy, mock, sig): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 194 | funcopy.mock = mock |
| 195 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 196 | def assert_called_with(*args, **kwargs): |
| 197 | return mock.assert_called_with(*args, **kwargs) |
Gregory P. Smith | ac5084b | 2016-10-06 14:31:23 -0700 | [diff] [blame] | 198 | def assert_called(*args, **kwargs): |
| 199 | return mock.assert_called(*args, **kwargs) |
| 200 | def assert_not_called(*args, **kwargs): |
| 201 | return mock.assert_not_called(*args, **kwargs) |
| 202 | def assert_called_once(*args, **kwargs): |
| 203 | return mock.assert_called_once(*args, **kwargs) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 204 | def assert_called_once_with(*args, **kwargs): |
| 205 | return mock.assert_called_once_with(*args, **kwargs) |
| 206 | def assert_has_calls(*args, **kwargs): |
| 207 | return mock.assert_has_calls(*args, **kwargs) |
| 208 | def assert_any_call(*args, **kwargs): |
| 209 | return mock.assert_any_call(*args, **kwargs) |
| 210 | def reset_mock(): |
| 211 | funcopy.method_calls = _CallList() |
| 212 | funcopy.mock_calls = _CallList() |
| 213 | mock.reset_mock() |
| 214 | ret = funcopy.return_value |
| 215 | if _is_instance_mock(ret) and not ret is mock: |
| 216 | ret.reset_mock() |
| 217 | |
| 218 | funcopy.called = False |
| 219 | funcopy.call_count = 0 |
| 220 | funcopy.call_args = None |
| 221 | funcopy.call_args_list = _CallList() |
| 222 | funcopy.method_calls = _CallList() |
| 223 | funcopy.mock_calls = _CallList() |
| 224 | |
| 225 | funcopy.return_value = mock.return_value |
| 226 | funcopy.side_effect = mock.side_effect |
| 227 | funcopy._mock_children = mock._mock_children |
| 228 | |
| 229 | funcopy.assert_called_with = assert_called_with |
| 230 | funcopy.assert_called_once_with = assert_called_once_with |
| 231 | funcopy.assert_has_calls = assert_has_calls |
| 232 | funcopy.assert_any_call = assert_any_call |
| 233 | funcopy.reset_mock = reset_mock |
Gregory P. Smith | ac5084b | 2016-10-06 14:31:23 -0700 | [diff] [blame] | 234 | funcopy.assert_called = assert_called |
| 235 | funcopy.assert_not_called = assert_not_called |
| 236 | funcopy.assert_called_once = assert_called_once |
Xtreak | f7fa62e | 2018-12-12 13:24:54 +0530 | [diff] [blame] | 237 | funcopy.__signature__ = sig |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 238 | |
| 239 | mock._mock_delegate = funcopy |
| 240 | |
| 241 | |
Xtreak | ff6b2e6 | 2019-05-27 18:26:23 +0530 | [diff] [blame] | 242 | def _setup_async_mock(mock): |
| 243 | mock._is_coroutine = asyncio.coroutines._is_coroutine |
| 244 | mock.await_count = 0 |
| 245 | mock.await_args = None |
| 246 | mock.await_args_list = _CallList() |
Xtreak | ff6b2e6 | 2019-05-27 18:26:23 +0530 | [diff] [blame] | 247 | |
| 248 | # Mock is not configured yet so the attributes are set |
| 249 | # to a function and then the corresponding mock helper function |
| 250 | # is called when the helper is accessed similar to _setup_func. |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 251 | def wrapper(attr, /, *args, **kwargs): |
Xtreak | ff6b2e6 | 2019-05-27 18:26:23 +0530 | [diff] [blame] | 252 | return getattr(mock.mock, attr)(*args, **kwargs) |
| 253 | |
| 254 | for attribute in ('assert_awaited', |
| 255 | 'assert_awaited_once', |
| 256 | 'assert_awaited_with', |
| 257 | 'assert_awaited_once_with', |
| 258 | 'assert_any_await', |
| 259 | 'assert_has_awaits', |
| 260 | 'assert_not_awaited'): |
| 261 | |
| 262 | # setattr(mock, attribute, wrapper) causes late binding |
| 263 | # hence attribute will always be the last value in the loop |
| 264 | # Use partial(wrapper, attribute) to ensure the attribute is bound |
| 265 | # correctly. |
| 266 | setattr(mock, attribute, partial(wrapper, attribute)) |
| 267 | |
| 268 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 269 | def _is_magic(name): |
| 270 | return '__%s__' % name[2:-2] == name |
| 271 | |
| 272 | |
| 273 | class _SentinelObject(object): |
| 274 | "A unique, named, sentinel object." |
| 275 | def __init__(self, name): |
| 276 | self.name = name |
| 277 | |
| 278 | def __repr__(self): |
| 279 | return 'sentinel.%s' % self.name |
| 280 | |
Serhiy Storchaka | d9c956f | 2017-01-11 20:13:03 +0200 | [diff] [blame] | 281 | def __reduce__(self): |
| 282 | return 'sentinel.%s' % self.name |
| 283 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 284 | |
| 285 | class _Sentinel(object): |
| 286 | """Access attributes to return a named object, usable as a sentinel.""" |
| 287 | def __init__(self): |
| 288 | self._sentinels = {} |
| 289 | |
| 290 | def __getattr__(self, name): |
| 291 | if name == '__bases__': |
| 292 | # Without this help(unittest.mock) raises an exception |
| 293 | raise AttributeError |
| 294 | return self._sentinels.setdefault(name, _SentinelObject(name)) |
| 295 | |
Serhiy Storchaka | d9c956f | 2017-01-11 20:13:03 +0200 | [diff] [blame] | 296 | def __reduce__(self): |
| 297 | return 'sentinel' |
| 298 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 299 | |
| 300 | sentinel = _Sentinel() |
| 301 | |
| 302 | DEFAULT = sentinel.DEFAULT |
| 303 | _missing = sentinel.MISSING |
| 304 | _deleted = sentinel.DELETED |
| 305 | |
| 306 | |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 307 | _allowed_names = { |
| 308 | 'return_value', '_mock_return_value', 'side_effect', |
| 309 | '_mock_side_effect', '_mock_parent', '_mock_new_parent', |
| 310 | '_mock_name', '_mock_new_name' |
| 311 | } |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 312 | |
| 313 | |
| 314 | def _delegating_property(name): |
| 315 | _allowed_names.add(name) |
| 316 | _the_name = '_mock_' + name |
| 317 | def _get(self, name=name, _the_name=_the_name): |
| 318 | sig = self._mock_delegate |
| 319 | if sig is None: |
| 320 | return getattr(self, _the_name) |
| 321 | return getattr(sig, name) |
| 322 | def _set(self, value, name=name, _the_name=_the_name): |
| 323 | sig = self._mock_delegate |
| 324 | if sig is None: |
| 325 | self.__dict__[_the_name] = value |
| 326 | else: |
| 327 | setattr(sig, name, value) |
| 328 | |
| 329 | return property(_get, _set) |
| 330 | |
| 331 | |
| 332 | |
| 333 | class _CallList(list): |
| 334 | |
| 335 | def __contains__(self, value): |
| 336 | if not isinstance(value, list): |
| 337 | return list.__contains__(self, value) |
| 338 | len_value = len(value) |
| 339 | len_self = len(self) |
| 340 | if len_value > len_self: |
| 341 | return False |
| 342 | |
| 343 | for i in range(0, len_self - len_value + 1): |
| 344 | sub_list = self[i:i+len_value] |
| 345 | if sub_list == value: |
| 346 | return True |
| 347 | return False |
| 348 | |
| 349 | def __repr__(self): |
| 350 | return pprint.pformat(list(self)) |
| 351 | |
| 352 | |
| 353 | def _check_and_set_parent(parent, value, name, new_name): |
Xtreak | 7397cda | 2019-07-22 13:08:22 +0530 | [diff] [blame] | 354 | value = _extract_mock(value) |
Xtreak | 9c3f284 | 2019-02-26 03:16:34 +0530 | [diff] [blame] | 355 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 356 | if not _is_instance_mock(value): |
| 357 | return False |
| 358 | if ((value._mock_name or value._mock_new_name) or |
| 359 | (value._mock_parent is not None) or |
| 360 | (value._mock_new_parent is not None)): |
| 361 | return False |
| 362 | |
| 363 | _parent = parent |
| 364 | while _parent is not None: |
| 365 | # setting a mock (value) as a child or return value of itself |
| 366 | # should not modify the mock |
| 367 | if _parent is value: |
| 368 | return False |
| 369 | _parent = _parent._mock_new_parent |
| 370 | |
| 371 | if new_name: |
| 372 | value._mock_new_parent = parent |
| 373 | value._mock_new_name = new_name |
| 374 | if name: |
| 375 | value._mock_parent = parent |
| 376 | value._mock_name = name |
| 377 | return True |
| 378 | |
Michael Foord | 01bafdc | 2014-04-14 16:09:42 -0400 | [diff] [blame] | 379 | # Internal class to identify if we wrapped an iterator object or not. |
| 380 | class _MockIter(object): |
| 381 | def __init__(self, obj): |
| 382 | self.obj = iter(obj) |
Michael Foord | 01bafdc | 2014-04-14 16:09:42 -0400 | [diff] [blame] | 383 | def __next__(self): |
| 384 | return next(self.obj) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 385 | |
| 386 | class Base(object): |
| 387 | _mock_return_value = DEFAULT |
| 388 | _mock_side_effect = None |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 389 | def __init__(self, /, *args, **kwargs): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 390 | pass |
| 391 | |
| 392 | |
| 393 | |
| 394 | class NonCallableMock(Base): |
| 395 | """A non-callable version of `Mock`""" |
| 396 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 397 | def __new__(cls, /, *args, **kw): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 398 | # every instance has its own class |
| 399 | # so we can create magic methods on the |
| 400 | # class without stomping on other mocks |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 401 | bases = (cls,) |
Michael Foord | 14fd925 | 2019-09-13 18:40:56 +0200 | [diff] [blame] | 402 | if not issubclass(cls, AsyncMockMixin): |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 403 | # Check if spec is an async object or function |
Michael Foord | 14fd925 | 2019-09-13 18:40:56 +0200 | [diff] [blame] | 404 | bound_args = _MOCK_SIG.bind_partial(cls, *args, **kw).arguments |
| 405 | spec_arg = bound_args.get('spec_set', bound_args.get('spec')) |
| 406 | if spec_arg and _is_async_obj(spec_arg): |
| 407 | bases = (AsyncMockMixin, cls) |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 408 | new = type(cls.__name__, bases, {'__doc__': cls.__doc__}) |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 409 | instance = _safe_super(NonCallableMock, cls).__new__(new) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 410 | return instance |
| 411 | |
| 412 | |
| 413 | def __init__( |
| 414 | self, spec=None, wraps=None, name=None, spec_set=None, |
| 415 | parent=None, _spec_state=None, _new_name='', _new_parent=None, |
Kushal Das | 8c14534 | 2014-04-16 23:32:21 +0530 | [diff] [blame] | 416 | _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 417 | ): |
| 418 | if _new_parent is None: |
| 419 | _new_parent = parent |
| 420 | |
| 421 | __dict__ = self.__dict__ |
| 422 | __dict__['_mock_parent'] = parent |
| 423 | __dict__['_mock_name'] = name |
| 424 | __dict__['_mock_new_name'] = _new_name |
| 425 | __dict__['_mock_new_parent'] = _new_parent |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 426 | __dict__['_mock_sealed'] = False |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 427 | |
| 428 | if spec_set is not None: |
| 429 | spec = spec_set |
| 430 | spec_set = True |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 431 | if _eat_self is None: |
| 432 | _eat_self = parent is not None |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 433 | |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 434 | self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 435 | |
| 436 | __dict__['_mock_children'] = {} |
| 437 | __dict__['_mock_wraps'] = wraps |
| 438 | __dict__['_mock_delegate'] = None |
| 439 | |
| 440 | __dict__['_mock_called'] = False |
| 441 | __dict__['_mock_call_args'] = None |
| 442 | __dict__['_mock_call_count'] = 0 |
| 443 | __dict__['_mock_call_args_list'] = _CallList() |
| 444 | __dict__['_mock_mock_calls'] = _CallList() |
| 445 | |
| 446 | __dict__['method_calls'] = _CallList() |
Kushal Das | 8c14534 | 2014-04-16 23:32:21 +0530 | [diff] [blame] | 447 | __dict__['_mock_unsafe'] = unsafe |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 448 | |
| 449 | if kwargs: |
| 450 | self.configure_mock(**kwargs) |
| 451 | |
Nick Coghlan | 0b43bcf | 2012-05-27 18:17:07 +1000 | [diff] [blame] | 452 | _safe_super(NonCallableMock, self).__init__( |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 453 | spec, wraps, name, spec_set, parent, |
| 454 | _spec_state |
| 455 | ) |
| 456 | |
| 457 | |
| 458 | def attach_mock(self, mock, attribute): |
| 459 | """ |
| 460 | Attach a mock as an attribute of this one, replacing its name and |
| 461 | parent. Calls to the attached mock will be recorded in the |
| 462 | `method_calls` and `mock_calls` attributes of this one.""" |
Xtreak | 7397cda | 2019-07-22 13:08:22 +0530 | [diff] [blame] | 463 | inner_mock = _extract_mock(mock) |
| 464 | |
| 465 | inner_mock._mock_parent = None |
| 466 | inner_mock._mock_new_parent = None |
| 467 | inner_mock._mock_name = '' |
| 468 | inner_mock._mock_new_name = None |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 469 | |
| 470 | setattr(self, attribute, mock) |
| 471 | |
| 472 | |
| 473 | def mock_add_spec(self, spec, spec_set=False): |
| 474 | """Add a spec to a mock. `spec` can either be an object or a |
| 475 | list of strings. Only attributes on the `spec` can be fetched as |
| 476 | attributes from the mock. |
| 477 | |
| 478 | If `spec_set` is True then only attributes on the spec can be set.""" |
| 479 | self._mock_add_spec(spec, spec_set) |
| 480 | |
| 481 | |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 482 | def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False, |
| 483 | _eat_self=False): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 484 | _spec_class = None |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 485 | _spec_signature = None |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 486 | _spec_asyncs = [] |
| 487 | |
| 488 | for attr in dir(spec): |
| 489 | if asyncio.iscoroutinefunction(getattr(spec, attr, None)): |
| 490 | _spec_asyncs.append(attr) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 491 | |
| 492 | if spec is not None and not _is_list(spec): |
| 493 | if isinstance(spec, type): |
| 494 | _spec_class = spec |
| 495 | else: |
Chris Withers | adbf178 | 2019-05-01 23:04:04 +0100 | [diff] [blame] | 496 | _spec_class = type(spec) |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 497 | res = _get_signature_object(spec, |
| 498 | _spec_as_instance, _eat_self) |
| 499 | _spec_signature = res and res[1] |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 500 | |
| 501 | spec = dir(spec) |
| 502 | |
| 503 | __dict__ = self.__dict__ |
| 504 | __dict__['_spec_class'] = _spec_class |
| 505 | __dict__['_spec_set'] = spec_set |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 506 | __dict__['_spec_signature'] = _spec_signature |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 507 | __dict__['_mock_methods'] = spec |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 508 | __dict__['_spec_asyncs'] = _spec_asyncs |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 509 | |
| 510 | def __get_return_value(self): |
| 511 | ret = self._mock_return_value |
| 512 | if self._mock_delegate is not None: |
| 513 | ret = self._mock_delegate.return_value |
| 514 | |
| 515 | if ret is DEFAULT: |
| 516 | ret = self._get_child_mock( |
| 517 | _new_parent=self, _new_name='()' |
| 518 | ) |
| 519 | self.return_value = ret |
| 520 | return ret |
| 521 | |
| 522 | |
| 523 | def __set_return_value(self, value): |
| 524 | if self._mock_delegate is not None: |
| 525 | self._mock_delegate.return_value = value |
| 526 | else: |
| 527 | self._mock_return_value = value |
| 528 | _check_and_set_parent(self, value, None, '()') |
| 529 | |
| 530 | __return_value_doc = "The value to be returned when the mock is called." |
| 531 | return_value = property(__get_return_value, __set_return_value, |
| 532 | __return_value_doc) |
| 533 | |
| 534 | |
| 535 | @property |
| 536 | def __class__(self): |
| 537 | if self._spec_class is None: |
| 538 | return type(self) |
| 539 | return self._spec_class |
| 540 | |
| 541 | called = _delegating_property('called') |
| 542 | call_count = _delegating_property('call_count') |
| 543 | call_args = _delegating_property('call_args') |
| 544 | call_args_list = _delegating_property('call_args_list') |
| 545 | mock_calls = _delegating_property('mock_calls') |
| 546 | |
| 547 | |
| 548 | def __get_side_effect(self): |
| 549 | delegated = self._mock_delegate |
| 550 | if delegated is None: |
| 551 | return self._mock_side_effect |
Michael Foord | 01bafdc | 2014-04-14 16:09:42 -0400 | [diff] [blame] | 552 | sf = delegated.side_effect |
Robert Collins | f58f88c | 2015-07-14 13:51:40 +1200 | [diff] [blame] | 553 | if (sf is not None and not callable(sf) |
| 554 | and not isinstance(sf, _MockIter) and not _is_exception(sf)): |
Michael Foord | 01bafdc | 2014-04-14 16:09:42 -0400 | [diff] [blame] | 555 | sf = _MockIter(sf) |
| 556 | delegated.side_effect = sf |
| 557 | return sf |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 558 | |
| 559 | def __set_side_effect(self, value): |
| 560 | value = _try_iter(value) |
| 561 | delegated = self._mock_delegate |
| 562 | if delegated is None: |
| 563 | self._mock_side_effect = value |
| 564 | else: |
| 565 | delegated.side_effect = value |
| 566 | |
| 567 | side_effect = property(__get_side_effect, __set_side_effect) |
| 568 | |
| 569 | |
Kushal Das | 9cd39a1 | 2016-06-02 10:20:16 -0700 | [diff] [blame] | 570 | def reset_mock(self, visited=None,*, return_value=False, side_effect=False): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 571 | "Restore the mock object to its initial state." |
Robert Collins | b37f43f | 2015-07-15 11:42:28 +1200 | [diff] [blame] | 572 | if visited is None: |
| 573 | visited = [] |
| 574 | if id(self) in visited: |
| 575 | return |
| 576 | visited.append(id(self)) |
| 577 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 578 | self.called = False |
| 579 | self.call_args = None |
| 580 | self.call_count = 0 |
| 581 | self.mock_calls = _CallList() |
| 582 | self.call_args_list = _CallList() |
| 583 | self.method_calls = _CallList() |
| 584 | |
Kushal Das | 9cd39a1 | 2016-06-02 10:20:16 -0700 | [diff] [blame] | 585 | if return_value: |
| 586 | self._mock_return_value = DEFAULT |
| 587 | if side_effect: |
| 588 | self._mock_side_effect = None |
| 589 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 590 | for child in self._mock_children.values(): |
Xtreak | edeca92 | 2018-12-01 15:33:54 +0530 | [diff] [blame] | 591 | if isinstance(child, _SpecState) or child is _deleted: |
Michael Foord | 7596364 | 2012-06-09 17:31:59 +0100 | [diff] [blame] | 592 | continue |
Robert Collins | b37f43f | 2015-07-15 11:42:28 +1200 | [diff] [blame] | 593 | child.reset_mock(visited) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 594 | |
| 595 | ret = self._mock_return_value |
| 596 | if _is_instance_mock(ret) and ret is not self: |
Robert Collins | b37f43f | 2015-07-15 11:42:28 +1200 | [diff] [blame] | 597 | ret.reset_mock(visited) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 598 | |
| 599 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 600 | def configure_mock(self, /, **kwargs): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 601 | """Set attributes on the mock through keyword arguments. |
| 602 | |
| 603 | Attributes plus return values and side effects can be set on child |
| 604 | mocks using standard dot notation and unpacking a dictionary in the |
| 605 | method call: |
| 606 | |
| 607 | >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} |
| 608 | >>> mock.configure_mock(**attrs)""" |
| 609 | for arg, val in sorted(kwargs.items(), |
| 610 | # we sort on the number of dots so that |
| 611 | # attributes are set before we set attributes on |
| 612 | # attributes |
| 613 | key=lambda entry: entry[0].count('.')): |
| 614 | args = arg.split('.') |
| 615 | final = args.pop() |
| 616 | obj = self |
| 617 | for entry in args: |
| 618 | obj = getattr(obj, entry) |
| 619 | setattr(obj, final, val) |
| 620 | |
| 621 | |
| 622 | def __getattr__(self, name): |
Kushal Das | 8c14534 | 2014-04-16 23:32:21 +0530 | [diff] [blame] | 623 | if name in {'_mock_methods', '_mock_unsafe'}: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 624 | raise AttributeError(name) |
| 625 | elif self._mock_methods is not None: |
| 626 | if name not in self._mock_methods or name in _all_magics: |
| 627 | raise AttributeError("Mock object has no attribute %r" % name) |
| 628 | elif _is_magic(name): |
| 629 | raise AttributeError(name) |
Kushal Das | 8c14534 | 2014-04-16 23:32:21 +0530 | [diff] [blame] | 630 | if not self._mock_unsafe: |
| 631 | if name.startswith(('assert', 'assret')): |
Zackery Spytz | b9b08cd | 2019-05-08 11:32:24 -0600 | [diff] [blame] | 632 | raise AttributeError("Attributes cannot start with 'assert' " |
| 633 | "or 'assret'") |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 634 | |
| 635 | result = self._mock_children.get(name) |
| 636 | if result is _deleted: |
| 637 | raise AttributeError(name) |
| 638 | elif result is None: |
| 639 | wraps = None |
| 640 | if self._mock_wraps is not None: |
| 641 | # XXXX should we get the attribute without triggering code |
| 642 | # execution? |
| 643 | wraps = getattr(self._mock_wraps, name) |
| 644 | |
| 645 | result = self._get_child_mock( |
| 646 | parent=self, name=name, wraps=wraps, _new_name=name, |
| 647 | _new_parent=self |
| 648 | ) |
| 649 | self._mock_children[name] = result |
| 650 | |
| 651 | elif isinstance(result, _SpecState): |
| 652 | result = create_autospec( |
| 653 | result.spec, result.spec_set, result.instance, |
| 654 | result.parent, result.name |
| 655 | ) |
| 656 | self._mock_children[name] = result |
| 657 | |
| 658 | return result |
| 659 | |
| 660 | |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 661 | def _extract_mock_name(self): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 662 | _name_list = [self._mock_new_name] |
| 663 | _parent = self._mock_new_parent |
| 664 | last = self |
| 665 | |
| 666 | dot = '.' |
| 667 | if _name_list == ['()']: |
| 668 | dot = '' |
Chris Withers | adbf178 | 2019-05-01 23:04:04 +0100 | [diff] [blame] | 669 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 670 | while _parent is not None: |
| 671 | last = _parent |
| 672 | |
| 673 | _name_list.append(_parent._mock_new_name + dot) |
| 674 | dot = '.' |
| 675 | if _parent._mock_new_name == '()': |
| 676 | dot = '' |
| 677 | |
| 678 | _parent = _parent._mock_new_parent |
| 679 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 680 | _name_list = list(reversed(_name_list)) |
| 681 | _first = last._mock_name or 'mock' |
| 682 | if len(_name_list) > 1: |
| 683 | if _name_list[1] not in ('()', '().'): |
| 684 | _first += '.' |
| 685 | _name_list[0] = _first |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 686 | return ''.join(_name_list) |
| 687 | |
| 688 | def __repr__(self): |
| 689 | name = self._extract_mock_name() |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 690 | |
| 691 | name_string = '' |
| 692 | if name not in ('mock', 'mock.'): |
| 693 | name_string = ' name=%r' % name |
| 694 | |
| 695 | spec_string = '' |
| 696 | if self._spec_class is not None: |
| 697 | spec_string = ' spec=%r' |
| 698 | if self._spec_set: |
| 699 | spec_string = ' spec_set=%r' |
| 700 | spec_string = spec_string % self._spec_class.__name__ |
| 701 | return "<%s%s%s id='%s'>" % ( |
| 702 | type(self).__name__, |
| 703 | name_string, |
| 704 | spec_string, |
| 705 | id(self) |
| 706 | ) |
| 707 | |
| 708 | |
| 709 | def __dir__(self): |
Michael Foord | d7c65e2 | 2012-03-14 14:56:54 -0700 | [diff] [blame] | 710 | """Filter the output of `dir(mock)` to only useful members.""" |
Michael Foord | 313f85f | 2012-03-25 18:16:07 +0100 | [diff] [blame] | 711 | if not FILTER_DIR: |
| 712 | return object.__dir__(self) |
| 713 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 714 | extras = self._mock_methods or [] |
| 715 | from_type = dir(type(self)) |
| 716 | from_dict = list(self.__dict__) |
Mario Corchero | 0df635c | 2019-04-30 19:56:36 +0100 | [diff] [blame] | 717 | from_child_mocks = [ |
| 718 | m_name for m_name, m_value in self._mock_children.items() |
| 719 | if m_value is not _deleted] |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 720 | |
Michael Foord | 313f85f | 2012-03-25 18:16:07 +0100 | [diff] [blame] | 721 | from_type = [e for e in from_type if not e.startswith('_')] |
| 722 | from_dict = [e for e in from_dict if not e.startswith('_') or |
| 723 | _is_magic(e)] |
Mario Corchero | 0df635c | 2019-04-30 19:56:36 +0100 | [diff] [blame] | 724 | return sorted(set(extras + from_type + from_dict + from_child_mocks)) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 725 | |
| 726 | |
| 727 | def __setattr__(self, name, value): |
| 728 | if name in _allowed_names: |
| 729 | # property setters go through here |
| 730 | return object.__setattr__(self, name, value) |
| 731 | elif (self._spec_set and self._mock_methods is not None and |
| 732 | name not in self._mock_methods and |
| 733 | name not in self.__dict__): |
| 734 | raise AttributeError("Mock object has no attribute '%s'" % name) |
| 735 | elif name in _unsupported_magics: |
| 736 | msg = 'Attempting to set unsupported magic method %r.' % name |
| 737 | raise AttributeError(msg) |
| 738 | elif name in _all_magics: |
| 739 | if self._mock_methods is not None and name not in self._mock_methods: |
| 740 | raise AttributeError("Mock object has no attribute '%s'" % name) |
| 741 | |
| 742 | if not _is_instance_mock(value): |
| 743 | setattr(type(self), name, _get_method(name, value)) |
| 744 | original = value |
| 745 | value = lambda *args, **kw: original(self, *args, **kw) |
| 746 | else: |
| 747 | # only set _new_name and not name so that mock_calls is tracked |
| 748 | # but not method calls |
| 749 | _check_and_set_parent(self, value, None, name) |
| 750 | setattr(type(self), name, value) |
Michael Foord | 7596364 | 2012-06-09 17:31:59 +0100 | [diff] [blame] | 751 | self._mock_children[name] = value |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 752 | elif name == '__class__': |
| 753 | self._spec_class = value |
| 754 | return |
| 755 | else: |
| 756 | if _check_and_set_parent(self, value, name, name): |
| 757 | self._mock_children[name] = value |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 758 | |
| 759 | if self._mock_sealed and not hasattr(self, name): |
| 760 | mock_name = f'{self._extract_mock_name()}.{name}' |
| 761 | raise AttributeError(f'Cannot set {mock_name}') |
| 762 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 763 | return object.__setattr__(self, name, value) |
| 764 | |
| 765 | |
| 766 | def __delattr__(self, name): |
| 767 | if name in _all_magics and name in type(self).__dict__: |
| 768 | delattr(type(self), name) |
| 769 | if name not in self.__dict__: |
| 770 | # for magic methods that are still MagicProxy objects and |
| 771 | # not set on the instance itself |
| 772 | return |
| 773 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 774 | obj = self._mock_children.get(name, _missing) |
Pablo Galindo | 222d303 | 2019-01-21 08:57:46 +0000 | [diff] [blame] | 775 | if name in self.__dict__: |
Xtreak | 830b43d | 2019-04-14 00:42:33 +0530 | [diff] [blame] | 776 | _safe_super(NonCallableMock, self).__delattr__(name) |
Pablo Galindo | 222d303 | 2019-01-21 08:57:46 +0000 | [diff] [blame] | 777 | elif obj is _deleted: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 778 | raise AttributeError(name) |
| 779 | if obj is not _missing: |
| 780 | del self._mock_children[name] |
| 781 | self._mock_children[name] = _deleted |
| 782 | |
| 783 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 784 | def _format_mock_call_signature(self, args, kwargs): |
| 785 | name = self._mock_name or 'mock' |
| 786 | return _format_call_signature(name, args, kwargs) |
| 787 | |
| 788 | |
Xtreak | 0ae022c | 2019-05-29 12:32:26 +0530 | [diff] [blame] | 789 | def _format_mock_failure_message(self, args, kwargs, action='call'): |
| 790 | message = 'expected %s not found.\nExpected: %s\nActual: %s' |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 791 | expected_string = self._format_mock_call_signature(args, kwargs) |
| 792 | call_args = self.call_args |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 793 | actual_string = self._format_mock_call_signature(*call_args) |
Xtreak | 0ae022c | 2019-05-29 12:32:26 +0530 | [diff] [blame] | 794 | return message % (action, expected_string, actual_string) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 795 | |
| 796 | |
Xtreak | c961278 | 2019-08-29 11:39:01 +0530 | [diff] [blame] | 797 | def _get_call_signature_from_name(self, name): |
| 798 | """ |
| 799 | * If call objects are asserted against a method/function like obj.meth1 |
| 800 | then there could be no name for the call object to lookup. Hence just |
| 801 | return the spec_signature of the method/function being asserted against. |
| 802 | * If the name is not empty then remove () and split by '.' to get |
| 803 | list of names to iterate through the children until a potential |
| 804 | match is found. A child mock is created only during attribute access |
| 805 | so if we get a _SpecState then no attributes of the spec were accessed |
| 806 | and can be safely exited. |
| 807 | """ |
| 808 | if not name: |
| 809 | return self._spec_signature |
| 810 | |
| 811 | sig = None |
| 812 | names = name.replace('()', '').split('.') |
| 813 | children = self._mock_children |
| 814 | |
| 815 | for name in names: |
| 816 | child = children.get(name) |
| 817 | if child is None or isinstance(child, _SpecState): |
| 818 | break |
| 819 | else: |
| 820 | children = child._mock_children |
| 821 | sig = child._spec_signature |
| 822 | |
| 823 | return sig |
| 824 | |
| 825 | |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 826 | def _call_matcher(self, _call): |
| 827 | """ |
Martin Panter | 204bf0b | 2016-07-11 07:51:37 +0000 | [diff] [blame] | 828 | Given a call (or simply an (args, kwargs) tuple), return a |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 829 | comparison key suitable for matching with other calls. |
| 830 | This is a best effort method which relies on the spec's signature, |
| 831 | if available, or falls back on the arguments themselves. |
| 832 | """ |
Xtreak | c961278 | 2019-08-29 11:39:01 +0530 | [diff] [blame] | 833 | |
| 834 | if isinstance(_call, tuple) and len(_call) > 2: |
| 835 | sig = self._get_call_signature_from_name(_call[0]) |
| 836 | else: |
| 837 | sig = self._spec_signature |
| 838 | |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 839 | if sig is not None: |
| 840 | if len(_call) == 2: |
| 841 | name = '' |
| 842 | args, kwargs = _call |
| 843 | else: |
| 844 | name, args, kwargs = _call |
| 845 | try: |
Elizabeth Uselton | d6a9d17 | 2019-09-13 08:54:32 -0700 | [diff] [blame] | 846 | bound_call = sig.bind(*args, **kwargs) |
| 847 | return call(name, bound_call.args, bound_call.kwargs) |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 848 | except TypeError as e: |
| 849 | return e.with_traceback(None) |
| 850 | else: |
| 851 | return _call |
| 852 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 853 | def assert_not_called(self): |
Kushal Das | 8af9db3 | 2014-04-17 01:36:14 +0530 | [diff] [blame] | 854 | """assert that the mock was never called. |
| 855 | """ |
Kushal Das | 8af9db3 | 2014-04-17 01:36:14 +0530 | [diff] [blame] | 856 | if self.call_count != 0: |
Petter Strandmark | 47d9424 | 2018-10-28 21:37:10 +0100 | [diff] [blame] | 857 | msg = ("Expected '%s' to not have been called. Called %s times.%s" |
| 858 | % (self._mock_name or 'mock', |
| 859 | self.call_count, |
| 860 | self._calls_repr())) |
Kushal Das | 8af9db3 | 2014-04-17 01:36:14 +0530 | [diff] [blame] | 861 | raise AssertionError(msg) |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 862 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 863 | def assert_called(self): |
Victor Stinner | 2c2a4e6 | 2016-03-11 22:17:48 +0100 | [diff] [blame] | 864 | """assert that the mock was called at least once |
| 865 | """ |
Victor Stinner | 2c2a4e6 | 2016-03-11 22:17:48 +0100 | [diff] [blame] | 866 | if self.call_count == 0: |
| 867 | msg = ("Expected '%s' to have been called." % |
Abraham Toriz Cruz | 5f5f11f | 2019-09-17 06:16:08 -0500 | [diff] [blame] | 868 | (self._mock_name or 'mock')) |
Victor Stinner | 2c2a4e6 | 2016-03-11 22:17:48 +0100 | [diff] [blame] | 869 | raise AssertionError(msg) |
| 870 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 871 | def assert_called_once(self): |
Victor Stinner | 2c2a4e6 | 2016-03-11 22:17:48 +0100 | [diff] [blame] | 872 | """assert that the mock was called only once. |
| 873 | """ |
Victor Stinner | 2c2a4e6 | 2016-03-11 22:17:48 +0100 | [diff] [blame] | 874 | if not self.call_count == 1: |
Petter Strandmark | 47d9424 | 2018-10-28 21:37:10 +0100 | [diff] [blame] | 875 | msg = ("Expected '%s' to have been called once. Called %s times.%s" |
| 876 | % (self._mock_name or 'mock', |
| 877 | self.call_count, |
| 878 | self._calls_repr())) |
Victor Stinner | 2c2a4e6 | 2016-03-11 22:17:48 +0100 | [diff] [blame] | 879 | raise AssertionError(msg) |
| 880 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 881 | def assert_called_with(self, /, *args, **kwargs): |
Rémi Lapeyre | f5896a0 | 2019-08-29 08:15:53 +0200 | [diff] [blame] | 882 | """assert that the last call was made with the specified arguments. |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 883 | |
| 884 | Raises an AssertionError if the args and keyword args passed in are |
| 885 | different to the last call to the mock.""" |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 886 | if self.call_args is None: |
| 887 | expected = self._format_mock_call_signature(args, kwargs) |
Susan Su | 2bdd585 | 2019-02-13 18:22:29 -0800 | [diff] [blame] | 888 | actual = 'not called.' |
| 889 | error_message = ('expected call not found.\nExpected: %s\nActual: %s' |
| 890 | % (expected, actual)) |
| 891 | raise AssertionError(error_message) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 892 | |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 893 | def _error_message(): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 894 | msg = self._format_mock_failure_message(args, kwargs) |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 895 | return msg |
Elizabeth Uselton | d6a9d17 | 2019-09-13 08:54:32 -0700 | [diff] [blame] | 896 | expected = self._call_matcher(_Call((args, kwargs), two=True)) |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 897 | actual = self._call_matcher(self.call_args) |
Elizabeth Uselton | d6a9d17 | 2019-09-13 08:54:32 -0700 | [diff] [blame] | 898 | if actual != expected: |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 899 | cause = expected if isinstance(expected, Exception) else None |
| 900 | raise AssertionError(_error_message()) from cause |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 901 | |
| 902 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 903 | def assert_called_once_with(self, /, *args, **kwargs): |
Arne de Laat | 324c5d8 | 2017-02-23 15:57:25 +0100 | [diff] [blame] | 904 | """assert that the mock was called exactly once and that that call was |
| 905 | with the specified arguments.""" |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 906 | if not self.call_count == 1: |
Petter Strandmark | 47d9424 | 2018-10-28 21:37:10 +0100 | [diff] [blame] | 907 | msg = ("Expected '%s' to be called once. Called %s times.%s" |
| 908 | % (self._mock_name or 'mock', |
| 909 | self.call_count, |
| 910 | self._calls_repr())) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 911 | raise AssertionError(msg) |
| 912 | return self.assert_called_with(*args, **kwargs) |
| 913 | |
| 914 | |
| 915 | def assert_has_calls(self, calls, any_order=False): |
| 916 | """assert the mock has been called with the specified calls. |
| 917 | The `mock_calls` list is checked for the calls. |
| 918 | |
| 919 | If `any_order` is False (the default) then the calls must be |
| 920 | sequential. There can be extra calls before or after the |
| 921 | specified calls. |
| 922 | |
| 923 | If `any_order` is True then the calls can be in any order, but |
| 924 | they must all appear in `mock_calls`.""" |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 925 | expected = [self._call_matcher(c) for c in calls] |
Samuel Freilich | b5a7a4f | 2019-09-24 15:08:31 -0400 | [diff] [blame] | 926 | cause = next((e for e in expected if isinstance(e, Exception)), None) |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 927 | all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 928 | if not any_order: |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 929 | if expected not in all_calls: |
Samuel Freilich | b5a7a4f | 2019-09-24 15:08:31 -0400 | [diff] [blame] | 930 | if cause is None: |
| 931 | problem = 'Calls not found.' |
| 932 | else: |
| 933 | problem = ('Error processing expected calls.\n' |
| 934 | 'Errors: {}').format( |
| 935 | [e if isinstance(e, Exception) else None |
| 936 | for e in expected]) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 937 | raise AssertionError( |
Samuel Freilich | b5a7a4f | 2019-09-24 15:08:31 -0400 | [diff] [blame] | 938 | f'{problem}\n' |
Samuel Freilich | 2180f6b | 2019-09-24 18:04:29 -0400 | [diff] [blame] | 939 | f'Expected: {_CallList(calls)}' |
| 940 | f'{self._calls_repr(prefix="Actual").rstrip(".")}' |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 941 | ) from cause |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 942 | return |
| 943 | |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 944 | all_calls = list(all_calls) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 945 | |
| 946 | not_found = [] |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 947 | for kall in expected: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 948 | try: |
| 949 | all_calls.remove(kall) |
| 950 | except ValueError: |
| 951 | not_found.append(kall) |
| 952 | if not_found: |
| 953 | raise AssertionError( |
davidair | 2b32da2 | 2018-08-17 15:09:58 -0400 | [diff] [blame] | 954 | '%r does not contain all of %r in its call list, ' |
| 955 | 'found %r instead' % (self._mock_name or 'mock', |
| 956 | tuple(not_found), all_calls) |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 957 | ) from cause |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 958 | |
| 959 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 960 | def assert_any_call(self, /, *args, **kwargs): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 961 | """assert the mock has been called with the specified arguments. |
| 962 | |
| 963 | The assert passes if the mock has *ever* been called, unlike |
| 964 | `assert_called_with` and `assert_called_once_with` that only pass if |
| 965 | the call is the most recent one.""" |
Elizabeth Uselton | d6a9d17 | 2019-09-13 08:54:32 -0700 | [diff] [blame] | 966 | expected = self._call_matcher(_Call((args, kwargs), two=True)) |
| 967 | cause = expected if isinstance(expected, Exception) else None |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 968 | actual = [self._call_matcher(c) for c in self.call_args_list] |
Elizabeth Uselton | d6a9d17 | 2019-09-13 08:54:32 -0700 | [diff] [blame] | 969 | if cause or expected not in _AnyComparer(actual): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 970 | expected_string = self._format_mock_call_signature(args, kwargs) |
| 971 | raise AssertionError( |
| 972 | '%s call not found' % expected_string |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 973 | ) from cause |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 974 | |
| 975 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 976 | def _get_child_mock(self, /, **kw): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 977 | """Create the child mocks for attributes and return value. |
| 978 | By default child mocks will be the same type as the parent. |
| 979 | Subclasses of Mock may want to override this to customize the way |
| 980 | child mocks are made. |
| 981 | |
| 982 | For non-callable mocks the callable variant will be used (rather than |
| 983 | any custom subclass).""" |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 984 | _new_name = kw.get("_new_name") |
| 985 | if _new_name in self.__dict__['_spec_asyncs']: |
| 986 | return AsyncMock(**kw) |
| 987 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 988 | _type = type(self) |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 989 | if issubclass(_type, MagicMock) and _new_name in _async_method_magics: |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 990 | # Any asynchronous magic becomes an AsyncMock |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 991 | klass = AsyncMock |
Lisa Roach | 8b03f94 | 2019-09-19 21:04:18 -0700 | [diff] [blame] | 992 | elif issubclass(_type, AsyncMockMixin): |
Lisa Roach | 3667e1e | 2019-09-29 21:56:47 -0700 | [diff] [blame] | 993 | if (_new_name in _all_sync_magics or |
| 994 | self._mock_methods and _new_name in self._mock_methods): |
| 995 | # Any synchronous method on AsyncMock becomes a MagicMock |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 996 | klass = MagicMock |
| 997 | else: |
| 998 | klass = AsyncMock |
Lisa Roach | 8b03f94 | 2019-09-19 21:04:18 -0700 | [diff] [blame] | 999 | elif not issubclass(_type, CallableMixin): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1000 | if issubclass(_type, NonCallableMagicMock): |
| 1001 | klass = MagicMock |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 1002 | elif issubclass(_type, NonCallableMock): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1003 | klass = Mock |
| 1004 | else: |
| 1005 | klass = _type.__mro__[1] |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 1006 | |
| 1007 | if self._mock_sealed: |
| 1008 | attribute = "." + kw["name"] if "name" in kw else "()" |
| 1009 | mock_name = self._extract_mock_name() + attribute |
| 1010 | raise AttributeError(mock_name) |
| 1011 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1012 | return klass(**kw) |
| 1013 | |
| 1014 | |
Petter Strandmark | 47d9424 | 2018-10-28 21:37:10 +0100 | [diff] [blame] | 1015 | def _calls_repr(self, prefix="Calls"): |
| 1016 | """Renders self.mock_calls as a string. |
| 1017 | |
| 1018 | Example: "\nCalls: [call(1), call(2)]." |
| 1019 | |
| 1020 | If self.mock_calls is empty, an empty string is returned. The |
| 1021 | output will be truncated if very long. |
| 1022 | """ |
| 1023 | if not self.mock_calls: |
| 1024 | return "" |
| 1025 | return f"\n{prefix}: {safe_repr(self.mock_calls)}." |
| 1026 | |
| 1027 | |
Michael Foord | 14fd925 | 2019-09-13 18:40:56 +0200 | [diff] [blame] | 1028 | _MOCK_SIG = inspect.signature(NonCallableMock.__init__) |
| 1029 | |
| 1030 | |
Elizabeth Uselton | d6a9d17 | 2019-09-13 08:54:32 -0700 | [diff] [blame] | 1031 | class _AnyComparer(list): |
| 1032 | """A list which checks if it contains a call which may have an |
| 1033 | argument of ANY, flipping the components of item and self from |
| 1034 | their traditional locations so that ANY is guaranteed to be on |
| 1035 | the left.""" |
| 1036 | def __contains__(self, item): |
| 1037 | for _call in self: |
| 1038 | if len(item) != len(_call): |
| 1039 | continue |
| 1040 | if all([ |
| 1041 | expected == actual |
| 1042 | for expected, actual in zip(item, _call) |
| 1043 | ]): |
| 1044 | return True |
| 1045 | return False |
| 1046 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1047 | |
| 1048 | def _try_iter(obj): |
| 1049 | if obj is None: |
| 1050 | return obj |
| 1051 | if _is_exception(obj): |
| 1052 | return obj |
| 1053 | if _callable(obj): |
| 1054 | return obj |
| 1055 | try: |
| 1056 | return iter(obj) |
| 1057 | except TypeError: |
| 1058 | # XXXX backwards compatibility |
| 1059 | # but this will blow up on first call - so maybe we should fail early? |
| 1060 | return obj |
| 1061 | |
| 1062 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1063 | class CallableMixin(Base): |
| 1064 | |
| 1065 | def __init__(self, spec=None, side_effect=None, return_value=DEFAULT, |
| 1066 | wraps=None, name=None, spec_set=None, parent=None, |
| 1067 | _spec_state=None, _new_name='', _new_parent=None, **kwargs): |
| 1068 | self.__dict__['_mock_return_value'] = return_value |
Nick Coghlan | 0b43bcf | 2012-05-27 18:17:07 +1000 | [diff] [blame] | 1069 | _safe_super(CallableMixin, self).__init__( |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1070 | spec, wraps, name, spec_set, parent, |
| 1071 | _spec_state, _new_name, _new_parent, **kwargs |
| 1072 | ) |
| 1073 | |
| 1074 | self.side_effect = side_effect |
| 1075 | |
| 1076 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 1077 | def _mock_check_sig(self, /, *args, **kwargs): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1078 | # stub method that can be replaced with one with a specific signature |
| 1079 | pass |
| 1080 | |
| 1081 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 1082 | def __call__(self, /, *args, **kwargs): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1083 | # can't use self in-case a function / method we are mocking uses self |
| 1084 | # in the signature |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 1085 | self._mock_check_sig(*args, **kwargs) |
Lisa Roach | ef04851 | 2019-09-23 20:49:40 -0700 | [diff] [blame] | 1086 | self._increment_mock_call(*args, **kwargs) |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 1087 | return self._mock_call(*args, **kwargs) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1088 | |
| 1089 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 1090 | def _mock_call(self, /, *args, **kwargs): |
Lisa Roach | ef04851 | 2019-09-23 20:49:40 -0700 | [diff] [blame] | 1091 | return self._execute_mock_call(*args, **kwargs) |
| 1092 | |
| 1093 | def _increment_mock_call(self, /, *args, **kwargs): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1094 | self.called = True |
| 1095 | self.call_count += 1 |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 1096 | |
Chris Withers | 8ca0fa9 | 2018-12-03 21:31:37 +0000 | [diff] [blame] | 1097 | # handle call_args |
Lisa Roach | ef04851 | 2019-09-23 20:49:40 -0700 | [diff] [blame] | 1098 | # needs to be set here so assertions on call arguments pass before |
| 1099 | # execution in the case of awaited calls |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 1100 | _call = _Call((args, kwargs), two=True) |
| 1101 | self.call_args = _call |
| 1102 | self.call_args_list.append(_call) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1103 | |
Chris Withers | 8ca0fa9 | 2018-12-03 21:31:37 +0000 | [diff] [blame] | 1104 | # initial stuff for method_calls: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1105 | do_method_calls = self._mock_parent is not None |
Chris Withers | 8ca0fa9 | 2018-12-03 21:31:37 +0000 | [diff] [blame] | 1106 | method_call_name = self._mock_name |
| 1107 | |
| 1108 | # initial stuff for mock_calls: |
| 1109 | mock_call_name = self._mock_new_name |
| 1110 | is_a_call = mock_call_name == '()' |
| 1111 | self.mock_calls.append(_Call(('', args, kwargs))) |
| 1112 | |
| 1113 | # follow up the chain of mocks: |
| 1114 | _new_parent = self._mock_new_parent |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1115 | while _new_parent is not None: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1116 | |
Chris Withers | 8ca0fa9 | 2018-12-03 21:31:37 +0000 | [diff] [blame] | 1117 | # handle method_calls: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1118 | if do_method_calls: |
Chris Withers | 8ca0fa9 | 2018-12-03 21:31:37 +0000 | [diff] [blame] | 1119 | _new_parent.method_calls.append(_Call((method_call_name, args, kwargs))) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1120 | do_method_calls = _new_parent._mock_parent is not None |
| 1121 | if do_method_calls: |
Chris Withers | 8ca0fa9 | 2018-12-03 21:31:37 +0000 | [diff] [blame] | 1122 | method_call_name = _new_parent._mock_name + '.' + method_call_name |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1123 | |
Chris Withers | 8ca0fa9 | 2018-12-03 21:31:37 +0000 | [diff] [blame] | 1124 | # handle mock_calls: |
| 1125 | this_mock_call = _Call((mock_call_name, args, kwargs)) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1126 | _new_parent.mock_calls.append(this_mock_call) |
Chris Withers | 8ca0fa9 | 2018-12-03 21:31:37 +0000 | [diff] [blame] | 1127 | |
| 1128 | if _new_parent._mock_new_name: |
| 1129 | if is_a_call: |
| 1130 | dot = '' |
| 1131 | else: |
| 1132 | dot = '.' |
| 1133 | is_a_call = _new_parent._mock_new_name == '()' |
| 1134 | mock_call_name = _new_parent._mock_new_name + dot + mock_call_name |
| 1135 | |
| 1136 | # follow the parental chain: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1137 | _new_parent = _new_parent._mock_new_parent |
| 1138 | |
Lisa Roach | ef04851 | 2019-09-23 20:49:40 -0700 | [diff] [blame] | 1139 | def _execute_mock_call(self, /, *args, **kwargs): |
Jason Fried | 046442d | 2019-11-20 16:27:51 -0800 | [diff] [blame] | 1140 | # separate from _increment_mock_call so that awaited functions are |
| 1141 | # executed separately from their call, also AsyncMock overrides this method |
Lisa Roach | ef04851 | 2019-09-23 20:49:40 -0700 | [diff] [blame] | 1142 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1143 | effect = self.side_effect |
| 1144 | if effect is not None: |
| 1145 | if _is_exception(effect): |
| 1146 | raise effect |
Mario Corchero | f05df0a | 2018-12-08 11:25:02 +0000 | [diff] [blame] | 1147 | elif not _callable(effect): |
Michael Foord | 2cd4873 | 2012-04-21 15:52:11 +0100 | [diff] [blame] | 1148 | result = next(effect) |
| 1149 | if _is_exception(result): |
| 1150 | raise result |
Mario Corchero | f05df0a | 2018-12-08 11:25:02 +0000 | [diff] [blame] | 1151 | else: |
| 1152 | result = effect(*args, **kwargs) |
| 1153 | |
| 1154 | if result is not DEFAULT: |
Michael Foord | 2cd4873 | 2012-04-21 15:52:11 +0100 | [diff] [blame] | 1155 | return result |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1156 | |
Mario Corchero | f05df0a | 2018-12-08 11:25:02 +0000 | [diff] [blame] | 1157 | if self._mock_return_value is not DEFAULT: |
| 1158 | return self.return_value |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1159 | |
Mario Corchero | f05df0a | 2018-12-08 11:25:02 +0000 | [diff] [blame] | 1160 | if self._mock_wraps is not None: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1161 | return self._mock_wraps(*args, **kwargs) |
Mario Corchero | f05df0a | 2018-12-08 11:25:02 +0000 | [diff] [blame] | 1162 | |
| 1163 | return self.return_value |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1164 | |
| 1165 | |
| 1166 | |
| 1167 | class Mock(CallableMixin, NonCallableMock): |
| 1168 | """ |
| 1169 | Create a new `Mock` object. `Mock` takes several optional arguments |
| 1170 | that specify the behaviour of the Mock object: |
| 1171 | |
| 1172 | * `spec`: This can be either a list of strings or an existing object (a |
| 1173 | class or instance) that acts as the specification for the mock object. If |
| 1174 | you pass in an object then a list of strings is formed by calling dir on |
| 1175 | the object (excluding unsupported magic attributes and methods). Accessing |
| 1176 | any attribute not in this list will raise an `AttributeError`. |
| 1177 | |
| 1178 | If `spec` is an object (rather than a list of strings) then |
| 1179 | `mock.__class__` returns the class of the spec object. This allows mocks |
| 1180 | to pass `isinstance` tests. |
| 1181 | |
| 1182 | * `spec_set`: A stricter variant of `spec`. If used, attempting to *set* |
| 1183 | or get an attribute on the mock that isn't on the object passed as |
| 1184 | `spec_set` will raise an `AttributeError`. |
| 1185 | |
| 1186 | * `side_effect`: A function to be called whenever the Mock is called. See |
| 1187 | the `side_effect` attribute. Useful for raising exceptions or |
| 1188 | dynamically changing return values. The function is called with the same |
| 1189 | arguments as the mock, and unless it returns `DEFAULT`, the return |
| 1190 | value of this function is used as the return value. |
| 1191 | |
Michael Foord | 2cd4873 | 2012-04-21 15:52:11 +0100 | [diff] [blame] | 1192 | If `side_effect` is an iterable then each call to the mock will return |
| 1193 | the next value from the iterable. If any of the members of the iterable |
| 1194 | are exceptions they will be raised instead of returned. |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1195 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1196 | * `return_value`: The value returned when the mock is called. By default |
| 1197 | this is a new Mock (created on first access). See the |
| 1198 | `return_value` attribute. |
| 1199 | |
Michael Foord | 0682a0c | 2012-04-13 20:51:20 +0100 | [diff] [blame] | 1200 | * `wraps`: Item for the mock object to wrap. If `wraps` is not None then |
| 1201 | calling the Mock will pass the call through to the wrapped object |
| 1202 | (returning the real result). Attribute access on the mock will return a |
| 1203 | Mock object that wraps the corresponding attribute of the wrapped object |
| 1204 | (so attempting to access an attribute that doesn't exist will raise an |
| 1205 | `AttributeError`). |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1206 | |
| 1207 | If the mock has an explicit `return_value` set then calls are not passed |
| 1208 | to the wrapped object and the `return_value` is returned instead. |
| 1209 | |
| 1210 | * `name`: If the mock has a name then it will be used in the repr of the |
| 1211 | mock. This can be useful for debugging. The name is propagated to child |
| 1212 | mocks. |
| 1213 | |
| 1214 | Mocks can also be called with arbitrary keyword arguments. These will be |
| 1215 | used to set attributes on the mock after it is created. |
| 1216 | """ |
| 1217 | |
| 1218 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1219 | def _dot_lookup(thing, comp, import_path): |
| 1220 | try: |
| 1221 | return getattr(thing, comp) |
| 1222 | except AttributeError: |
| 1223 | __import__(import_path) |
| 1224 | return getattr(thing, comp) |
| 1225 | |
| 1226 | |
| 1227 | def _importer(target): |
| 1228 | components = target.split('.') |
| 1229 | import_path = components.pop(0) |
| 1230 | thing = __import__(import_path) |
| 1231 | |
| 1232 | for comp in components: |
| 1233 | import_path += ".%s" % comp |
| 1234 | thing = _dot_lookup(thing, comp, import_path) |
| 1235 | return thing |
| 1236 | |
| 1237 | |
| 1238 | def _is_started(patcher): |
| 1239 | # XXXX horrible |
| 1240 | return hasattr(patcher, 'is_local') |
| 1241 | |
| 1242 | |
| 1243 | class _patch(object): |
| 1244 | |
| 1245 | attribute_name = None |
Michael Foord | ebc1a30 | 2014-04-15 17:21:08 -0400 | [diff] [blame] | 1246 | _active_patches = [] |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1247 | |
| 1248 | def __init__( |
| 1249 | self, getter, attribute, new, spec, create, |
| 1250 | spec_set, autospec, new_callable, kwargs |
| 1251 | ): |
| 1252 | if new_callable is not None: |
| 1253 | if new is not DEFAULT: |
| 1254 | raise ValueError( |
| 1255 | "Cannot use 'new' and 'new_callable' together" |
| 1256 | ) |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1257 | if autospec is not None: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1258 | raise ValueError( |
| 1259 | "Cannot use 'autospec' and 'new_callable' together" |
| 1260 | ) |
| 1261 | |
| 1262 | self.getter = getter |
| 1263 | self.attribute = attribute |
| 1264 | self.new = new |
| 1265 | self.new_callable = new_callable |
| 1266 | self.spec = spec |
| 1267 | self.create = create |
| 1268 | self.has_local = False |
| 1269 | self.spec_set = spec_set |
| 1270 | self.autospec = autospec |
| 1271 | self.kwargs = kwargs |
| 1272 | self.additional_patchers = [] |
| 1273 | |
| 1274 | |
| 1275 | def copy(self): |
| 1276 | patcher = _patch( |
| 1277 | self.getter, self.attribute, self.new, self.spec, |
| 1278 | self.create, self.spec_set, |
| 1279 | self.autospec, self.new_callable, self.kwargs |
| 1280 | ) |
| 1281 | patcher.attribute_name = self.attribute_name |
| 1282 | patcher.additional_patchers = [ |
| 1283 | p.copy() for p in self.additional_patchers |
| 1284 | ] |
| 1285 | return patcher |
| 1286 | |
| 1287 | |
| 1288 | def __call__(self, func): |
| 1289 | if isinstance(func, type): |
| 1290 | return self.decorate_class(func) |
Xtreak | 436c2b0 | 2019-05-28 12:37:39 +0530 | [diff] [blame] | 1291 | if inspect.iscoroutinefunction(func): |
| 1292 | return self.decorate_async_callable(func) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1293 | return self.decorate_callable(func) |
| 1294 | |
| 1295 | |
| 1296 | def decorate_class(self, klass): |
| 1297 | for attr in dir(klass): |
| 1298 | if not attr.startswith(patch.TEST_PREFIX): |
| 1299 | continue |
| 1300 | |
| 1301 | attr_value = getattr(klass, attr) |
| 1302 | if not hasattr(attr_value, "__call__"): |
| 1303 | continue |
| 1304 | |
| 1305 | patcher = self.copy() |
| 1306 | setattr(klass, attr, patcher(attr_value)) |
| 1307 | return klass |
| 1308 | |
| 1309 | |
Xtreak | 436c2b0 | 2019-05-28 12:37:39 +0530 | [diff] [blame] | 1310 | @contextlib.contextmanager |
| 1311 | def decoration_helper(self, patched, args, keywargs): |
| 1312 | extra_args = [] |
| 1313 | entered_patchers = [] |
| 1314 | patching = None |
| 1315 | |
| 1316 | exc_info = tuple() |
| 1317 | try: |
| 1318 | for patching in patched.patchings: |
| 1319 | arg = patching.__enter__() |
| 1320 | entered_patchers.append(patching) |
| 1321 | if patching.attribute_name is not None: |
| 1322 | keywargs.update(arg) |
| 1323 | elif patching.new is DEFAULT: |
| 1324 | extra_args.append(arg) |
| 1325 | |
| 1326 | args += tuple(extra_args) |
| 1327 | yield (args, keywargs) |
| 1328 | except: |
| 1329 | if (patching not in entered_patchers and |
| 1330 | _is_started(patching)): |
| 1331 | # the patcher may have been started, but an exception |
| 1332 | # raised whilst entering one of its additional_patchers |
| 1333 | entered_patchers.append(patching) |
| 1334 | # Pass the exception to __exit__ |
| 1335 | exc_info = sys.exc_info() |
| 1336 | # re-raise the exception |
| 1337 | raise |
| 1338 | finally: |
| 1339 | for patching in reversed(entered_patchers): |
| 1340 | patching.__exit__(*exc_info) |
| 1341 | |
| 1342 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1343 | def decorate_callable(self, func): |
Xtreak | 436c2b0 | 2019-05-28 12:37:39 +0530 | [diff] [blame] | 1344 | # NB. Keep the method in sync with decorate_async_callable() |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1345 | if hasattr(func, 'patchings'): |
| 1346 | func.patchings.append(self) |
| 1347 | return func |
| 1348 | |
| 1349 | @wraps(func) |
| 1350 | def patched(*args, **keywargs): |
Xtreak | 436c2b0 | 2019-05-28 12:37:39 +0530 | [diff] [blame] | 1351 | with self.decoration_helper(patched, |
| 1352 | args, |
| 1353 | keywargs) as (newargs, newkeywargs): |
| 1354 | return func(*newargs, **newkeywargs) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1355 | |
Xtreak | 436c2b0 | 2019-05-28 12:37:39 +0530 | [diff] [blame] | 1356 | patched.patchings = [self] |
| 1357 | return patched |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1358 | |
Xtreak | 436c2b0 | 2019-05-28 12:37:39 +0530 | [diff] [blame] | 1359 | |
| 1360 | def decorate_async_callable(self, func): |
| 1361 | # NB. Keep the method in sync with decorate_callable() |
| 1362 | if hasattr(func, 'patchings'): |
| 1363 | func.patchings.append(self) |
| 1364 | return func |
| 1365 | |
| 1366 | @wraps(func) |
| 1367 | async def patched(*args, **keywargs): |
| 1368 | with self.decoration_helper(patched, |
| 1369 | args, |
| 1370 | keywargs) as (newargs, newkeywargs): |
| 1371 | return await func(*newargs, **newkeywargs) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1372 | |
| 1373 | patched.patchings = [self] |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1374 | return patched |
| 1375 | |
| 1376 | |
| 1377 | def get_original(self): |
| 1378 | target = self.getter() |
| 1379 | name = self.attribute |
| 1380 | |
| 1381 | original = DEFAULT |
| 1382 | local = False |
| 1383 | |
| 1384 | try: |
| 1385 | original = target.__dict__[name] |
| 1386 | except (AttributeError, KeyError): |
| 1387 | original = getattr(target, name, DEFAULT) |
| 1388 | else: |
| 1389 | local = True |
| 1390 | |
Michael Foord | fddcfa2 | 2014-04-14 16:25:20 -0400 | [diff] [blame] | 1391 | if name in _builtins and isinstance(target, ModuleType): |
| 1392 | self.create = True |
| 1393 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1394 | if not self.create and original is DEFAULT: |
| 1395 | raise AttributeError( |
| 1396 | "%s does not have the attribute %r" % (target, name) |
| 1397 | ) |
| 1398 | return original, local |
| 1399 | |
| 1400 | |
| 1401 | def __enter__(self): |
| 1402 | """Perform the patch.""" |
| 1403 | new, spec, spec_set = self.new, self.spec, self.spec_set |
| 1404 | autospec, kwargs = self.autospec, self.kwargs |
| 1405 | new_callable = self.new_callable |
| 1406 | self.target = self.getter() |
| 1407 | |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1408 | # normalise False to None |
| 1409 | if spec is False: |
| 1410 | spec = None |
| 1411 | if spec_set is False: |
| 1412 | spec_set = None |
| 1413 | if autospec is False: |
| 1414 | autospec = None |
| 1415 | |
| 1416 | if spec is not None and autospec is not None: |
| 1417 | raise TypeError("Can't specify spec and autospec") |
| 1418 | if ((spec is not None or autospec is not None) and |
| 1419 | spec_set not in (True, None)): |
| 1420 | raise TypeError("Can't provide explicit spec_set *and* spec or autospec") |
| 1421 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1422 | original, local = self.get_original() |
| 1423 | |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1424 | if new is DEFAULT and autospec is None: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1425 | inherit = False |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1426 | if spec is True: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1427 | # set spec to the object we are replacing |
| 1428 | spec = original |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1429 | if spec_set is True: |
| 1430 | spec_set = original |
| 1431 | spec = None |
| 1432 | elif spec is not None: |
| 1433 | if spec_set is True: |
| 1434 | spec_set = spec |
| 1435 | spec = None |
| 1436 | elif spec_set is True: |
| 1437 | spec_set = original |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1438 | |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1439 | if spec is not None or spec_set is not None: |
| 1440 | if original is DEFAULT: |
| 1441 | raise TypeError("Can't use 'spec' with create=True") |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1442 | if isinstance(original, type): |
| 1443 | # If we're patching out a class and there is a spec |
| 1444 | inherit = True |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 1445 | if spec is None and _is_async_obj(original): |
| 1446 | Klass = AsyncMock |
| 1447 | else: |
| 1448 | Klass = MagicMock |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1449 | _kwargs = {} |
| 1450 | if new_callable is not None: |
| 1451 | Klass = new_callable |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1452 | elif spec is not None or spec_set is not None: |
Michael Foord | e58a562 | 2012-03-25 19:53:18 +0100 | [diff] [blame] | 1453 | this_spec = spec |
| 1454 | if spec_set is not None: |
| 1455 | this_spec = spec_set |
| 1456 | if _is_list(this_spec): |
| 1457 | not_callable = '__call__' not in this_spec |
| 1458 | else: |
| 1459 | not_callable = not callable(this_spec) |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 1460 | if _is_async_obj(this_spec): |
| 1461 | Klass = AsyncMock |
| 1462 | elif not_callable: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1463 | Klass = NonCallableMagicMock |
| 1464 | |
| 1465 | if spec is not None: |
| 1466 | _kwargs['spec'] = spec |
| 1467 | if spec_set is not None: |
| 1468 | _kwargs['spec_set'] = spec_set |
| 1469 | |
| 1470 | # add a name to mocks |
| 1471 | if (isinstance(Klass, type) and |
| 1472 | issubclass(Klass, NonCallableMock) and self.attribute): |
| 1473 | _kwargs['name'] = self.attribute |
| 1474 | |
| 1475 | _kwargs.update(kwargs) |
| 1476 | new = Klass(**_kwargs) |
| 1477 | |
| 1478 | if inherit and _is_instance_mock(new): |
| 1479 | # we can only tell if the instance should be callable if the |
| 1480 | # spec is not a list |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1481 | this_spec = spec |
| 1482 | if spec_set is not None: |
| 1483 | this_spec = spec_set |
| 1484 | if (not _is_list(this_spec) and not |
| 1485 | _instance_callable(this_spec)): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1486 | Klass = NonCallableMagicMock |
| 1487 | |
| 1488 | _kwargs.pop('name') |
| 1489 | new.return_value = Klass(_new_parent=new, _new_name='()', |
| 1490 | **_kwargs) |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1491 | elif autospec is not None: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1492 | # spec is ignored, new *must* be default, spec_set is treated |
| 1493 | # as a boolean. Should we check spec is not None and that spec_set |
| 1494 | # is a bool? |
| 1495 | if new is not DEFAULT: |
| 1496 | raise TypeError( |
| 1497 | "autospec creates the mock for you. Can't specify " |
| 1498 | "autospec and new." |
| 1499 | ) |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1500 | if original is DEFAULT: |
Michael Foord | 9925473 | 2012-03-25 19:07:33 +0100 | [diff] [blame] | 1501 | raise TypeError("Can't use 'autospec' with create=True") |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1502 | spec_set = bool(spec_set) |
| 1503 | if autospec is True: |
| 1504 | autospec = original |
| 1505 | |
| 1506 | new = create_autospec(autospec, spec_set=spec_set, |
| 1507 | _name=self.attribute, **kwargs) |
| 1508 | elif kwargs: |
| 1509 | # can't set keyword args when we aren't creating the mock |
| 1510 | # XXXX If new is a Mock we could call new.configure_mock(**kwargs) |
| 1511 | raise TypeError("Can't pass kwargs to a mock we aren't creating") |
| 1512 | |
| 1513 | new_attr = new |
| 1514 | |
| 1515 | self.temp_original = original |
| 1516 | self.is_local = local |
| 1517 | setattr(self.target, self.attribute, new_attr) |
| 1518 | if self.attribute_name is not None: |
| 1519 | extra_args = {} |
| 1520 | if self.new is DEFAULT: |
| 1521 | extra_args[self.attribute_name] = new |
| 1522 | for patching in self.additional_patchers: |
| 1523 | arg = patching.__enter__() |
| 1524 | if patching.new is DEFAULT: |
| 1525 | extra_args.update(arg) |
| 1526 | return extra_args |
| 1527 | |
| 1528 | return new |
| 1529 | |
| 1530 | |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1531 | def __exit__(self, *exc_info): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1532 | """Undo the patch.""" |
| 1533 | if not _is_started(self): |
Xtreak | 02b84cb | 2019-03-29 02:38:43 +0530 | [diff] [blame] | 1534 | return |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1535 | |
| 1536 | if self.is_local and self.temp_original is not DEFAULT: |
| 1537 | setattr(self.target, self.attribute, self.temp_original) |
| 1538 | else: |
| 1539 | delattr(self.target, self.attribute) |
Senthil Kumaran | 81bc927 | 2016-01-08 23:43:29 -0800 | [diff] [blame] | 1540 | if not self.create and (not hasattr(self.target, self.attribute) or |
| 1541 | self.attribute in ('__doc__', '__module__', |
| 1542 | '__defaults__', '__annotations__', |
| 1543 | '__kwdefaults__')): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1544 | # needed for proxy objects like django settings |
| 1545 | setattr(self.target, self.attribute, self.temp_original) |
| 1546 | |
| 1547 | del self.temp_original |
| 1548 | del self.is_local |
| 1549 | del self.target |
| 1550 | for patcher in reversed(self.additional_patchers): |
| 1551 | if _is_started(patcher): |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1552 | patcher.__exit__(*exc_info) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1553 | |
Michael Foord | f7c4158 | 2012-06-10 20:36:32 +0100 | [diff] [blame] | 1554 | |
| 1555 | def start(self): |
| 1556 | """Activate a patch, returning any created mock.""" |
| 1557 | result = self.__enter__() |
Michael Foord | ebc1a30 | 2014-04-15 17:21:08 -0400 | [diff] [blame] | 1558 | self._active_patches.append(self) |
Michael Foord | f7c4158 | 2012-06-10 20:36:32 +0100 | [diff] [blame] | 1559 | return result |
| 1560 | |
| 1561 | |
| 1562 | def stop(self): |
| 1563 | """Stop an active patch.""" |
Michael Foord | ebc1a30 | 2014-04-15 17:21:08 -0400 | [diff] [blame] | 1564 | try: |
| 1565 | self._active_patches.remove(self) |
| 1566 | except ValueError: |
| 1567 | # If the patch hasn't been started this will fail |
| 1568 | pass |
| 1569 | |
Michael Foord | f7c4158 | 2012-06-10 20:36:32 +0100 | [diff] [blame] | 1570 | return self.__exit__() |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1571 | |
| 1572 | |
| 1573 | |
| 1574 | def _get_target(target): |
| 1575 | try: |
| 1576 | target, attribute = target.rsplit('.', 1) |
| 1577 | except (TypeError, ValueError): |
| 1578 | raise TypeError("Need a valid target to patch. You supplied: %r" % |
| 1579 | (target,)) |
| 1580 | getter = lambda: _importer(target) |
| 1581 | return getter, attribute |
| 1582 | |
| 1583 | |
| 1584 | def _patch_object( |
| 1585 | target, attribute, new=DEFAULT, spec=None, |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1586 | create=False, spec_set=None, autospec=None, |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1587 | new_callable=None, **kwargs |
| 1588 | ): |
| 1589 | """ |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1590 | patch the named member (`attribute`) on an object (`target`) with a mock |
| 1591 | object. |
| 1592 | |
| 1593 | `patch.object` can be used as a decorator, class decorator or a context |
| 1594 | manager. Arguments `new`, `spec`, `create`, `spec_set`, |
| 1595 | `autospec` and `new_callable` have the same meaning as for `patch`. Like |
| 1596 | `patch`, `patch.object` takes arbitrary keyword arguments for configuring |
| 1597 | the mock object it creates. |
| 1598 | |
| 1599 | When used as a class decorator `patch.object` honours `patch.TEST_PREFIX` |
| 1600 | for choosing which methods to wrap. |
| 1601 | """ |
Elena Oat | cd90a52 | 2019-12-08 12:14:38 -0800 | [diff] [blame] | 1602 | if type(target) is str: |
| 1603 | raise TypeError( |
| 1604 | f"{target!r} must be the actual object to be patched, not a str" |
| 1605 | ) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1606 | getter = lambda: target |
| 1607 | return _patch( |
| 1608 | getter, attribute, new, spec, create, |
| 1609 | spec_set, autospec, new_callable, kwargs |
| 1610 | ) |
| 1611 | |
| 1612 | |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1613 | def _patch_multiple(target, spec=None, create=False, spec_set=None, |
| 1614 | autospec=None, new_callable=None, **kwargs): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1615 | """Perform multiple patches in a single call. It takes the object to be |
| 1616 | patched (either as an object or a string to fetch the object by importing) |
| 1617 | and keyword arguments for the patches:: |
| 1618 | |
| 1619 | with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): |
| 1620 | ... |
| 1621 | |
| 1622 | Use `DEFAULT` as the value if you want `patch.multiple` to create |
| 1623 | mocks for you. In this case the created mocks are passed into a decorated |
| 1624 | function by keyword, and a dictionary is returned when `patch.multiple` is |
| 1625 | used as a context manager. |
| 1626 | |
| 1627 | `patch.multiple` can be used as a decorator, class decorator or a context |
| 1628 | manager. The arguments `spec`, `spec_set`, `create`, |
| 1629 | `autospec` and `new_callable` have the same meaning as for `patch`. These |
| 1630 | arguments will be applied to *all* patches done by `patch.multiple`. |
| 1631 | |
| 1632 | When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX` |
| 1633 | for choosing which methods to wrap. |
| 1634 | """ |
| 1635 | if type(target) is str: |
| 1636 | getter = lambda: _importer(target) |
| 1637 | else: |
| 1638 | getter = lambda: target |
| 1639 | |
| 1640 | if not kwargs: |
| 1641 | raise ValueError( |
| 1642 | 'Must supply at least one keyword argument with patch.multiple' |
| 1643 | ) |
| 1644 | # need to wrap in a list for python 3, where items is a view |
| 1645 | items = list(kwargs.items()) |
| 1646 | attribute, new = items[0] |
| 1647 | patcher = _patch( |
| 1648 | getter, attribute, new, spec, create, spec_set, |
| 1649 | autospec, new_callable, {} |
| 1650 | ) |
| 1651 | patcher.attribute_name = attribute |
| 1652 | for attribute, new in items[1:]: |
| 1653 | this_patcher = _patch( |
| 1654 | getter, attribute, new, spec, create, spec_set, |
| 1655 | autospec, new_callable, {} |
| 1656 | ) |
| 1657 | this_patcher.attribute_name = attribute |
| 1658 | patcher.additional_patchers.append(this_patcher) |
| 1659 | return patcher |
| 1660 | |
| 1661 | |
| 1662 | def patch( |
| 1663 | target, new=DEFAULT, spec=None, create=False, |
Michael Foord | 50a8c0e | 2012-03-25 18:57:58 +0100 | [diff] [blame] | 1664 | spec_set=None, autospec=None, new_callable=None, **kwargs |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1665 | ): |
| 1666 | """ |
| 1667 | `patch` acts as a function decorator, class decorator or a context |
| 1668 | manager. Inside the body of the function or with statement, the `target` |
Michael Foord | 54b3db8 | 2012-03-28 15:08:08 +0100 | [diff] [blame] | 1669 | is patched with a `new` object. When the function/with statement exits |
| 1670 | the patch is undone. |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1671 | |
Mario Corchero | f5e7f39 | 2019-09-09 15:18:06 +0100 | [diff] [blame] | 1672 | If `new` is omitted, then the target is replaced with an |
| 1673 | `AsyncMock if the patched object is an async function or a |
| 1674 | `MagicMock` otherwise. If `patch` is used as a decorator and `new` is |
Michael Foord | 54b3db8 | 2012-03-28 15:08:08 +0100 | [diff] [blame] | 1675 | omitted, the created mock is passed in as an extra argument to the |
| 1676 | decorated function. If `patch` is used as a context manager the created |
| 1677 | mock is returned by the context manager. |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1678 | |
Michael Foord | 54b3db8 | 2012-03-28 15:08:08 +0100 | [diff] [blame] | 1679 | `target` should be a string in the form `'package.module.ClassName'`. The |
| 1680 | `target` is imported and the specified object replaced with the `new` |
| 1681 | object, so the `target` must be importable from the environment you are |
| 1682 | calling `patch` from. The target is imported when the decorated function |
| 1683 | is executed, not at decoration time. |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1684 | |
| 1685 | The `spec` and `spec_set` keyword arguments are passed to the `MagicMock` |
| 1686 | if patch is creating one for you. |
| 1687 | |
| 1688 | In addition you can pass `spec=True` or `spec_set=True`, which causes |
| 1689 | patch to pass in the object being mocked as the spec/spec_set object. |
| 1690 | |
| 1691 | `new_callable` allows you to specify a different class, or callable object, |
Mario Corchero | f5e7f39 | 2019-09-09 15:18:06 +0100 | [diff] [blame] | 1692 | that will be called to create the `new` object. By default `AsyncMock` is |
| 1693 | used for async functions and `MagicMock` for the rest. |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1694 | |
| 1695 | A more powerful form of `spec` is `autospec`. If you set `autospec=True` |
Robert Collins | 92b3e065 | 2015-07-17 21:58:36 +1200 | [diff] [blame] | 1696 | then the mock will be created with a spec from the object being replaced. |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1697 | All attributes of the mock will also have the spec of the corresponding |
| 1698 | attribute of the object being replaced. Methods and functions being |
| 1699 | mocked will have their arguments checked and will raise a `TypeError` if |
| 1700 | they are called with the wrong signature. For mocks replacing a class, |
| 1701 | their return value (the 'instance') will have the same spec as the class. |
| 1702 | |
| 1703 | Instead of `autospec=True` you can pass `autospec=some_object` to use an |
| 1704 | arbitrary object as the spec instead of the one being replaced. |
| 1705 | |
| 1706 | By default `patch` will fail to replace attributes that don't exist. If |
| 1707 | you pass in `create=True`, and the attribute doesn't exist, patch will |
| 1708 | create the attribute for you when the patched function is called, and |
| 1709 | delete it again afterwards. This is useful for writing tests against |
Terry Jan Reedy | 0f84764 | 2013-03-11 18:34:00 -0400 | [diff] [blame] | 1710 | attributes that your production code creates at runtime. It is off by |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1711 | default because it can be dangerous. With it switched on you can write |
| 1712 | passing tests against APIs that don't actually exist! |
| 1713 | |
| 1714 | Patch can be used as a `TestCase` class decorator. It works by |
| 1715 | decorating each test method in the class. This reduces the boilerplate |
| 1716 | code when your test methods share a common patchings set. `patch` finds |
| 1717 | tests by looking for method names that start with `patch.TEST_PREFIX`. |
| 1718 | By default this is `test`, which matches the way `unittest` finds tests. |
| 1719 | You can specify an alternative prefix by setting `patch.TEST_PREFIX`. |
| 1720 | |
| 1721 | Patch can be used as a context manager, with the with statement. Here the |
| 1722 | patching applies to the indented block after the with statement. If you |
| 1723 | use "as" then the patched object will be bound to the name after the |
| 1724 | "as"; very useful if `patch` is creating a mock object for you. |
| 1725 | |
| 1726 | `patch` takes arbitrary keyword arguments. These will be passed to |
| 1727 | the `Mock` (or `new_callable`) on construction. |
| 1728 | |
| 1729 | `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are |
| 1730 | available for alternate use-cases. |
| 1731 | """ |
| 1732 | getter, attribute = _get_target(target) |
| 1733 | return _patch( |
| 1734 | getter, attribute, new, spec, create, |
| 1735 | spec_set, autospec, new_callable, kwargs |
| 1736 | ) |
| 1737 | |
| 1738 | |
| 1739 | class _patch_dict(object): |
| 1740 | """ |
| 1741 | Patch a dictionary, or dictionary like object, and restore the dictionary |
| 1742 | to its original state after the test. |
| 1743 | |
| 1744 | `in_dict` can be a dictionary or a mapping like container. If it is a |
| 1745 | mapping then it must at least support getting, setting and deleting items |
| 1746 | plus iterating over keys. |
| 1747 | |
| 1748 | `in_dict` can also be a string specifying the name of the dictionary, which |
| 1749 | will then be fetched by importing it. |
| 1750 | |
| 1751 | `values` can be a dictionary of values to set in the dictionary. `values` |
| 1752 | can also be an iterable of `(key, value)` pairs. |
| 1753 | |
| 1754 | If `clear` is True then the dictionary will be cleared before the new |
| 1755 | values are set. |
| 1756 | |
| 1757 | `patch.dict` can also be called with arbitrary keyword arguments to set |
| 1758 | values in the dictionary:: |
| 1759 | |
| 1760 | with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()): |
| 1761 | ... |
| 1762 | |
| 1763 | `patch.dict` can be used as a context manager, decorator or class |
| 1764 | decorator. When used as a class decorator `patch.dict` honours |
| 1765 | `patch.TEST_PREFIX` for choosing which methods to wrap. |
| 1766 | """ |
| 1767 | |
| 1768 | def __init__(self, in_dict, values=(), clear=False, **kwargs): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1769 | self.in_dict = in_dict |
| 1770 | # support any argument supported by dict(...) constructor |
| 1771 | self.values = dict(values) |
| 1772 | self.values.update(kwargs) |
| 1773 | self.clear = clear |
| 1774 | self._original = None |
| 1775 | |
| 1776 | |
| 1777 | def __call__(self, f): |
| 1778 | if isinstance(f, type): |
| 1779 | return self.decorate_class(f) |
| 1780 | @wraps(f) |
| 1781 | def _inner(*args, **kw): |
| 1782 | self._patch_dict() |
| 1783 | try: |
| 1784 | return f(*args, **kw) |
| 1785 | finally: |
| 1786 | self._unpatch_dict() |
| 1787 | |
| 1788 | return _inner |
| 1789 | |
| 1790 | |
| 1791 | def decorate_class(self, klass): |
| 1792 | for attr in dir(klass): |
| 1793 | attr_value = getattr(klass, attr) |
| 1794 | if (attr.startswith(patch.TEST_PREFIX) and |
| 1795 | hasattr(attr_value, "__call__")): |
| 1796 | decorator = _patch_dict(self.in_dict, self.values, self.clear) |
| 1797 | decorated = decorator(attr_value) |
| 1798 | setattr(klass, attr, decorated) |
| 1799 | return klass |
| 1800 | |
| 1801 | |
| 1802 | def __enter__(self): |
| 1803 | """Patch the dict.""" |
| 1804 | self._patch_dict() |
Mario Corchero | 0453081 | 2019-05-28 13:53:31 +0100 | [diff] [blame] | 1805 | return self.in_dict |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1806 | |
| 1807 | |
| 1808 | def _patch_dict(self): |
| 1809 | values = self.values |
Xtreak | a875ea5 | 2019-02-25 00:24:49 +0530 | [diff] [blame] | 1810 | if isinstance(self.in_dict, str): |
| 1811 | self.in_dict = _importer(self.in_dict) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1812 | in_dict = self.in_dict |
| 1813 | clear = self.clear |
| 1814 | |
| 1815 | try: |
| 1816 | original = in_dict.copy() |
| 1817 | except AttributeError: |
| 1818 | # dict like object with no copy method |
| 1819 | # must support iteration over keys |
| 1820 | original = {} |
| 1821 | for key in in_dict: |
| 1822 | original[key] = in_dict[key] |
| 1823 | self._original = original |
| 1824 | |
| 1825 | if clear: |
| 1826 | _clear_dict(in_dict) |
| 1827 | |
| 1828 | try: |
| 1829 | in_dict.update(values) |
| 1830 | except AttributeError: |
| 1831 | # dict like object with no update method |
| 1832 | for key in values: |
| 1833 | in_dict[key] = values[key] |
| 1834 | |
| 1835 | |
| 1836 | def _unpatch_dict(self): |
| 1837 | in_dict = self.in_dict |
| 1838 | original = self._original |
| 1839 | |
| 1840 | _clear_dict(in_dict) |
| 1841 | |
| 1842 | try: |
| 1843 | in_dict.update(original) |
| 1844 | except AttributeError: |
| 1845 | for key in original: |
| 1846 | in_dict[key] = original[key] |
| 1847 | |
| 1848 | |
| 1849 | def __exit__(self, *args): |
| 1850 | """Unpatch the dict.""" |
| 1851 | self._unpatch_dict() |
| 1852 | return False |
| 1853 | |
| 1854 | start = __enter__ |
| 1855 | stop = __exit__ |
| 1856 | |
| 1857 | |
| 1858 | def _clear_dict(in_dict): |
| 1859 | try: |
| 1860 | in_dict.clear() |
| 1861 | except AttributeError: |
| 1862 | keys = list(in_dict) |
| 1863 | for key in keys: |
| 1864 | del in_dict[key] |
| 1865 | |
| 1866 | |
Michael Foord | f7c4158 | 2012-06-10 20:36:32 +0100 | [diff] [blame] | 1867 | def _patch_stopall(): |
Michael Foord | ebc1a30 | 2014-04-15 17:21:08 -0400 | [diff] [blame] | 1868 | """Stop all active patches. LIFO to unroll nested patches.""" |
| 1869 | for patch in reversed(_patch._active_patches): |
Michael Foord | f7c4158 | 2012-06-10 20:36:32 +0100 | [diff] [blame] | 1870 | patch.stop() |
| 1871 | |
| 1872 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1873 | patch.object = _patch_object |
| 1874 | patch.dict = _patch_dict |
| 1875 | patch.multiple = _patch_multiple |
Michael Foord | f7c4158 | 2012-06-10 20:36:32 +0100 | [diff] [blame] | 1876 | patch.stopall = _patch_stopall |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1877 | patch.TEST_PREFIX = 'test' |
| 1878 | |
| 1879 | magic_methods = ( |
| 1880 | "lt le gt ge eq ne " |
| 1881 | "getitem setitem delitem " |
| 1882 | "len contains iter " |
| 1883 | "hash str sizeof " |
| 1884 | "enter exit " |
Berker Peksag | a785dec | 2015-03-15 01:51:56 +0200 | [diff] [blame] | 1885 | # we added divmod and rdivmod here instead of numerics |
| 1886 | # because there is no idivmod |
| 1887 | "divmod rdivmod neg pos abs invert " |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1888 | "complex int float index " |
John Reese | 6c4fab0 | 2018-05-22 13:01:10 -0700 | [diff] [blame] | 1889 | "round trunc floor ceil " |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1890 | "bool next " |
Max Bélanger | 6c83d9f | 2018-10-25 14:48:58 -0700 | [diff] [blame] | 1891 | "fspath " |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 1892 | "aiter " |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1893 | ) |
| 1894 | |
Michael Foord | d2623d7 | 2014-04-14 11:23:48 -0400 | [diff] [blame] | 1895 | numerics = ( |
Berker Peksag | 9bd8af7 | 2015-03-12 20:42:48 +0200 | [diff] [blame] | 1896 | "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv" |
Michael Foord | d2623d7 | 2014-04-14 11:23:48 -0400 | [diff] [blame] | 1897 | ) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1898 | inplace = ' '.join('i%s' % n for n in numerics.split()) |
| 1899 | right = ' '.join('r%s' % n for n in numerics.split()) |
| 1900 | |
| 1901 | # not including __prepare__, __instancecheck__, __subclasscheck__ |
| 1902 | # (as they are metaclass methods) |
| 1903 | # __del__ is not supported at all as it causes problems if it exists |
| 1904 | |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 1905 | _non_defaults = { |
| 1906 | '__get__', '__set__', '__delete__', '__reversed__', '__missing__', |
| 1907 | '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__', |
| 1908 | '__getstate__', '__setstate__', '__getformat__', '__setformat__', |
| 1909 | '__repr__', '__dir__', '__subclasses__', '__format__', |
Lisa Roach | 8b03f94 | 2019-09-19 21:04:18 -0700 | [diff] [blame] | 1910 | '__getnewargs_ex__', |
Victor Stinner | eb1a995 | 2014-12-11 22:25:49 +0100 | [diff] [blame] | 1911 | } |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1912 | |
| 1913 | |
| 1914 | def _get_method(name, func): |
| 1915 | "Turns a callable object (like a mock) into a real function" |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 1916 | def method(self, /, *args, **kw): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1917 | return func(self, *args, **kw) |
| 1918 | method.__name__ = name |
| 1919 | return method |
| 1920 | |
| 1921 | |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 1922 | _magics = { |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1923 | '__%s__' % method for method in |
| 1924 | ' '.join([magic_methods, numerics, inplace, right]).split() |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 1925 | } |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1926 | |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 1927 | # Magic methods used for async `with` statements |
| 1928 | _async_method_magics = {"__aenter__", "__aexit__", "__anext__"} |
Lisa Roach | 8b03f94 | 2019-09-19 21:04:18 -0700 | [diff] [blame] | 1929 | # Magic methods that are only used with async calls but are synchronous functions themselves |
| 1930 | _sync_async_magics = {"__aiter__"} |
| 1931 | _async_magics = _async_method_magics | _sync_async_magics |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 1932 | |
Lisa Roach | 8b03f94 | 2019-09-19 21:04:18 -0700 | [diff] [blame] | 1933 | _all_sync_magics = _magics | _non_defaults |
| 1934 | _all_magics = _all_sync_magics | _async_magics |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1935 | |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 1936 | _unsupported_magics = { |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1937 | '__getattr__', '__setattr__', |
Serhiy Storchaka | 34fd4c2 | 2018-11-05 16:20:25 +0200 | [diff] [blame] | 1938 | '__init__', '__new__', '__prepare__', |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1939 | '__instancecheck__', '__subclasscheck__', |
| 1940 | '__del__' |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 1941 | } |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1942 | |
| 1943 | _calculate_return_value = { |
| 1944 | '__hash__': lambda self: object.__hash__(self), |
| 1945 | '__str__': lambda self: object.__str__(self), |
| 1946 | '__sizeof__': lambda self: object.__sizeof__(self), |
Max Bélanger | 6c83d9f | 2018-10-25 14:48:58 -0700 | [diff] [blame] | 1947 | '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}", |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1948 | } |
| 1949 | |
| 1950 | _return_values = { |
Michael Foord | 313f85f | 2012-03-25 18:16:07 +0100 | [diff] [blame] | 1951 | '__lt__': NotImplemented, |
| 1952 | '__gt__': NotImplemented, |
| 1953 | '__le__': NotImplemented, |
| 1954 | '__ge__': NotImplemented, |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1955 | '__int__': 1, |
| 1956 | '__contains__': False, |
| 1957 | '__len__': 0, |
| 1958 | '__exit__': False, |
| 1959 | '__complex__': 1j, |
| 1960 | '__float__': 1.0, |
| 1961 | '__bool__': True, |
| 1962 | '__index__': 1, |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 1963 | '__aexit__': False, |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1964 | } |
| 1965 | |
| 1966 | |
| 1967 | def _get_eq(self): |
| 1968 | def __eq__(other): |
| 1969 | ret_val = self.__eq__._mock_return_value |
| 1970 | if ret_val is not DEFAULT: |
| 1971 | return ret_val |
Serhiy Storchaka | 362f058 | 2017-01-21 23:12:58 +0200 | [diff] [blame] | 1972 | if self is other: |
| 1973 | return True |
| 1974 | return NotImplemented |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1975 | return __eq__ |
| 1976 | |
| 1977 | def _get_ne(self): |
| 1978 | def __ne__(other): |
| 1979 | if self.__ne__._mock_return_value is not DEFAULT: |
| 1980 | return DEFAULT |
Serhiy Storchaka | 362f058 | 2017-01-21 23:12:58 +0200 | [diff] [blame] | 1981 | if self is other: |
| 1982 | return False |
| 1983 | return NotImplemented |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 1984 | return __ne__ |
| 1985 | |
| 1986 | def _get_iter(self): |
| 1987 | def __iter__(): |
| 1988 | ret_val = self.__iter__._mock_return_value |
| 1989 | if ret_val is DEFAULT: |
| 1990 | return iter([]) |
| 1991 | # if ret_val was already an iterator, then calling iter on it should |
| 1992 | # return the iterator unchanged |
| 1993 | return iter(ret_val) |
| 1994 | return __iter__ |
| 1995 | |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 1996 | def _get_async_iter(self): |
| 1997 | def __aiter__(): |
| 1998 | ret_val = self.__aiter__._mock_return_value |
| 1999 | if ret_val is DEFAULT: |
| 2000 | return _AsyncIterator(iter([])) |
| 2001 | return _AsyncIterator(iter(ret_val)) |
| 2002 | return __aiter__ |
| 2003 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2004 | _side_effect_methods = { |
| 2005 | '__eq__': _get_eq, |
| 2006 | '__ne__': _get_ne, |
| 2007 | '__iter__': _get_iter, |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2008 | '__aiter__': _get_async_iter |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2009 | } |
| 2010 | |
| 2011 | |
| 2012 | |
| 2013 | def _set_return_value(mock, method, name): |
| 2014 | fixed = _return_values.get(name, DEFAULT) |
| 2015 | if fixed is not DEFAULT: |
| 2016 | method.return_value = fixed |
| 2017 | return |
| 2018 | |
marcoramirezmx | a9187c3 | 2019-09-16 11:34:46 -0500 | [diff] [blame] | 2019 | return_calculator = _calculate_return_value.get(name) |
| 2020 | if return_calculator is not None: |
| 2021 | return_value = return_calculator(mock) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2022 | method.return_value = return_value |
| 2023 | return |
| 2024 | |
| 2025 | side_effector = _side_effect_methods.get(name) |
| 2026 | if side_effector is not None: |
| 2027 | method.side_effect = side_effector(mock) |
| 2028 | |
| 2029 | |
| 2030 | |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 2031 | class MagicMixin(Base): |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2032 | def __init__(self, /, *args, **kw): |
Łukasz Langa | a468db9 | 2015-04-13 23:12:42 -0700 | [diff] [blame] | 2033 | self._mock_set_magics() # make magic work for kwargs in init |
Nick Coghlan | 0b43bcf | 2012-05-27 18:17:07 +1000 | [diff] [blame] | 2034 | _safe_super(MagicMixin, self).__init__(*args, **kw) |
Łukasz Langa | a468db9 | 2015-04-13 23:12:42 -0700 | [diff] [blame] | 2035 | self._mock_set_magics() # fix magic broken by upper level init |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2036 | |
| 2037 | |
| 2038 | def _mock_set_magics(self): |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 2039 | orig_magics = _magics | _async_method_magics |
| 2040 | these_magics = orig_magics |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2041 | |
Łukasz Langa | a468db9 | 2015-04-13 23:12:42 -0700 | [diff] [blame] | 2042 | if getattr(self, "_mock_methods", None) is not None: |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 2043 | these_magics = orig_magics.intersection(self._mock_methods) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2044 | |
| 2045 | remove_magics = set() |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 2046 | remove_magics = orig_magics - these_magics |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2047 | |
| 2048 | for entry in remove_magics: |
| 2049 | if entry in type(self).__dict__: |
| 2050 | # remove unneeded magic methods |
| 2051 | delattr(self, entry) |
| 2052 | |
| 2053 | # don't overwrite existing attributes if called a second time |
| 2054 | these_magics = these_magics - set(type(self).__dict__) |
| 2055 | |
| 2056 | _type = type(self) |
| 2057 | for entry in these_magics: |
| 2058 | setattr(_type, entry, MagicProxy(entry, self)) |
| 2059 | |
| 2060 | |
| 2061 | |
| 2062 | class NonCallableMagicMock(MagicMixin, NonCallableMock): |
| 2063 | """A version of `MagicMock` that isn't callable.""" |
| 2064 | def mock_add_spec(self, spec, spec_set=False): |
| 2065 | """Add a spec to a mock. `spec` can either be an object or a |
| 2066 | list of strings. Only attributes on the `spec` can be fetched as |
| 2067 | attributes from the mock. |
| 2068 | |
| 2069 | If `spec_set` is True then only attributes on the spec can be set.""" |
| 2070 | self._mock_add_spec(spec, spec_set) |
| 2071 | self._mock_set_magics() |
| 2072 | |
| 2073 | |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 2074 | class AsyncMagicMixin(MagicMixin): |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2075 | def __init__(self, /, *args, **kw): |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 2076 | self._mock_set_magics() # make magic work for kwargs in init |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2077 | _safe_super(AsyncMagicMixin, self).__init__(*args, **kw) |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 2078 | self._mock_set_magics() # fix magic broken by upper level init |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2079 | |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 2080 | class MagicMock(MagicMixin, Mock): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2081 | """ |
| 2082 | MagicMock is a subclass of Mock with default implementations |
| 2083 | of most of the magic methods. You can use MagicMock without having to |
| 2084 | configure the magic methods yourself. |
| 2085 | |
| 2086 | If you use the `spec` or `spec_set` arguments then *only* magic |
| 2087 | methods that exist in the spec will be created. |
| 2088 | |
| 2089 | Attributes and the return value of a `MagicMock` will also be `MagicMocks`. |
| 2090 | """ |
| 2091 | def mock_add_spec(self, spec, spec_set=False): |
| 2092 | """Add a spec to a mock. `spec` can either be an object or a |
| 2093 | list of strings. Only attributes on the `spec` can be fetched as |
| 2094 | attributes from the mock. |
| 2095 | |
| 2096 | If `spec_set` is True then only attributes on the spec can be set.""" |
| 2097 | self._mock_add_spec(spec, spec_set) |
| 2098 | self._mock_set_magics() |
| 2099 | |
| 2100 | |
| 2101 | |
Lisa Roach | 9a7d951 | 2019-09-28 18:42:44 -0700 | [diff] [blame] | 2102 | class MagicProxy(Base): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2103 | def __init__(self, name, parent): |
| 2104 | self.name = name |
| 2105 | self.parent = parent |
| 2106 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2107 | def create_mock(self): |
| 2108 | entry = self.name |
| 2109 | parent = self.parent |
| 2110 | m = parent._get_child_mock(name=entry, _new_name=entry, |
| 2111 | _new_parent=parent) |
| 2112 | setattr(parent, entry, m) |
| 2113 | _set_return_value(parent, m, entry) |
| 2114 | return m |
| 2115 | |
| 2116 | def __get__(self, obj, _type=None): |
| 2117 | return self.create_mock() |
| 2118 | |
| 2119 | |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2120 | class AsyncMockMixin(Base): |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2121 | await_count = _delegating_property('await_count') |
| 2122 | await_args = _delegating_property('await_args') |
| 2123 | await_args_list = _delegating_property('await_args_list') |
| 2124 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2125 | def __init__(self, /, *args, **kwargs): |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2126 | super().__init__(*args, **kwargs) |
| 2127 | # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an |
| 2128 | # object is a coroutine. Without this check it looks to see if it is a |
| 2129 | # function/method, which in this case it is not (since it is an |
| 2130 | # AsyncMock). |
| 2131 | # It is set through __dict__ because when spec_set is True, this |
| 2132 | # attribute is likely undefined. |
| 2133 | self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2134 | self.__dict__['_mock_await_count'] = 0 |
| 2135 | self.__dict__['_mock_await_args'] = None |
| 2136 | self.__dict__['_mock_await_args_list'] = _CallList() |
| 2137 | code_mock = NonCallableMock(spec_set=CodeType) |
| 2138 | code_mock.co_flags = inspect.CO_COROUTINE |
| 2139 | self.__dict__['__code__'] = code_mock |
| 2140 | |
Jason Fried | 046442d | 2019-11-20 16:27:51 -0800 | [diff] [blame] | 2141 | async def _execute_mock_call(self, /, *args, **kwargs): |
| 2142 | # This is nearly just like super(), except for sepcial handling |
| 2143 | # of coroutines |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2144 | |
| 2145 | _call = self.call_args |
Jason Fried | 046442d | 2019-11-20 16:27:51 -0800 | [diff] [blame] | 2146 | self.await_count += 1 |
| 2147 | self.await_args = _call |
| 2148 | self.await_args_list.append(_call) |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2149 | |
Jason Fried | 046442d | 2019-11-20 16:27:51 -0800 | [diff] [blame] | 2150 | effect = self.side_effect |
| 2151 | if effect is not None: |
| 2152 | if _is_exception(effect): |
| 2153 | raise effect |
| 2154 | elif not _callable(effect): |
| 2155 | try: |
| 2156 | result = next(effect) |
| 2157 | except StopIteration: |
| 2158 | # It is impossible to propogate a StopIteration |
| 2159 | # through coroutines because of PEP 479 |
| 2160 | raise StopAsyncIteration |
| 2161 | if _is_exception(result): |
| 2162 | raise result |
| 2163 | elif asyncio.iscoroutinefunction(effect): |
| 2164 | result = await effect(*args, **kwargs) |
| 2165 | else: |
| 2166 | result = effect(*args, **kwargs) |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2167 | |
Jason Fried | 046442d | 2019-11-20 16:27:51 -0800 | [diff] [blame] | 2168 | if result is not DEFAULT: |
| 2169 | return result |
| 2170 | |
| 2171 | if self._mock_return_value is not DEFAULT: |
| 2172 | return self.return_value |
| 2173 | |
| 2174 | if self._mock_wraps is not None: |
| 2175 | if asyncio.iscoroutinefunction(self._mock_wraps): |
| 2176 | return await self._mock_wraps(*args, **kwargs) |
| 2177 | return self._mock_wraps(*args, **kwargs) |
| 2178 | |
| 2179 | return self.return_value |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2180 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2181 | def assert_awaited(self): |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2182 | """ |
| 2183 | Assert that the mock was awaited at least once. |
| 2184 | """ |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2185 | if self.await_count == 0: |
| 2186 | msg = f"Expected {self._mock_name or 'mock'} to have been awaited." |
| 2187 | raise AssertionError(msg) |
| 2188 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2189 | def assert_awaited_once(self): |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2190 | """ |
| 2191 | Assert that the mock was awaited exactly once. |
| 2192 | """ |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2193 | if not self.await_count == 1: |
| 2194 | msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once." |
| 2195 | f" Awaited {self.await_count} times.") |
| 2196 | raise AssertionError(msg) |
| 2197 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2198 | def assert_awaited_with(self, /, *args, **kwargs): |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2199 | """ |
| 2200 | Assert that the last await was with the specified arguments. |
| 2201 | """ |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2202 | if self.await_args is None: |
| 2203 | expected = self._format_mock_call_signature(args, kwargs) |
| 2204 | raise AssertionError(f'Expected await: {expected}\nNot awaited') |
| 2205 | |
| 2206 | def _error_message(): |
Xtreak | 0ae022c | 2019-05-29 12:32:26 +0530 | [diff] [blame] | 2207 | msg = self._format_mock_failure_message(args, kwargs, action='await') |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2208 | return msg |
| 2209 | |
Elizabeth Uselton | d6a9d17 | 2019-09-13 08:54:32 -0700 | [diff] [blame] | 2210 | expected = self._call_matcher(_Call((args, kwargs), two=True)) |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2211 | actual = self._call_matcher(self.await_args) |
Elizabeth Uselton | d6a9d17 | 2019-09-13 08:54:32 -0700 | [diff] [blame] | 2212 | if actual != expected: |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2213 | cause = expected if isinstance(expected, Exception) else None |
| 2214 | raise AssertionError(_error_message()) from cause |
| 2215 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2216 | def assert_awaited_once_with(self, /, *args, **kwargs): |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2217 | """ |
| 2218 | Assert that the mock was awaited exactly once and with the specified |
| 2219 | arguments. |
| 2220 | """ |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2221 | if not self.await_count == 1: |
| 2222 | msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once." |
| 2223 | f" Awaited {self.await_count} times.") |
| 2224 | raise AssertionError(msg) |
| 2225 | return self.assert_awaited_with(*args, **kwargs) |
| 2226 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2227 | def assert_any_await(self, /, *args, **kwargs): |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2228 | """ |
| 2229 | Assert the mock has ever been awaited with the specified arguments. |
| 2230 | """ |
Elizabeth Uselton | d6a9d17 | 2019-09-13 08:54:32 -0700 | [diff] [blame] | 2231 | expected = self._call_matcher(_Call((args, kwargs), two=True)) |
| 2232 | cause = expected if isinstance(expected, Exception) else None |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2233 | actual = [self._call_matcher(c) for c in self.await_args_list] |
Elizabeth Uselton | d6a9d17 | 2019-09-13 08:54:32 -0700 | [diff] [blame] | 2234 | if cause or expected not in _AnyComparer(actual): |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2235 | expected_string = self._format_mock_call_signature(args, kwargs) |
| 2236 | raise AssertionError( |
| 2237 | '%s await not found' % expected_string |
| 2238 | ) from cause |
| 2239 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2240 | def assert_has_awaits(self, calls, any_order=False): |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2241 | """ |
| 2242 | Assert the mock has been awaited with the specified calls. |
| 2243 | The :attr:`await_args_list` list is checked for the awaits. |
| 2244 | |
| 2245 | If `any_order` is False (the default) then the awaits must be |
| 2246 | sequential. There can be extra calls before or after the |
| 2247 | specified awaits. |
| 2248 | |
| 2249 | If `any_order` is True then the awaits can be in any order, but |
| 2250 | they must all appear in :attr:`await_args_list`. |
| 2251 | """ |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2252 | expected = [self._call_matcher(c) for c in calls] |
Samuel Freilich | b5a7a4f | 2019-09-24 15:08:31 -0400 | [diff] [blame] | 2253 | cause = next((e for e in expected if isinstance(e, Exception)), None) |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2254 | all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list) |
| 2255 | if not any_order: |
| 2256 | if expected not in all_awaits: |
Samuel Freilich | b5a7a4f | 2019-09-24 15:08:31 -0400 | [diff] [blame] | 2257 | if cause is None: |
| 2258 | problem = 'Awaits not found.' |
| 2259 | else: |
| 2260 | problem = ('Error processing expected awaits.\n' |
| 2261 | 'Errors: {}').format( |
| 2262 | [e if isinstance(e, Exception) else None |
| 2263 | for e in expected]) |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2264 | raise AssertionError( |
Samuel Freilich | b5a7a4f | 2019-09-24 15:08:31 -0400 | [diff] [blame] | 2265 | f'{problem}\n' |
| 2266 | f'Expected: {_CallList(calls)}\n' |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2267 | f'Actual: {self.await_args_list}' |
| 2268 | ) from cause |
| 2269 | return |
| 2270 | |
| 2271 | all_awaits = list(all_awaits) |
| 2272 | |
| 2273 | not_found = [] |
| 2274 | for kall in expected: |
| 2275 | try: |
| 2276 | all_awaits.remove(kall) |
| 2277 | except ValueError: |
| 2278 | not_found.append(kall) |
| 2279 | if not_found: |
| 2280 | raise AssertionError( |
| 2281 | '%r not all found in await list' % (tuple(not_found),) |
| 2282 | ) from cause |
| 2283 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2284 | def assert_not_awaited(self): |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2285 | """ |
| 2286 | Assert that the mock was never awaited. |
| 2287 | """ |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2288 | if self.await_count != 0: |
Xtreak | ff6b2e6 | 2019-05-27 18:26:23 +0530 | [diff] [blame] | 2289 | msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited." |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2290 | f" Awaited {self.await_count} times.") |
| 2291 | raise AssertionError(msg) |
| 2292 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2293 | def reset_mock(self, /, *args, **kwargs): |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2294 | """ |
| 2295 | See :func:`.Mock.reset_mock()` |
| 2296 | """ |
| 2297 | super().reset_mock(*args, **kwargs) |
| 2298 | self.await_count = 0 |
| 2299 | self.await_args = None |
| 2300 | self.await_args_list = _CallList() |
| 2301 | |
| 2302 | |
| 2303 | class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): |
| 2304 | """ |
| 2305 | Enhance :class:`Mock` with features allowing to mock |
| 2306 | an async function. |
| 2307 | |
| 2308 | The :class:`AsyncMock` object will behave so the object is |
| 2309 | recognized as an async function, and the result of a call is an awaitable: |
| 2310 | |
| 2311 | >>> mock = AsyncMock() |
| 2312 | >>> asyncio.iscoroutinefunction(mock) |
| 2313 | True |
| 2314 | >>> inspect.isawaitable(mock()) |
| 2315 | True |
| 2316 | |
| 2317 | |
| 2318 | The result of ``mock()`` is an async function which will have the outcome |
| 2319 | of ``side_effect`` or ``return_value``: |
| 2320 | |
| 2321 | - if ``side_effect`` is a function, the async function will return the |
| 2322 | result of that function, |
| 2323 | - if ``side_effect`` is an exception, the async function will raise the |
| 2324 | exception, |
| 2325 | - if ``side_effect`` is an iterable, the async function will return the |
| 2326 | next value of the iterable, however, if the sequence of result is |
| 2327 | exhausted, ``StopIteration`` is raised immediately, |
| 2328 | - if ``side_effect`` is not defined, the async function will return the |
| 2329 | value defined by ``return_value``, hence, by default, the async function |
| 2330 | returns a new :class:`AsyncMock` object. |
| 2331 | |
| 2332 | If the outcome of ``side_effect`` or ``return_value`` is an async function, |
| 2333 | the mock async function obtained when the mock object is called will be this |
| 2334 | async function itself (and not an async function returning an async |
| 2335 | function). |
| 2336 | |
| 2337 | The test author can also specify a wrapped object with ``wraps``. In this |
| 2338 | case, the :class:`Mock` object behavior is the same as with an |
| 2339 | :class:`.Mock` object: the wrapped object may have methods |
| 2340 | defined as async function functions. |
| 2341 | |
Xtreak | e7cb23b | 2019-05-21 14:17:17 +0530 | [diff] [blame] | 2342 | Based on Martin Richard's asynctest project. |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2343 | """ |
| 2344 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2345 | |
| 2346 | class _ANY(object): |
| 2347 | "A helper object that compares equal to everything." |
| 2348 | |
| 2349 | def __eq__(self, other): |
| 2350 | return True |
| 2351 | |
| 2352 | def __ne__(self, other): |
| 2353 | return False |
| 2354 | |
| 2355 | def __repr__(self): |
| 2356 | return '<ANY>' |
| 2357 | |
| 2358 | ANY = _ANY() |
| 2359 | |
| 2360 | |
| 2361 | |
| 2362 | def _format_call_signature(name, args, kwargs): |
| 2363 | message = '%s(%%s)' % name |
| 2364 | formatted_args = '' |
| 2365 | args_string = ', '.join([repr(arg) for arg in args]) |
| 2366 | kwargs_string = ', '.join([ |
Xtreak | 9d60706 | 2019-09-09 16:25:22 +0530 | [diff] [blame] | 2367 | '%s=%r' % (key, value) for key, value in kwargs.items() |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2368 | ]) |
| 2369 | if args_string: |
| 2370 | formatted_args = args_string |
| 2371 | if kwargs_string: |
| 2372 | if formatted_args: |
| 2373 | formatted_args += ', ' |
| 2374 | formatted_args += kwargs_string |
| 2375 | |
| 2376 | return message % formatted_args |
| 2377 | |
| 2378 | |
| 2379 | |
| 2380 | class _Call(tuple): |
| 2381 | """ |
| 2382 | A tuple for holding the results of a call to a mock, either in the form |
| 2383 | `(args, kwargs)` or `(name, args, kwargs)`. |
| 2384 | |
| 2385 | If args or kwargs are empty then a call tuple will compare equal to |
| 2386 | a tuple without those values. This makes comparisons less verbose:: |
| 2387 | |
| 2388 | _Call(('name', (), {})) == ('name',) |
| 2389 | _Call(('name', (1,), {})) == ('name', (1,)) |
| 2390 | _Call(((), {'a': 'b'})) == ({'a': 'b'},) |
| 2391 | |
| 2392 | The `_Call` object provides a useful shortcut for comparing with call:: |
| 2393 | |
| 2394 | _Call(((1, 2), {'a': 3})) == call(1, 2, a=3) |
| 2395 | _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3) |
| 2396 | |
| 2397 | If the _Call has no name then it will match any name. |
| 2398 | """ |
Victor Stinner | 84b6fb0 | 2017-01-06 18:15:51 +0100 | [diff] [blame] | 2399 | def __new__(cls, value=(), name='', parent=None, two=False, |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2400 | from_kall=True): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2401 | args = () |
| 2402 | kwargs = {} |
| 2403 | _len = len(value) |
| 2404 | if _len == 3: |
| 2405 | name, args, kwargs = value |
| 2406 | elif _len == 2: |
| 2407 | first, second = value |
| 2408 | if isinstance(first, str): |
| 2409 | name = first |
| 2410 | if isinstance(second, tuple): |
| 2411 | args = second |
| 2412 | else: |
| 2413 | kwargs = second |
| 2414 | else: |
| 2415 | args, kwargs = first, second |
| 2416 | elif _len == 1: |
| 2417 | value, = value |
| 2418 | if isinstance(value, str): |
| 2419 | name = value |
| 2420 | elif isinstance(value, tuple): |
| 2421 | args = value |
| 2422 | else: |
| 2423 | kwargs = value |
| 2424 | |
| 2425 | if two: |
| 2426 | return tuple.__new__(cls, (args, kwargs)) |
| 2427 | |
| 2428 | return tuple.__new__(cls, (name, args, kwargs)) |
| 2429 | |
| 2430 | |
| 2431 | def __init__(self, value=(), name=None, parent=None, two=False, |
| 2432 | from_kall=True): |
Andrew Dunai | e63e617 | 2018-12-04 11:08:45 +0200 | [diff] [blame] | 2433 | self._mock_name = name |
| 2434 | self._mock_parent = parent |
| 2435 | self._mock_from_kall = from_kall |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2436 | |
| 2437 | |
| 2438 | def __eq__(self, other): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2439 | try: |
| 2440 | len_other = len(other) |
| 2441 | except TypeError: |
Serhiy Storchaka | 662db12 | 2019-08-08 08:42:54 +0300 | [diff] [blame] | 2442 | return NotImplemented |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2443 | |
| 2444 | self_name = '' |
| 2445 | if len(self) == 2: |
| 2446 | self_args, self_kwargs = self |
| 2447 | else: |
| 2448 | self_name, self_args, self_kwargs = self |
| 2449 | |
Andrew Dunai | e63e617 | 2018-12-04 11:08:45 +0200 | [diff] [blame] | 2450 | if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None) |
| 2451 | and self._mock_parent != other._mock_parent): |
Chris Withers | 8ca0fa9 | 2018-12-03 21:31:37 +0000 | [diff] [blame] | 2452 | return False |
| 2453 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2454 | other_name = '' |
| 2455 | if len_other == 0: |
| 2456 | other_args, other_kwargs = (), {} |
| 2457 | elif len_other == 3: |
| 2458 | other_name, other_args, other_kwargs = other |
| 2459 | elif len_other == 1: |
| 2460 | value, = other |
| 2461 | if isinstance(value, tuple): |
| 2462 | other_args = value |
| 2463 | other_kwargs = {} |
| 2464 | elif isinstance(value, str): |
| 2465 | other_name = value |
| 2466 | other_args, other_kwargs = (), {} |
| 2467 | else: |
| 2468 | other_args = () |
| 2469 | other_kwargs = value |
Berker Peksag | 3fc536f | 2015-09-09 23:35:25 +0300 | [diff] [blame] | 2470 | elif len_other == 2: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2471 | # could be (name, args) or (name, kwargs) or (args, kwargs) |
| 2472 | first, second = other |
| 2473 | if isinstance(first, str): |
| 2474 | other_name = first |
| 2475 | if isinstance(second, tuple): |
| 2476 | other_args, other_kwargs = second, {} |
| 2477 | else: |
| 2478 | other_args, other_kwargs = (), second |
| 2479 | else: |
| 2480 | other_args, other_kwargs = first, second |
Berker Peksag | 3fc536f | 2015-09-09 23:35:25 +0300 | [diff] [blame] | 2481 | else: |
| 2482 | return False |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2483 | |
| 2484 | if self_name and other_name != self_name: |
| 2485 | return False |
| 2486 | |
| 2487 | # this order is important for ANY to work! |
| 2488 | return (other_args, other_kwargs) == (self_args, self_kwargs) |
| 2489 | |
| 2490 | |
Berker Peksag | ce91387 | 2016-03-28 00:30:02 +0300 | [diff] [blame] | 2491 | __ne__ = object.__ne__ |
| 2492 | |
| 2493 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2494 | def __call__(self, /, *args, **kwargs): |
Andrew Dunai | e63e617 | 2018-12-04 11:08:45 +0200 | [diff] [blame] | 2495 | if self._mock_name is None: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2496 | return _Call(('', args, kwargs), name='()') |
| 2497 | |
Andrew Dunai | e63e617 | 2018-12-04 11:08:45 +0200 | [diff] [blame] | 2498 | name = self._mock_name + '()' |
| 2499 | return _Call((self._mock_name, args, kwargs), name=name, parent=self) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2500 | |
| 2501 | |
| 2502 | def __getattr__(self, attr): |
Andrew Dunai | e63e617 | 2018-12-04 11:08:45 +0200 | [diff] [blame] | 2503 | if self._mock_name is None: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2504 | return _Call(name=attr, from_kall=False) |
Andrew Dunai | e63e617 | 2018-12-04 11:08:45 +0200 | [diff] [blame] | 2505 | name = '%s.%s' % (self._mock_name, attr) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2506 | return _Call(name=name, parent=self, from_kall=False) |
| 2507 | |
| 2508 | |
blhsing | 72c3599 | 2019-09-11 07:28:06 -0700 | [diff] [blame] | 2509 | def __getattribute__(self, attr): |
| 2510 | if attr in tuple.__dict__: |
| 2511 | raise AttributeError |
| 2512 | return tuple.__getattribute__(self, attr) |
| 2513 | |
| 2514 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2515 | def count(self, /, *args, **kwargs): |
Kushal Das | a37b958 | 2014-09-16 18:33:37 +0530 | [diff] [blame] | 2516 | return self.__getattr__('count')(*args, **kwargs) |
| 2517 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2518 | def index(self, /, *args, **kwargs): |
Kushal Das | a37b958 | 2014-09-16 18:33:37 +0530 | [diff] [blame] | 2519 | return self.__getattr__('index')(*args, **kwargs) |
| 2520 | |
Kumar Akshay | b0df45e | 2019-03-22 13:40:40 +0530 | [diff] [blame] | 2521 | def _get_call_arguments(self): |
| 2522 | if len(self) == 2: |
| 2523 | args, kwargs = self |
| 2524 | else: |
| 2525 | name, args, kwargs = self |
| 2526 | |
| 2527 | return args, kwargs |
| 2528 | |
| 2529 | @property |
| 2530 | def args(self): |
| 2531 | return self._get_call_arguments()[0] |
| 2532 | |
| 2533 | @property |
| 2534 | def kwargs(self): |
| 2535 | return self._get_call_arguments()[1] |
| 2536 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2537 | def __repr__(self): |
Andrew Dunai | e63e617 | 2018-12-04 11:08:45 +0200 | [diff] [blame] | 2538 | if not self._mock_from_kall: |
| 2539 | name = self._mock_name or 'call' |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2540 | if name.startswith('()'): |
| 2541 | name = 'call%s' % name |
| 2542 | return name |
| 2543 | |
| 2544 | if len(self) == 2: |
| 2545 | name = 'call' |
| 2546 | args, kwargs = self |
| 2547 | else: |
| 2548 | name, args, kwargs = self |
| 2549 | if not name: |
| 2550 | name = 'call' |
| 2551 | elif not name.startswith('()'): |
| 2552 | name = 'call.%s' % name |
| 2553 | else: |
| 2554 | name = 'call%s' % name |
| 2555 | return _format_call_signature(name, args, kwargs) |
| 2556 | |
| 2557 | |
| 2558 | def call_list(self): |
| 2559 | """For a call object that represents multiple calls, `call_list` |
| 2560 | returns a list of all the intermediate calls as well as the |
| 2561 | final call.""" |
| 2562 | vals = [] |
| 2563 | thing = self |
| 2564 | while thing is not None: |
Andrew Dunai | e63e617 | 2018-12-04 11:08:45 +0200 | [diff] [blame] | 2565 | if thing._mock_from_kall: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2566 | vals.append(thing) |
Andrew Dunai | e63e617 | 2018-12-04 11:08:45 +0200 | [diff] [blame] | 2567 | thing = thing._mock_parent |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2568 | return _CallList(reversed(vals)) |
| 2569 | |
| 2570 | |
| 2571 | call = _Call(from_kall=False) |
| 2572 | |
| 2573 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2574 | def create_autospec(spec, spec_set=False, instance=False, _parent=None, |
| 2575 | _name=None, **kwargs): |
| 2576 | """Create a mock object using another object as a spec. Attributes on the |
| 2577 | mock will use the corresponding attribute on the `spec` object as their |
| 2578 | spec. |
| 2579 | |
| 2580 | Functions or methods being mocked will have their arguments checked |
| 2581 | to check that they are called with the correct signature. |
| 2582 | |
| 2583 | If `spec_set` is True then attempting to set attributes that don't exist |
| 2584 | on the spec object will raise an `AttributeError`. |
| 2585 | |
| 2586 | If a class is used as a spec then the return value of the mock (the |
| 2587 | instance of the class) will have the same spec. You can use a class as the |
| 2588 | spec for an instance object by passing `instance=True`. The returned mock |
| 2589 | will only be callable if instances of the mock are callable. |
| 2590 | |
| 2591 | `create_autospec` also takes arbitrary keyword arguments that are passed to |
| 2592 | the constructor of the created mock.""" |
| 2593 | if _is_list(spec): |
| 2594 | # can't pass a list instance to the mock constructor as it will be |
| 2595 | # interpreted as a list of strings |
| 2596 | spec = type(spec) |
| 2597 | |
| 2598 | is_type = isinstance(spec, type) |
Xtreak | ff6b2e6 | 2019-05-27 18:26:23 +0530 | [diff] [blame] | 2599 | is_async_func = _is_async_func(spec) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2600 | _kwargs = {'spec': spec} |
| 2601 | if spec_set: |
| 2602 | _kwargs = {'spec_set': spec} |
| 2603 | elif spec is None: |
| 2604 | # None we mock with a normal mock without a spec |
| 2605 | _kwargs = {} |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 2606 | if _kwargs and instance: |
| 2607 | _kwargs['_spec_as_instance'] = True |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2608 | |
| 2609 | _kwargs.update(kwargs) |
| 2610 | |
| 2611 | Klass = MagicMock |
Gregory P. Smith | d4583d7 | 2016-08-15 23:23:40 -0700 | [diff] [blame] | 2612 | if inspect.isdatadescriptor(spec): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2613 | # descriptors don't have a spec |
| 2614 | # because we don't know what type they return |
| 2615 | _kwargs = {} |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2616 | elif is_async_func: |
| 2617 | if instance: |
| 2618 | raise RuntimeError("Instance can not be True when create_autospec " |
| 2619 | "is mocking an async function") |
| 2620 | Klass = AsyncMock |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2621 | elif not _callable(spec): |
| 2622 | Klass = NonCallableMagicMock |
| 2623 | elif is_type and instance and not _instance_callable(spec): |
| 2624 | Klass = NonCallableMagicMock |
| 2625 | |
Kushal Das | 484f8a8 | 2014-04-16 01:05:50 +0530 | [diff] [blame] | 2626 | _name = _kwargs.pop('name', _name) |
| 2627 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2628 | _new_name = _name |
| 2629 | if _parent is None: |
| 2630 | # for a top level object no _new_name should be set |
| 2631 | _new_name = '' |
| 2632 | |
| 2633 | mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name, |
| 2634 | name=_name, **_kwargs) |
| 2635 | |
| 2636 | if isinstance(spec, FunctionTypes): |
| 2637 | # should only happen at the top level because we don't |
| 2638 | # recurse for functions |
| 2639 | mock = _set_signature(mock, spec) |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2640 | if is_async_func: |
Xtreak | ff6b2e6 | 2019-05-27 18:26:23 +0530 | [diff] [blame] | 2641 | _setup_async_mock(mock) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2642 | else: |
| 2643 | _check_signature(spec, mock, is_type, instance) |
| 2644 | |
| 2645 | if _parent is not None and not instance: |
| 2646 | _parent._mock_children[_name] = mock |
| 2647 | |
| 2648 | if is_type and not instance and 'return_value' not in kwargs: |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2649 | mock.return_value = create_autospec(spec, spec_set, instance=True, |
| 2650 | _name='()', _parent=mock) |
| 2651 | |
| 2652 | for entry in dir(spec): |
| 2653 | if _is_magic(entry): |
| 2654 | # MagicMock already does the useful magic methods for us |
| 2655 | continue |
| 2656 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2657 | # XXXX do we need a better way of getting attributes without |
| 2658 | # triggering code execution (?) Probably not - we need the actual |
| 2659 | # object to mock it so we would rather trigger a property than mock |
| 2660 | # the property descriptor. Likewise we want to mock out dynamically |
| 2661 | # provided attributes. |
Michael Foord | 656319e | 2012-04-13 17:39:16 +0100 | [diff] [blame] | 2662 | # XXXX what about attributes that raise exceptions other than |
| 2663 | # AttributeError on being fetched? |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2664 | # we could be resilient against it, or catch and propagate the |
| 2665 | # exception when the attribute is fetched from the mock |
Michael Foord | 656319e | 2012-04-13 17:39:16 +0100 | [diff] [blame] | 2666 | try: |
| 2667 | original = getattr(spec, entry) |
| 2668 | except AttributeError: |
| 2669 | continue |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2670 | |
| 2671 | kwargs = {'spec': original} |
| 2672 | if spec_set: |
| 2673 | kwargs = {'spec_set': original} |
| 2674 | |
| 2675 | if not isinstance(original, FunctionTypes): |
| 2676 | new = _SpecState(original, spec_set, mock, entry, instance) |
| 2677 | mock._mock_children[entry] = new |
| 2678 | else: |
| 2679 | parent = mock |
| 2680 | if isinstance(spec, FunctionTypes): |
| 2681 | parent = mock.mock |
| 2682 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2683 | skipfirst = _must_skip(spec, entry, is_type) |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 2684 | kwargs['_eat_self'] = skipfirst |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2685 | if asyncio.iscoroutinefunction(original): |
| 2686 | child_klass = AsyncMock |
| 2687 | else: |
| 2688 | child_klass = MagicMock |
| 2689 | new = child_klass(parent=parent, name=entry, _new_name=entry, |
| 2690 | _new_parent=parent, |
| 2691 | **kwargs) |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 2692 | mock._mock_children[entry] = new |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2693 | _check_signature(original, new, skipfirst=skipfirst) |
| 2694 | |
| 2695 | # so functions created with _set_signature become instance attributes, |
| 2696 | # *plus* their underlying mock exists in _mock_children of the parent |
| 2697 | # mock. Adding to _mock_children may be unnecessary where we are also |
| 2698 | # setting as an instance attribute? |
| 2699 | if isinstance(new, FunctionTypes): |
| 2700 | setattr(mock, entry, new) |
| 2701 | |
| 2702 | return mock |
| 2703 | |
| 2704 | |
| 2705 | def _must_skip(spec, entry, is_type): |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 2706 | """ |
| 2707 | Return whether we should skip the first argument on spec's `entry` |
| 2708 | attribute. |
| 2709 | """ |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2710 | if not isinstance(spec, type): |
| 2711 | if entry in getattr(spec, '__dict__', {}): |
| 2712 | # instance attribute - shouldn't skip |
| 2713 | return False |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2714 | spec = spec.__class__ |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2715 | |
| 2716 | for klass in spec.__mro__: |
| 2717 | result = klass.__dict__.get(entry, DEFAULT) |
| 2718 | if result is DEFAULT: |
| 2719 | continue |
| 2720 | if isinstance(result, (staticmethod, classmethod)): |
| 2721 | return False |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 2722 | elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes): |
| 2723 | # Normal method => skip if looked up on type |
| 2724 | # (if looked up on instance, self is already skipped) |
| 2725 | return is_type |
| 2726 | else: |
| 2727 | return False |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2728 | |
Chris Withers | adbf178 | 2019-05-01 23:04:04 +0100 | [diff] [blame] | 2729 | # function is a dynamically provided attribute |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2730 | return is_type |
| 2731 | |
| 2732 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2733 | class _SpecState(object): |
| 2734 | |
| 2735 | def __init__(self, spec, spec_set=False, parent=None, |
| 2736 | name=None, ids=None, instance=False): |
| 2737 | self.spec = spec |
| 2738 | self.ids = ids |
| 2739 | self.spec_set = spec_set |
| 2740 | self.parent = parent |
| 2741 | self.instance = instance |
| 2742 | self.name = name |
| 2743 | |
| 2744 | |
| 2745 | FunctionTypes = ( |
| 2746 | # python function |
| 2747 | type(create_autospec), |
| 2748 | # instance method |
| 2749 | type(ANY.__eq__), |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2750 | ) |
| 2751 | |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 2752 | MethodWrapperTypes = ( |
| 2753 | type(ANY.__eq__.__get__), |
| 2754 | ) |
| 2755 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2756 | |
Michael Foord | a74561a | 2012-03-25 19:03:13 +0100 | [diff] [blame] | 2757 | file_spec = None |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2758 | |
Michael Foord | 04cbe0c | 2013-03-19 17:22:51 -0700 | [diff] [blame] | 2759 | |
Rémi Lapeyre | 11a8832 | 2019-05-07 12:48:36 +0200 | [diff] [blame] | 2760 | def _to_stream(read_data): |
| 2761 | if isinstance(read_data, bytes): |
| 2762 | return io.BytesIO(read_data) |
Michael Foord | 04cbe0c | 2013-03-19 17:22:51 -0700 | [diff] [blame] | 2763 | else: |
Rémi Lapeyre | 11a8832 | 2019-05-07 12:48:36 +0200 | [diff] [blame] | 2764 | return io.StringIO(read_data) |
Michael Foord | 0dccf65 | 2012-03-25 19:11:50 +0100 | [diff] [blame] | 2765 | |
Robert Collins | 5329aaa | 2015-07-17 20:08:45 +1200 | [diff] [blame] | 2766 | |
Michael Foord | 0dccf65 | 2012-03-25 19:11:50 +0100 | [diff] [blame] | 2767 | def mock_open(mock=None, read_data=''): |
Michael Foord | 9925473 | 2012-03-25 19:07:33 +0100 | [diff] [blame] | 2768 | """ |
| 2769 | A helper function to create a mock to replace the use of `open`. It works |
| 2770 | for `open` called directly or used as a context manager. |
| 2771 | |
| 2772 | The `mock` argument is the mock object to configure. If `None` (the |
| 2773 | default) then a `MagicMock` will be created for you, with the API limited |
| 2774 | to methods or attributes available on standard file handles. |
| 2775 | |
Xtreak | 71f82a2 | 2018-12-20 21:30:21 +0530 | [diff] [blame] | 2776 | `read_data` is a string for the `read`, `readline` and `readlines` of the |
Michael Foord | 04cbe0c | 2013-03-19 17:22:51 -0700 | [diff] [blame] | 2777 | file handle to return. This is an empty string by default. |
Michael Foord | 9925473 | 2012-03-25 19:07:33 +0100 | [diff] [blame] | 2778 | """ |
Rémi Lapeyre | 11a8832 | 2019-05-07 12:48:36 +0200 | [diff] [blame] | 2779 | _read_data = _to_stream(read_data) |
| 2780 | _state = [_read_data, None] |
| 2781 | |
Robert Collins | ca647ef | 2015-07-24 03:48:20 +1200 | [diff] [blame] | 2782 | def _readlines_side_effect(*args, **kwargs): |
| 2783 | if handle.readlines.return_value is not None: |
| 2784 | return handle.readlines.return_value |
Rémi Lapeyre | 11a8832 | 2019-05-07 12:48:36 +0200 | [diff] [blame] | 2785 | return _state[0].readlines(*args, **kwargs) |
Robert Collins | ca647ef | 2015-07-24 03:48:20 +1200 | [diff] [blame] | 2786 | |
| 2787 | def _read_side_effect(*args, **kwargs): |
| 2788 | if handle.read.return_value is not None: |
| 2789 | return handle.read.return_value |
Rémi Lapeyre | 11a8832 | 2019-05-07 12:48:36 +0200 | [diff] [blame] | 2790 | return _state[0].read(*args, **kwargs) |
Robert Collins | ca647ef | 2015-07-24 03:48:20 +1200 | [diff] [blame] | 2791 | |
Rémi Lapeyre | 11a8832 | 2019-05-07 12:48:36 +0200 | [diff] [blame] | 2792 | def _readline_side_effect(*args, **kwargs): |
Tony Flury | 2087023 | 2018-09-12 23:21:16 +0100 | [diff] [blame] | 2793 | yield from _iter_side_effect() |
| 2794 | while True: |
Rémi Lapeyre | 11a8832 | 2019-05-07 12:48:36 +0200 | [diff] [blame] | 2795 | yield _state[0].readline(*args, **kwargs) |
Tony Flury | 2087023 | 2018-09-12 23:21:16 +0100 | [diff] [blame] | 2796 | |
| 2797 | def _iter_side_effect(): |
Robert Collins | ca647ef | 2015-07-24 03:48:20 +1200 | [diff] [blame] | 2798 | if handle.readline.return_value is not None: |
| 2799 | while True: |
| 2800 | yield handle.readline.return_value |
| 2801 | for line in _state[0]: |
| 2802 | yield line |
Robert Collins | ca647ef | 2015-07-24 03:48:20 +1200 | [diff] [blame] | 2803 | |
Damien Nadé | 394119a | 2019-05-23 12:03:25 +0200 | [diff] [blame] | 2804 | def _next_side_effect(): |
| 2805 | if handle.readline.return_value is not None: |
| 2806 | return handle.readline.return_value |
| 2807 | return next(_state[0]) |
| 2808 | |
Michael Foord | a74561a | 2012-03-25 19:03:13 +0100 | [diff] [blame] | 2809 | global file_spec |
| 2810 | if file_spec is None: |
| 2811 | import _io |
| 2812 | file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO)))) |
| 2813 | |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2814 | if mock is None: |
Michael Foord | 0dccf65 | 2012-03-25 19:11:50 +0100 | [diff] [blame] | 2815 | mock = MagicMock(name='open', spec=open) |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2816 | |
Robert Collins | ca647ef | 2015-07-24 03:48:20 +1200 | [diff] [blame] | 2817 | handle = MagicMock(spec=file_spec) |
| 2818 | handle.__enter__.return_value = handle |
Michael Foord | 04cbe0c | 2013-03-19 17:22:51 -0700 | [diff] [blame] | 2819 | |
Robert Collins | ca647ef | 2015-07-24 03:48:20 +1200 | [diff] [blame] | 2820 | handle.write.return_value = None |
| 2821 | handle.read.return_value = None |
| 2822 | handle.readline.return_value = None |
| 2823 | handle.readlines.return_value = None |
Michael Foord | 04cbe0c | 2013-03-19 17:22:51 -0700 | [diff] [blame] | 2824 | |
Robert Collins | ca647ef | 2015-07-24 03:48:20 +1200 | [diff] [blame] | 2825 | handle.read.side_effect = _read_side_effect |
| 2826 | _state[1] = _readline_side_effect() |
| 2827 | handle.readline.side_effect = _state[1] |
| 2828 | handle.readlines.side_effect = _readlines_side_effect |
Tony Flury | 2087023 | 2018-09-12 23:21:16 +0100 | [diff] [blame] | 2829 | handle.__iter__.side_effect = _iter_side_effect |
Damien Nadé | 394119a | 2019-05-23 12:03:25 +0200 | [diff] [blame] | 2830 | handle.__next__.side_effect = _next_side_effect |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2831 | |
Robert Collins | ca647ef | 2015-07-24 03:48:20 +1200 | [diff] [blame] | 2832 | def reset_data(*args, **kwargs): |
Rémi Lapeyre | 11a8832 | 2019-05-07 12:48:36 +0200 | [diff] [blame] | 2833 | _state[0] = _to_stream(read_data) |
Robert Collins | ca647ef | 2015-07-24 03:48:20 +1200 | [diff] [blame] | 2834 | if handle.readline.side_effect == _state[1]: |
| 2835 | # Only reset the side effect if the user hasn't overridden it. |
| 2836 | _state[1] = _readline_side_effect() |
| 2837 | handle.readline.side_effect = _state[1] |
| 2838 | return DEFAULT |
Robert Collins | 5329aaa | 2015-07-17 20:08:45 +1200 | [diff] [blame] | 2839 | |
Robert Collins | ca647ef | 2015-07-24 03:48:20 +1200 | [diff] [blame] | 2840 | mock.side_effect = reset_data |
| 2841 | mock.return_value = handle |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2842 | return mock |
| 2843 | |
| 2844 | |
| 2845 | class PropertyMock(Mock): |
Michael Foord | 9925473 | 2012-03-25 19:07:33 +0100 | [diff] [blame] | 2846 | """ |
| 2847 | A mock intended to be used as a property, or other descriptor, on a class. |
| 2848 | `PropertyMock` provides `__get__` and `__set__` methods so you can specify |
| 2849 | a return value when it is fetched. |
| 2850 | |
| 2851 | Fetching a `PropertyMock` instance from an object calls the mock, with |
| 2852 | no args. Setting it calls the mock with the value being set. |
| 2853 | """ |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 2854 | def _get_child_mock(self, /, **kwargs): |
Michael Foord | c287062 | 2012-04-13 16:57:22 +0100 | [diff] [blame] | 2855 | return MagicMock(**kwargs) |
| 2856 | |
Raymond Hettinger | 0dac68f | 2019-08-29 01:27:42 -0700 | [diff] [blame] | 2857 | def __get__(self, obj, obj_type=None): |
Michael Foord | 345266a | 2012-03-14 12:24:34 -0700 | [diff] [blame] | 2858 | return self() |
| 2859 | def __set__(self, obj, val): |
| 2860 | self(val) |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 2861 | |
| 2862 | |
| 2863 | def seal(mock): |
Mario Corchero | 96200eb | 2018-10-19 22:57:37 +0100 | [diff] [blame] | 2864 | """Disable the automatic generation of child mocks. |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 2865 | |
| 2866 | Given an input Mock, seals it to ensure no further mocks will be generated |
| 2867 | when accessing an attribute that was not already defined. |
| 2868 | |
Mario Corchero | 96200eb | 2018-10-19 22:57:37 +0100 | [diff] [blame] | 2869 | The operation recursively seals the mock passed in, meaning that |
| 2870 | the mock itself, any mocks generated by accessing one of its attributes, |
| 2871 | and all assigned mocks without a name or spec will be sealed. |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 2872 | """ |
| 2873 | mock._mock_sealed = True |
| 2874 | for attr in dir(mock): |
| 2875 | try: |
| 2876 | m = getattr(mock, attr) |
| 2877 | except AttributeError: |
| 2878 | continue |
| 2879 | if not isinstance(m, NonCallableMock): |
| 2880 | continue |
| 2881 | if m._mock_new_parent is mock: |
| 2882 | seal(m) |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2883 | |
| 2884 | |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 2885 | class _AsyncIterator: |
| 2886 | """ |
| 2887 | Wraps an iterator in an asynchronous iterator. |
| 2888 | """ |
| 2889 | def __init__(self, iterator): |
| 2890 | self.iterator = iterator |
| 2891 | code_mock = NonCallableMock(spec_set=CodeType) |
| 2892 | code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE |
| 2893 | self.__dict__['__code__'] = code_mock |
| 2894 | |
| 2895 | def __aiter__(self): |
| 2896 | return self |
| 2897 | |
| 2898 | async def __anext__(self): |
| 2899 | try: |
| 2900 | return next(self.iterator) |
| 2901 | except StopIteration: |
| 2902 | pass |
| 2903 | raise StopAsyncIteration |