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