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