annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/unittest/mock.py @ 69:33d812a61356

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