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