logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

mock.py (102003B)


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