You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2619 lines
84 KiB

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