PageRenderTime 54ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/third_party/py/mock/__init__.py

https://gitlab.com/18runt88/bazel
Python | 1536 lines | 1415 code | 62 blank | 59 comment | 78 complexity | ebe54ce85313274ebdb69f7a28ce076f MD5 | raw file
  1. # mock.py
  2. # Test tools for mocking and patching.
  3. # Copyright (C) 2007-2012 Michael Foord & the mock team
  4. # E-mail: fuzzyman AT voidspace DOT org DOT uk
  5. # mock 1.0
  6. # http://www.voidspace.org.uk/python/mock/
  7. # Released subject to the BSD License
  8. # Please see http://www.voidspace.org.uk/python/license.shtml
  9. # Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
  10. # Comments, suggestions and bug reports welcome.
  11. __all__ = (
  12. 'Mock',
  13. 'MagicMock',
  14. 'patch',
  15. 'sentinel',
  16. 'DEFAULT',
  17. 'ANY',
  18. 'call',
  19. 'create_autospec',
  20. 'FILTER_DIR',
  21. 'NonCallableMock',
  22. 'NonCallableMagicMock',
  23. 'mock_open',
  24. 'PropertyMock',
  25. )
  26. __version__ = '1.0.1'
  27. import pprint
  28. import sys
  29. try:
  30. import inspect
  31. except ImportError:
  32. # for alternative platforms that
  33. # may not have inspect
  34. inspect = None
  35. try:
  36. from functools import wraps as original_wraps
  37. except ImportError:
  38. # Python 2.4 compatibility
  39. def wraps(original):
  40. def inner(f):
  41. f.__name__ = original.__name__
  42. f.__doc__ = original.__doc__
  43. f.__module__ = original.__module__
  44. f.__wrapped__ = original
  45. return f
  46. return inner
  47. else:
  48. if sys.version_info[:2] >= (3, 3):
  49. wraps = original_wraps
  50. else:
  51. def wraps(func):
  52. def inner(f):
  53. f = original_wraps(func)(f)
  54. f.__wrapped__ = func
  55. return f
  56. return inner
  57. try:
  58. unicode
  59. except NameError:
  60. # Python 3
  61. basestring = unicode = str
  62. try:
  63. long
  64. except NameError:
  65. # Python 3
  66. long = int
  67. try:
  68. BaseException
  69. except NameError:
  70. # Python 2.4 compatibility
  71. BaseException = Exception
  72. try:
  73. next
  74. except NameError:
  75. def next(obj):
  76. return obj.next()
  77. BaseExceptions = (BaseException,)
  78. if 'java' in sys.platform:
  79. # jython
  80. import java
  81. BaseExceptions = (BaseException, java.lang.Throwable)
  82. try:
  83. _isidentifier = str.isidentifier
  84. except AttributeError:
  85. # Python 2.X
  86. import keyword
  87. import re
  88. regex = re.compile(r'^[a-z_][a-z0-9_]*$', re.I)
  89. def _isidentifier(string):
  90. if string in keyword.kwlist:
  91. return False
  92. return regex.match(string)
  93. inPy3k = sys.version_info[0] == 3
  94. # Needed to work around Python 3 bug where use of "super" interferes with
  95. # defining __class__ as a descriptor
  96. _super = super
  97. self = 'im_self'
  98. builtin = '__builtin__'
  99. if inPy3k:
  100. self = '__self__'
  101. builtin = 'builtins'
  102. FILTER_DIR = True
  103. def _is_instance_mock(obj):
  104. # can't use isinstance on Mock objects because they override __class__
  105. # The base class for all mocks is NonCallableMock
  106. return issubclass(type(obj), NonCallableMock)
  107. def _is_exception(obj):
  108. return (
  109. isinstance(obj, BaseExceptions) or
  110. isinstance(obj, ClassTypes) and issubclass(obj, BaseExceptions)
  111. )
  112. class _slotted(object):
  113. __slots__ = ['a']
  114. DescriptorTypes = (
  115. type(_slotted.a),
  116. property,
  117. )
  118. def _getsignature(func, skipfirst, instance=False):
  119. if inspect is None:
  120. raise ImportError('inspect module not available')
  121. if isinstance(func, ClassTypes) and not instance:
  122. try:
  123. func = func.__init__
  124. except AttributeError:
  125. return
  126. skipfirst = True
  127. elif not isinstance(func, FunctionTypes):
  128. # for classes where instance is True we end up here too
  129. try:
  130. func = func.__call__
  131. except AttributeError:
  132. return
  133. if inPy3k:
  134. try:
  135. argspec = inspect.getfullargspec(func)
  136. except TypeError:
  137. # C function / method, possibly inherited object().__init__
  138. return
  139. regargs, varargs, varkw, defaults, kwonly, kwonlydef, ann = argspec
  140. else:
  141. try:
  142. regargs, varargs, varkwargs, defaults = inspect.getargspec(func)
  143. except TypeError:
  144. # C function / method, possibly inherited object().__init__
  145. return
  146. # instance methods and classmethods need to lose the self argument
  147. if getattr(func, self, None) is not None:
  148. regargs = regargs[1:]
  149. if skipfirst:
  150. # this condition and the above one are never both True - why?
  151. regargs = regargs[1:]
  152. if inPy3k:
  153. signature = inspect.formatargspec(
  154. regargs, varargs, varkw, defaults,
  155. kwonly, kwonlydef, ann, formatvalue=lambda value: "")
  156. else:
  157. signature = inspect.formatargspec(
  158. regargs, varargs, varkwargs, defaults,
  159. formatvalue=lambda value: "")
  160. return signature[1:-1], func
  161. def _check_signature(func, mock, skipfirst, instance=False):
  162. if not _callable(func):
  163. return
  164. result = _getsignature(func, skipfirst, instance)
  165. if result is None:
  166. return
  167. signature, func = result
  168. # can't use self because "self" is common as an argument name
  169. # unfortunately even not in the first place
  170. src = "lambda _mock_self, %s: None" % signature
  171. checksig = eval(src, {})
  172. _copy_func_details(func, checksig)
  173. type(mock)._mock_check_sig = checksig
  174. def _copy_func_details(func, funcopy):
  175. funcopy.__name__ = func.__name__
  176. funcopy.__doc__ = func.__doc__
  177. #funcopy.__dict__.update(func.__dict__)
  178. funcopy.__module__ = func.__module__
  179. if not inPy3k:
  180. funcopy.func_defaults = func.func_defaults
  181. return
  182. funcopy.__defaults__ = func.__defaults__
  183. funcopy.__kwdefaults__ = func.__kwdefaults__
  184. def _callable(obj):
  185. if isinstance(obj, ClassTypes):
  186. return True
  187. if getattr(obj, '__call__', None) is not None:
  188. return True
  189. return False
  190. def _is_list(obj):
  191. # checks for list or tuples
  192. # XXXX badly named!
  193. return type(obj) in (list, tuple)
  194. def _instance_callable(obj):
  195. """Given an object, return True if the object is callable.
  196. For classes, return True if instances would be callable."""
  197. if not isinstance(obj, ClassTypes):
  198. # already an instance
  199. return getattr(obj, '__call__', None) is not None
  200. klass = obj
  201. # uses __bases__ instead of __mro__ so that we work with old style classes
  202. if klass.__dict__.get('__call__') is not None:
  203. return True
  204. for base in klass.__bases__:
  205. if _instance_callable(base):
  206. return True
  207. return False
  208. def _set_signature(mock, original, instance=False):
  209. # creates a function with signature (*args, **kwargs) that delegates to a
  210. # mock. It still does signature checking by calling a lambda with the same
  211. # signature as the original.
  212. if not _callable(original):
  213. return
  214. skipfirst = isinstance(original, ClassTypes)
  215. result = _getsignature(original, skipfirst, instance)
  216. if result is None:
  217. # was a C function (e.g. object().__init__ ) that can't be mocked
  218. return
  219. signature, func = result
  220. src = "lambda %s: None" % signature
  221. checksig = eval(src, {})
  222. _copy_func_details(func, checksig)
  223. name = original.__name__
  224. if not _isidentifier(name):
  225. name = 'funcopy'
  226. context = {'_checksig_': checksig, 'mock': mock}
  227. src = """def %s(*args, **kwargs):
  228. _checksig_(*args, **kwargs)
  229. return mock(*args, **kwargs)""" % name
  230. exec (src, context)
  231. funcopy = context[name]
  232. _setup_func(funcopy, mock)
  233. return funcopy
  234. def _setup_func(funcopy, mock):
  235. funcopy.mock = mock
  236. # can't use isinstance with mocks
  237. if not _is_instance_mock(mock):
  238. return
  239. def assert_called_with(*args, **kwargs):
  240. return mock.assert_called_with(*args, **kwargs)
  241. def assert_called_once_with(*args, **kwargs):
  242. return mock.assert_called_once_with(*args, **kwargs)
  243. def assert_has_calls(*args, **kwargs):
  244. return mock.assert_has_calls(*args, **kwargs)
  245. def assert_any_call(*args, **kwargs):
  246. return mock.assert_any_call(*args, **kwargs)
  247. def reset_mock():
  248. funcopy.method_calls = _CallList()
  249. funcopy.mock_calls = _CallList()
  250. mock.reset_mock()
  251. ret = funcopy.return_value
  252. if _is_instance_mock(ret) and not ret is mock:
  253. ret.reset_mock()
  254. funcopy.called = False
  255. funcopy.call_count = 0
  256. funcopy.call_args = None
  257. funcopy.call_args_list = _CallList()
  258. funcopy.method_calls = _CallList()
  259. funcopy.mock_calls = _CallList()
  260. funcopy.return_value = mock.return_value
  261. funcopy.side_effect = mock.side_effect
  262. funcopy._mock_children = mock._mock_children
  263. funcopy.assert_called_with = assert_called_with
  264. funcopy.assert_called_once_with = assert_called_once_with
  265. funcopy.assert_has_calls = assert_has_calls
  266. funcopy.assert_any_call = assert_any_call
  267. funcopy.reset_mock = reset_mock
  268. mock._mock_delegate = funcopy
  269. def _is_magic(name):
  270. return '__%s__' % name[2:-2] == name
  271. class _SentinelObject(object):
  272. "A unique, named, sentinel object."
  273. def __init__(self, name):
  274. self.name = name
  275. def __repr__(self):
  276. return 'sentinel.%s' % self.name
  277. class _Sentinel(object):
  278. """Access attributes to return a named object, usable as a sentinel."""
  279. def __init__(self):
  280. self._sentinels = {}
  281. def __getattr__(self, name):
  282. if name == '__bases__':
  283. # Without this help(mock) raises an exception
  284. raise AttributeError
  285. return self._sentinels.setdefault(name, _SentinelObject(name))
  286. sentinel = _Sentinel()
  287. DEFAULT = sentinel.DEFAULT
  288. _missing = sentinel.MISSING
  289. _deleted = sentinel.DELETED
  290. class OldStyleClass:
  291. pass
  292. ClassType = type(OldStyleClass)
  293. def _copy(value):
  294. if type(value) in (dict, list, tuple, set):
  295. return type(value)(value)
  296. return value
  297. ClassTypes = (type,)
  298. if not inPy3k:
  299. ClassTypes = (type, ClassType)
  300. _allowed_names = set(
  301. [
  302. 'return_value', '_mock_return_value', 'side_effect',
  303. '_mock_side_effect', '_mock_parent', '_mock_new_parent',
  304. '_mock_name', '_mock_new_name'
  305. ]
  306. )
  307. def _delegating_property(name):
  308. _allowed_names.add(name)
  309. _the_name = '_mock_' + name
  310. def _get(self, name=name, _the_name=_the_name):
  311. sig = self._mock_delegate
  312. if sig is None:
  313. return getattr(self, _the_name)
  314. return getattr(sig, name)
  315. def _set(self, value, name=name, _the_name=_the_name):
  316. sig = self._mock_delegate
  317. if sig is None:
  318. self.__dict__[_the_name] = value
  319. else:
  320. setattr(sig, name, value)
  321. return property(_get, _set)
  322. class _CallList(list):
  323. def __contains__(self, value):
  324. if not isinstance(value, list):
  325. return list.__contains__(self, value)
  326. len_value = len(value)
  327. len_self = len(self)
  328. if len_value > len_self:
  329. return False
  330. for i in range(0, len_self - len_value + 1):
  331. sub_list = self[i:i+len_value]
  332. if sub_list == value:
  333. return True
  334. return False
  335. def __repr__(self):
  336. return pprint.pformat(list(self))
  337. def _check_and_set_parent(parent, value, name, new_name):
  338. if not _is_instance_mock(value):
  339. return False
  340. if ((value._mock_name or value._mock_new_name) or
  341. (value._mock_parent is not None) or
  342. (value._mock_new_parent is not None)):
  343. return False
  344. _parent = parent
  345. while _parent is not None:
  346. # setting a mock (value) as a child or return value of itself
  347. # should not modify the mock
  348. if _parent is value:
  349. return False
  350. _parent = _parent._mock_new_parent
  351. if new_name:
  352. value._mock_new_parent = parent
  353. value._mock_new_name = new_name
  354. if name:
  355. value._mock_parent = parent
  356. value._mock_name = name
  357. return True
  358. class Base(object):
  359. _mock_return_value = DEFAULT
  360. _mock_side_effect = None
  361. def __init__(self, *args, **kwargs):
  362. pass
  363. class NonCallableMock(Base):
  364. """A non-callable version of `Mock`"""
  365. def __new__(cls, *args, **kw):
  366. # every instance has its own class
  367. # so we can create magic methods on the
  368. # class without stomping on other mocks
  369. new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
  370. instance = object.__new__(new)
  371. return instance
  372. def __init__(
  373. self, spec=None, wraps=None, name=None, spec_set=None,
  374. parent=None, _spec_state=None, _new_name='', _new_parent=None,
  375. **kwargs
  376. ):
  377. if _new_parent is None:
  378. _new_parent = parent
  379. __dict__ = self.__dict__
  380. __dict__['_mock_parent'] = parent
  381. __dict__['_mock_name'] = name
  382. __dict__['_mock_new_name'] = _new_name
  383. __dict__['_mock_new_parent'] = _new_parent
  384. if spec_set is not None:
  385. spec = spec_set
  386. spec_set = True
  387. self._mock_add_spec(spec, spec_set)
  388. __dict__['_mock_children'] = {}
  389. __dict__['_mock_wraps'] = wraps
  390. __dict__['_mock_delegate'] = None
  391. __dict__['_mock_called'] = False
  392. __dict__['_mock_call_args'] = None
  393. __dict__['_mock_call_count'] = 0
  394. __dict__['_mock_call_args_list'] = _CallList()
  395. __dict__['_mock_mock_calls'] = _CallList()
  396. __dict__['method_calls'] = _CallList()
  397. if kwargs:
  398. self.configure_mock(**kwargs)
  399. _super(NonCallableMock, self).__init__(
  400. spec, wraps, name, spec_set, parent,
  401. _spec_state
  402. )
  403. def attach_mock(self, mock, attribute):
  404. """
  405. Attach a mock as an attribute of this one, replacing its name and
  406. parent. Calls to the attached mock will be recorded in the
  407. `method_calls` and `mock_calls` attributes of this one."""
  408. mock._mock_parent = None
  409. mock._mock_new_parent = None
  410. mock._mock_name = ''
  411. mock._mock_new_name = None
  412. setattr(self, attribute, mock)
  413. def mock_add_spec(self, spec, spec_set=False):
  414. """Add a spec to a mock. `spec` can either be an object or a
  415. list of strings. Only attributes on the `spec` can be fetched as
  416. attributes from the mock.
  417. If `spec_set` is True then only attributes on the spec can be set."""
  418. self._mock_add_spec(spec, spec_set)
  419. def _mock_add_spec(self, spec, spec_set):
  420. _spec_class = None
  421. if spec is not None and not _is_list(spec):
  422. if isinstance(spec, ClassTypes):
  423. _spec_class = spec
  424. else:
  425. _spec_class = _get_class(spec)
  426. spec = dir(spec)
  427. __dict__ = self.__dict__
  428. __dict__['_spec_class'] = _spec_class
  429. __dict__['_spec_set'] = spec_set
  430. __dict__['_mock_methods'] = spec
  431. def __get_return_value(self):
  432. ret = self._mock_return_value
  433. if self._mock_delegate is not None:
  434. ret = self._mock_delegate.return_value
  435. if ret is DEFAULT:
  436. ret = self._get_child_mock(
  437. _new_parent=self, _new_name='()'
  438. )
  439. self.return_value = ret
  440. return ret
  441. def __set_return_value(self, value):
  442. if self._mock_delegate is not None:
  443. self._mock_delegate.return_value = value
  444. else:
  445. self._mock_return_value = value
  446. _check_and_set_parent(self, value, None, '()')
  447. __return_value_doc = "The value to be returned when the mock is called."
  448. return_value = property(__get_return_value, __set_return_value,
  449. __return_value_doc)
  450. @property
  451. def __class__(self):
  452. if self._spec_class is None:
  453. return type(self)
  454. return self._spec_class
  455. called = _delegating_property('called')
  456. call_count = _delegating_property('call_count')
  457. call_args = _delegating_property('call_args')
  458. call_args_list = _delegating_property('call_args_list')
  459. mock_calls = _delegating_property('mock_calls')
  460. def __get_side_effect(self):
  461. sig = self._mock_delegate
  462. if sig is None:
  463. return self._mock_side_effect
  464. return sig.side_effect
  465. def __set_side_effect(self, value):
  466. value = _try_iter(value)
  467. sig = self._mock_delegate
  468. if sig is None:
  469. self._mock_side_effect = value
  470. else:
  471. sig.side_effect = value
  472. side_effect = property(__get_side_effect, __set_side_effect)
  473. def reset_mock(self):
  474. "Restore the mock object to its initial state."
  475. self.called = False
  476. self.call_args = None
  477. self.call_count = 0
  478. self.mock_calls = _CallList()
  479. self.call_args_list = _CallList()
  480. self.method_calls = _CallList()
  481. for child in self._mock_children.values():
  482. if isinstance(child, _SpecState):
  483. continue
  484. child.reset_mock()
  485. ret = self._mock_return_value
  486. if _is_instance_mock(ret) and ret is not self:
  487. ret.reset_mock()
  488. def configure_mock(self, **kwargs):
  489. """Set attributes on the mock through keyword arguments.
  490. Attributes plus return values and side effects can be set on child
  491. mocks using standard dot notation and unpacking a dictionary in the
  492. method call:
  493. >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
  494. >>> mock.configure_mock(**attrs)"""
  495. for arg, val in sorted(kwargs.items(),
  496. # we sort on the number of dots so that
  497. # attributes are set before we set attributes on
  498. # attributes
  499. key=lambda entry: entry[0].count('.')):
  500. args = arg.split('.')
  501. final = args.pop()
  502. obj = self
  503. for entry in args:
  504. obj = getattr(obj, entry)
  505. setattr(obj, final, val)
  506. def __getattr__(self, name):
  507. if name == '_mock_methods':
  508. raise AttributeError(name)
  509. elif self._mock_methods is not None:
  510. if name not in self._mock_methods or name in _all_magics:
  511. raise AttributeError("Mock object has no attribute %r" % name)
  512. elif _is_magic(name):
  513. raise AttributeError(name)
  514. result = self._mock_children.get(name)
  515. if result is _deleted:
  516. raise AttributeError(name)
  517. elif result is None:
  518. wraps = None
  519. if self._mock_wraps is not None:
  520. # XXXX should we get the attribute without triggering code
  521. # execution?
  522. wraps = getattr(self._mock_wraps, name)
  523. result = self._get_child_mock(
  524. parent=self, name=name, wraps=wraps, _new_name=name,
  525. _new_parent=self
  526. )
  527. self._mock_children[name] = result
  528. elif isinstance(result, _SpecState):
  529. result = create_autospec(
  530. result.spec, result.spec_set, result.instance,
  531. result.parent, result.name
  532. )
  533. self._mock_children[name] = result
  534. return result
  535. def __repr__(self):
  536. _name_list = [self._mock_new_name]
  537. _parent = self._mock_new_parent
  538. last = self
  539. dot = '.'
  540. if _name_list == ['()']:
  541. dot = ''
  542. seen = set()
  543. while _parent is not None:
  544. last = _parent
  545. _name_list.append(_parent._mock_new_name + dot)
  546. dot = '.'
  547. if _parent._mock_new_name == '()':
  548. dot = ''
  549. _parent = _parent._mock_new_parent
  550. # use ids here so as not to call __hash__ on the mocks
  551. if id(_parent) in seen:
  552. break
  553. seen.add(id(_parent))
  554. _name_list = list(reversed(_name_list))
  555. _first = last._mock_name or 'mock'
  556. if len(_name_list) > 1:
  557. if _name_list[1] not in ('()', '().'):
  558. _first += '.'
  559. _name_list[0] = _first
  560. name = ''.join(_name_list)
  561. name_string = ''
  562. if name not in ('mock', 'mock.'):
  563. name_string = ' name=%r' % name
  564. spec_string = ''
  565. if self._spec_class is not None:
  566. spec_string = ' spec=%r'
  567. if self._spec_set:
  568. spec_string = ' spec_set=%r'
  569. spec_string = spec_string % self._spec_class.__name__
  570. return "<%s%s%s id='%s'>" % (
  571. type(self).__name__,
  572. name_string,
  573. spec_string,
  574. id(self)
  575. )
  576. def __dir__(self):
  577. """Filter the output of `dir(mock)` to only useful members.
  578. XXXX
  579. """
  580. extras = self._mock_methods or []
  581. from_type = dir(type(self))
  582. from_dict = list(self.__dict__)
  583. if FILTER_DIR:
  584. from_type = [e for e in from_type if not e.startswith('_')]
  585. from_dict = [e for e in from_dict if not e.startswith('_') or
  586. _is_magic(e)]
  587. return sorted(set(extras + from_type + from_dict +
  588. list(self._mock_children)))
  589. def __setattr__(self, name, value):
  590. if name in _allowed_names:
  591. # property setters go through here
  592. return object.__setattr__(self, name, value)
  593. elif (self._spec_set and self._mock_methods is not None and
  594. name not in self._mock_methods and
  595. name not in self.__dict__):
  596. raise AttributeError("Mock object has no attribute '%s'" % name)
  597. elif name in _unsupported_magics:
  598. msg = 'Attempting to set unsupported magic method %r.' % name
  599. raise AttributeError(msg)
  600. elif name in _all_magics:
  601. if self._mock_methods is not None and name not in self._mock_methods:
  602. raise AttributeError("Mock object has no attribute '%s'" % name)
  603. if not _is_instance_mock(value):
  604. setattr(type(self), name, _get_method(name, value))
  605. original = value
  606. value = lambda *args, **kw: original(self, *args, **kw)
  607. else:
  608. # only set _new_name and not name so that mock_calls is tracked
  609. # but not method calls
  610. _check_and_set_parent(self, value, None, name)
  611. setattr(type(self), name, value)
  612. self._mock_children[name] = value
  613. elif name == '__class__':
  614. self._spec_class = value
  615. return
  616. else:
  617. if _check_and_set_parent(self, value, name, name):
  618. self._mock_children[name] = value
  619. return object.__setattr__(self, name, value)
  620. def __delattr__(self, name):
  621. if name in _all_magics and name in type(self).__dict__:
  622. delattr(type(self), name)
  623. if name not in self.__dict__:
  624. # for magic methods that are still MagicProxy objects and
  625. # not set on the instance itself
  626. return
  627. if name in self.__dict__:
  628. object.__delattr__(self, name)
  629. obj = self._mock_children.get(name, _missing)
  630. if obj is _deleted:
  631. raise AttributeError(name)
  632. if obj is not _missing:
  633. del self._mock_children[name]
  634. self._mock_children[name] = _deleted
  635. def _format_mock_call_signature(self, args, kwargs):
  636. name = self._mock_name or 'mock'
  637. return _format_call_signature(name, args, kwargs)
  638. def _format_mock_failure_message(self, args, kwargs):
  639. message = 'Expected call: %s\nActual call: %s'
  640. expected_string = self._format_mock_call_signature(args, kwargs)
  641. call_args = self.call_args
  642. if len(call_args) == 3:
  643. call_args = call_args[1:]
  644. actual_string = self._format_mock_call_signature(*call_args)
  645. return message % (expected_string, actual_string)
  646. def assert_called_with(_mock_self, *args, **kwargs):
  647. """assert that the mock was called with the specified arguments.
  648. Raises an AssertionError if the args and keyword args passed in are
  649. different to the last call to the mock."""
  650. self = _mock_self
  651. if self.call_args is None:
  652. expected = self._format_mock_call_signature(args, kwargs)
  653. raise AssertionError('Expected call: %s\nNot called' % (expected,))
  654. if self.call_args != (args, kwargs):
  655. msg = self._format_mock_failure_message(args, kwargs)
  656. raise AssertionError(msg)
  657. def assert_called_once_with(_mock_self, *args, **kwargs):
  658. """assert that the mock was called exactly once and with the specified
  659. arguments."""
  660. self = _mock_self
  661. if not self.call_count == 1:
  662. msg = ("Expected to be called once. Called %s times." %
  663. self.call_count)
  664. raise AssertionError(msg)
  665. return self.assert_called_with(*args, **kwargs)
  666. def assert_has_calls(self, calls, any_order=False):
  667. """assert the mock has been called with the specified calls.
  668. The `mock_calls` list is checked for the calls.
  669. If `any_order` is False (the default) then the calls must be
  670. sequential. There can be extra calls before or after the
  671. specified calls.
  672. If `any_order` is True then the calls can be in any order, but
  673. they must all appear in `mock_calls`."""
  674. if not any_order:
  675. if calls not in self.mock_calls:
  676. raise AssertionError(
  677. 'Calls not found.\nExpected: %r\n'
  678. 'Actual: %r' % (calls, self.mock_calls)
  679. )
  680. return
  681. all_calls = list(self.mock_calls)
  682. not_found = []
  683. for kall in calls:
  684. try:
  685. all_calls.remove(kall)
  686. except ValueError:
  687. not_found.append(kall)
  688. if not_found:
  689. raise AssertionError(
  690. '%r not all found in call list' % (tuple(not_found),)
  691. )
  692. def assert_any_call(self, *args, **kwargs):
  693. """assert the mock has been called with the specified arguments.
  694. The assert passes if the mock has *ever* been called, unlike
  695. `assert_called_with` and `assert_called_once_with` that only pass if
  696. the call is the most recent one."""
  697. kall = call(*args, **kwargs)
  698. if kall not in self.call_args_list:
  699. expected_string = self._format_mock_call_signature(args, kwargs)
  700. raise AssertionError(
  701. '%s call not found' % expected_string
  702. )
  703. def _get_child_mock(self, **kw):
  704. """Create the child mocks for attributes and return value.
  705. By default child mocks will be the same type as the parent.
  706. Subclasses of Mock may want to override this to customize the way
  707. child mocks are made.
  708. For non-callable mocks the callable variant will be used (rather than
  709. any custom subclass)."""
  710. _type = type(self)
  711. if not issubclass(_type, CallableMixin):
  712. if issubclass(_type, NonCallableMagicMock):
  713. klass = MagicMock
  714. elif issubclass(_type, NonCallableMock) :
  715. klass = Mock
  716. else:
  717. klass = _type.__mro__[1]
  718. return klass(**kw)
  719. def _try_iter(obj):
  720. if obj is None:
  721. return obj
  722. if _is_exception(obj):
  723. return obj
  724. if _callable(obj):
  725. return obj
  726. try:
  727. return iter(obj)
  728. except TypeError:
  729. # XXXX backwards compatibility
  730. # but this will blow up on first call - so maybe we should fail early?
  731. return obj
  732. class CallableMixin(Base):
  733. def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
  734. wraps=None, name=None, spec_set=None, parent=None,
  735. _spec_state=None, _new_name='', _new_parent=None, **kwargs):
  736. self.__dict__['_mock_return_value'] = return_value
  737. _super(CallableMixin, self).__init__(
  738. spec, wraps, name, spec_set, parent,
  739. _spec_state, _new_name, _new_parent, **kwargs
  740. )
  741. self.side_effect = side_effect
  742. def _mock_check_sig(self, *args, **kwargs):
  743. # stub method that can be replaced with one with a specific signature
  744. pass
  745. def __call__(_mock_self, *args, **kwargs):
  746. # can't use self in-case a function / method we are mocking uses self
  747. # in the signature
  748. _mock_self._mock_check_sig(*args, **kwargs)
  749. return _mock_self._mock_call(*args, **kwargs)
  750. def _mock_call(_mock_self, *args, **kwargs):
  751. self = _mock_self
  752. self.called = True
  753. self.call_count += 1
  754. self.call_args = _Call((args, kwargs), two=True)
  755. self.call_args_list.append(_Call((args, kwargs), two=True))
  756. _new_name = self._mock_new_name
  757. _new_parent = self._mock_new_parent
  758. self.mock_calls.append(_Call(('', args, kwargs)))
  759. seen = set()
  760. skip_next_dot = _new_name == '()'
  761. do_method_calls = self._mock_parent is not None
  762. name = self._mock_name
  763. while _new_parent is not None:
  764. this_mock_call = _Call((_new_name, args, kwargs))
  765. if _new_parent._mock_new_name:
  766. dot = '.'
  767. if skip_next_dot:
  768. dot = ''
  769. skip_next_dot = False
  770. if _new_parent._mock_new_name == '()':
  771. skip_next_dot = True
  772. _new_name = _new_parent._mock_new_name + dot + _new_name
  773. if do_method_calls:
  774. if _new_name == name:
  775. this_method_call = this_mock_call
  776. else:
  777. this_method_call = _Call((name, args, kwargs))
  778. _new_parent.method_calls.append(this_method_call)
  779. do_method_calls = _new_parent._mock_parent is not None
  780. if do_method_calls:
  781. name = _new_parent._mock_name + '.' + name
  782. _new_parent.mock_calls.append(this_mock_call)
  783. _new_parent = _new_parent._mock_new_parent
  784. # use ids here so as not to call __hash__ on the mocks
  785. _new_parent_id = id(_new_parent)
  786. if _new_parent_id in seen:
  787. break
  788. seen.add(_new_parent_id)
  789. ret_val = DEFAULT
  790. effect = self.side_effect
  791. if effect is not None:
  792. if _is_exception(effect):
  793. raise effect
  794. if not _callable(effect):
  795. result = next(effect)
  796. if _is_exception(result):
  797. raise result
  798. return result
  799. ret_val = effect(*args, **kwargs)
  800. if ret_val is DEFAULT:
  801. ret_val = self.return_value
  802. if (self._mock_wraps is not None and
  803. self._mock_return_value is DEFAULT):
  804. return self._mock_wraps(*args, **kwargs)
  805. if ret_val is DEFAULT:
  806. ret_val = self.return_value
  807. return ret_val
  808. class Mock(CallableMixin, NonCallableMock):
  809. """
  810. Create a new `Mock` object. `Mock` takes several optional arguments
  811. that specify the behaviour of the Mock object:
  812. * `spec`: This can be either a list of strings or an existing object (a
  813. class or instance) that acts as the specification for the mock object. If
  814. you pass in an object then a list of strings is formed by calling dir on
  815. the object (excluding unsupported magic attributes and methods). Accessing
  816. any attribute not in this list will raise an `AttributeError`.
  817. If `spec` is an object (rather than a list of strings) then
  818. `mock.__class__` returns the class of the spec object. This allows mocks
  819. to pass `isinstance` tests.
  820. * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
  821. or get an attribute on the mock that isn't on the object passed as
  822. `spec_set` will raise an `AttributeError`.
  823. * `side_effect`: A function to be called whenever the Mock is called. See
  824. the `side_effect` attribute. Useful for raising exceptions or
  825. dynamically changing return values. The function is called with the same
  826. arguments as the mock, and unless it returns `DEFAULT`, the return
  827. value of this function is used as the return value.
  828. Alternatively `side_effect` can be an exception class or instance. In
  829. this case the exception will be raised when the mock is called.
  830. If `side_effect` is an iterable then each call to the mock will return
  831. the next value from the iterable. If any of the members of the iterable
  832. are exceptions they will be raised instead of returned.
  833. * `return_value`: The value returned when the mock is called. By default
  834. this is a new Mock (created on first access). See the
  835. `return_value` attribute.
  836. * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
  837. calling the Mock will pass the call through to the wrapped object
  838. (returning the real result). Attribute access on the mock will return a
  839. Mock object that wraps the corresponding attribute of the wrapped object
  840. (so attempting to access an attribute that doesn't exist will raise an
  841. `AttributeError`).
  842. If the mock has an explicit `return_value` set then calls are not passed
  843. to the wrapped object and the `return_value` is returned instead.
  844. * `name`: If the mock has a name then it will be used in the repr of the
  845. mock. This can be useful for debugging. The name is propagated to child
  846. mocks.
  847. Mocks can also be called with arbitrary keyword arguments. These will be
  848. used to set attributes on the mock after it is created.
  849. """
  850. def _dot_lookup(thing, comp, import_path):
  851. try:
  852. return getattr(thing, comp)
  853. except AttributeError:
  854. __import__(import_path)
  855. return getattr(thing, comp)
  856. def _importer(target):
  857. components = target.split('.')
  858. import_path = components.pop(0)
  859. thing = __import__(import_path)
  860. for comp in components:
  861. import_path += ".%s" % comp
  862. thing = _dot_lookup(thing, comp, import_path)
  863. return thing
  864. def _is_started(patcher):
  865. # XXXX horrible
  866. return hasattr(patcher, 'is_local')
  867. class _patch(object):
  868. attribute_name = None
  869. _active_patches = set()
  870. def __init__(
  871. self, getter, attribute, new, spec, create,
  872. spec_set, autospec, new_callable, kwargs
  873. ):
  874. if new_callable is not None:
  875. if new is not DEFAULT:
  876. raise ValueError(
  877. "Cannot use 'new' and 'new_callable' together"
  878. )
  879. if autospec is not None:
  880. raise ValueError(
  881. "Cannot use 'autospec' and 'new_callable' together"
  882. )
  883. self.getter = getter
  884. self.attribute = attribute
  885. self.new = new
  886. self.new_callable = new_callable
  887. self.spec = spec
  888. self.create = create
  889. self.has_local = False
  890. self.spec_set = spec_set
  891. self.autospec = autospec
  892. self.kwargs = kwargs
  893. self.additional_patchers = []
  894. def copy(self):
  895. patcher = _patch(
  896. self.getter, self.attribute, self.new, self.spec,
  897. self.create, self.spec_set,
  898. self.autospec, self.new_callable, self.kwargs
  899. )
  900. patcher.attribute_name = self.attribute_name
  901. patcher.additional_patchers = [
  902. p.copy() for p in self.additional_patchers
  903. ]
  904. return patcher
  905. def __call__(self, func):
  906. if isinstance(func, ClassTypes):
  907. return self.decorate_class(func)
  908. return self.decorate_callable(func)
  909. def decorate_class(self, klass):
  910. for attr in dir(klass):
  911. if not attr.startswith(patch.TEST_PREFIX):
  912. continue
  913. attr_value = getattr(klass, attr)
  914. if not hasattr(attr_value, "__call__"):
  915. continue
  916. patcher = self.copy()
  917. setattr(klass, attr, patcher(attr_value))
  918. return klass
  919. def decorate_callable(self, func):
  920. if hasattr(func, 'patchings'):
  921. func.patchings.append(self)
  922. return func
  923. @wraps(func)
  924. def patched(*args, **keywargs):
  925. # don't use a with here (backwards compatability with Python 2.4)
  926. extra_args = []
  927. entered_patchers = []
  928. # can't use try...except...finally because of Python 2.4
  929. # compatibility
  930. exc_info = tuple()
  931. try:
  932. try:
  933. for patching in patched.patchings:
  934. arg = patching.__enter__()
  935. entered_patchers.append(patching)
  936. if patching.attribute_name is not None:
  937. keywargs.update(arg)
  938. elif patching.new is DEFAULT:
  939. extra_args.append(arg)
  940. args += tuple(extra_args)
  941. return func(*args, **keywargs)
  942. except:
  943. if (patching not in entered_patchers and
  944. _is_started(patching)):
  945. # the patcher may have been started, but an exception
  946. # raised whilst entering one of its additional_patchers
  947. entered_patchers.append(patching)
  948. # Pass the exception to __exit__
  949. exc_info = sys.exc_info()
  950. # re-raise the exception
  951. raise
  952. finally:
  953. for patching in reversed(entered_patchers):
  954. patching.__exit__(*exc_info)
  955. patched.patchings = [self]
  956. if hasattr(func, 'func_code'):
  957. # not in Python 3
  958. patched.compat_co_firstlineno = getattr(
  959. func, "compat_co_firstlineno",
  960. func.func_code.co_firstlineno
  961. )
  962. return patched
  963. def get_original(self):
  964. target = self.getter()
  965. name = self.attribute
  966. original = DEFAULT
  967. local = False
  968. try:
  969. original = target.__dict__[name]
  970. except (AttributeError, KeyError):
  971. original = getattr(target, name, DEFAULT)
  972. else:
  973. local = True
  974. if not self.create and original is DEFAULT:
  975. raise AttributeError(
  976. "%s does not have the attribute %r" % (target, name)
  977. )
  978. return original, local
  979. def __enter__(self):
  980. """Perform the patch."""
  981. new, spec, spec_set = self.new, self.spec, self.spec_set
  982. autospec, kwargs = self.autospec, self.kwargs
  983. new_callable = self.new_callable
  984. self.target = self.getter()
  985. # normalise False to None
  986. if spec is False:
  987. spec = None
  988. if spec_set is False:
  989. spec_set = None
  990. if autospec is False:
  991. autospec = None
  992. if spec is not None and autospec is not None:
  993. raise TypeError("Can't specify spec and autospec")
  994. if ((spec is not None or autospec is not None) and
  995. spec_set not in (True, None)):
  996. raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
  997. original, local = self.get_original()
  998. if new is DEFAULT and autospec is None:
  999. inherit = False
  1000. if spec is True:
  1001. # set spec to the object we are replacing
  1002. spec = original
  1003. if spec_set is True:
  1004. spec_set = original
  1005. spec = None
  1006. elif spec is not None:
  1007. if spec_set is True:
  1008. spec_set = spec
  1009. spec = None
  1010. elif spec_set is True:
  1011. spec_set = original
  1012. if spec is not None or spec_set is not None:
  1013. if original is DEFAULT:
  1014. raise TypeError("Can't use 'spec' with create=True")
  1015. if isinstance(original, ClassTypes):
  1016. # If we're patching out a class and there is a spec
  1017. inherit = True
  1018. Klass = MagicMock
  1019. _kwargs = {}
  1020. if new_callable is not None:
  1021. Klass = new_callable
  1022. elif spec is not None or spec_set is not None:
  1023. this_spec = spec
  1024. if spec_set is not None:
  1025. this_spec = spec_set
  1026. if _is_list(this_spec):
  1027. not_callable = '__call__' not in this_spec
  1028. else:
  1029. not_callable = not _callable(this_spec)
  1030. if not_callable:
  1031. Klass = NonCallableMagicMock
  1032. if spec is not None:
  1033. _kwargs['spec'] = spec
  1034. if spec_set is not None:
  1035. _kwargs['spec_set'] = spec_set
  1036. # add a name to mocks
  1037. if (isinstance(Klass, type) and
  1038. issubclass(Klass, NonCallableMock) and self.attribute):
  1039. _kwargs['name'] = self.attribute
  1040. _kwargs.update(kwargs)
  1041. new = Klass(**_kwargs)
  1042. if inherit and _is_instance_mock(new):
  1043. # we can only tell if the instance should be callable if the
  1044. # spec is not a list
  1045. this_spec = spec
  1046. if spec_set is not None:
  1047. this_spec = spec_set
  1048. if (not _is_list(this_spec) and not
  1049. _instance_callable(this_spec)):
  1050. Klass = NonCallableMagicMock
  1051. _kwargs.pop('name')
  1052. new.return_value = Klass(_new_parent=new, _new_name='()',
  1053. **_kwargs)
  1054. elif autospec is not None:
  1055. # spec is ignored, new *must* be default, spec_set is treated
  1056. # as a boolean. Should we check spec is not None and that spec_set
  1057. # is a bool?
  1058. if new is not DEFAULT:
  1059. raise TypeError(
  1060. "autospec creates the mock for you. Can't specify "
  1061. "autospec and new."
  1062. )
  1063. if original is DEFAULT:
  1064. raise TypeError("Can't use 'autospec' with create=True")
  1065. spec_set = bool(spec_set)
  1066. if autospec is True:
  1067. autospec = original
  1068. new = create_autospec(autospec, spec_set=spec_set,
  1069. _name=self.attribute, **kwargs)
  1070. elif kwargs:
  1071. # can't set keyword args when we aren't creating the mock
  1072. # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
  1073. raise TypeError("Can't pass kwargs to a mock we aren't creating")
  1074. new_attr = new
  1075. self.temp_original = original
  1076. self.is_local = local
  1077. setattr(self.target, self.attribute, new_attr)
  1078. if self.attribute_name is not None:
  1079. extra_args = {}
  1080. if self.new is DEFAULT:
  1081. extra_args[self.attribute_name] = new
  1082. for patching in self.additional_patchers:
  1083. arg = patching.__enter__()
  1084. if patching.new is DEFAULT:
  1085. extra_args.update(arg)
  1086. return extra_args
  1087. return new
  1088. def __exit__(self, *exc_info):
  1089. """Undo the patch."""
  1090. if not _is_started(self):
  1091. raise RuntimeError('stop called on unstarted patcher')
  1092. if self.is_local and self.temp_original is not DEFAULT:
  1093. setattr(self.target, self.attribute, self.temp_original)
  1094. else:
  1095. delattr(self.target, self.attribute)
  1096. if not self.create and not hasattr(self.target, self.attribute):
  1097. # needed for proxy objects like django settings
  1098. setattr(self.target, self.attribute, self.temp_original)
  1099. del self.temp_original
  1100. del self.is_local
  1101. del self.target
  1102. for patcher in reversed(self.additional_patchers):
  1103. if _is_started(patcher):
  1104. patcher.__exit__(*exc_info)
  1105. def start(self):
  1106. """Activate a patch, returning any created mock."""
  1107. result = self.__enter__()
  1108. self._active_patches.add(self)
  1109. return result
  1110. def stop(self):
  1111. """Stop an active patch."""
  1112. self._active_patches.discard(self)
  1113. return self.__exit__()
  1114. def _get_target(target):
  1115. try:
  1116. target, attribute = target.rsplit('.', 1)
  1117. except (TypeError, ValueError):
  1118. raise TypeError("Need a valid target to patch. You supplied: %r" %
  1119. (target,))
  1120. getter = lambda: _importer(target)
  1121. return getter, attribute
  1122. def _patch_object(
  1123. target, attribute, new=DEFAULT, spec=None,
  1124. create=False, spec_set=None, autospec=None,
  1125. new_callable=None, **kwargs
  1126. ):
  1127. """
  1128. patch.object(target, attribute, new=DEFAULT, spec=None, create=False,
  1129. spec_set=None, autospec=None, new_callable=None, **kwargs)
  1130. patch the named member (`attribute`) on an object (`target`) with a mock
  1131. object.
  1132. `patch.object` can be used as a decorator, class decorator or a context
  1133. manager. Arguments `new`, `spec`, `create`, `spec_set`,
  1134. `autospec` and `new_callable` have the same meaning as for `patch`. Like
  1135. `patch`, `patch.object` takes arbitrary keyword arguments for configuring
  1136. the mock object it creates.
  1137. When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
  1138. for choosing which methods to wrap.
  1139. """
  1140. getter = lambda: target
  1141. return _patch(
  1142. getter, attribute, new, spec, create,
  1143. spec_set, autospec, new_callable, kwargs
  1144. )
  1145. def _patch_multiple(target, spec=None, create=False, spec_set=None,
  1146. autospec=None, new_callable=None, **kwargs):
  1147. """Perform multiple patches in a single call. It takes the object to be
  1148. patched (either as an object or a string to fetch the object by importing)
  1149. and keyword arguments for the patches::
  1150. with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
  1151. ...
  1152. Use `DEFAULT` as the value if you want `patch.multiple` to create
  1153. mocks for you. In this case the created mocks are passed into a decorated
  1154. function by keyword, and a dictionary is returned when `patch.multiple` is
  1155. used as a context manager.
  1156. `patch.multiple` can be used as a decorator, class decorator or a context
  1157. manager. The arguments `spec`, `spec_set`, `create`,
  1158. `autospec` and `new_callable` have the same meaning as for `patch`. These
  1159. arguments will be applied to *all* patches done by `patch.multiple`.
  1160. When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
  1161. for choosing which methods to wrap.
  1162. """
  1163. if type(target) in (unicode, str):
  1164. getter = lambda: _importer(target)
  1165. else:
  1166. getter = lambda: target
  1167. if not kwargs:
  1168. raise ValueError(
  1169. 'Must supply at least one keyword argument with patch.multiple'
  1170. )
  1171. # need to wrap in a list for python 3, where items is a view
  1172. items = list(kwargs.items())
  1173. attribute, new = items[0]
  1174. patcher = _patch(
  1175. getter, attribute, new, spec, create, spec_set,
  1176. autospec, new_callable, {}
  1177. )
  1178. patcher.attribute_name = attribute
  1179. for attribute, new in items[1:]:
  1180. this_patcher = _patch(
  1181. getter, attribute, new, spec, create, spec_set,
  1182. autospec, new_callable, {}
  1183. )
  1184. this_patcher.attribute_name = attribute
  1185. patcher.additional_patchers.append(this_patcher)
  1186. return patcher
  1187. def patch(
  1188. target, new=DEFAULT, spec=None, create=False,
  1189. spec_set=None, autospec=None, new_callable=None, **kwargs
  1190. ):
  1191. """
  1192. `patch` acts as a function decorator, class decorator or a context
  1193. manager. Inside the body of the function or with statement, the `target`
  1194. is patched with a `new` object. When the function/with statement exits
  1195. the patch is undone.
  1196. If `new` is omitted, then the target is replaced with a
  1197. `MagicMock`. If `patch` is used as a decorator and `new` is
  1198. omitted, the created mock is passed in as an extra argument to the
  1199. decorated function. If `patch` is used as a context manager the created
  1200. mock is returned by the context manager.
  1201. `target` should be a string in the form `'package.module.ClassName'`. The
  1202. `target` is imported and the specified object replaced with the `new`
  1203. object, so the `target` must be importable from the environment you are
  1204. calling `patch` from. The target is imported when the decorated function
  1205. is executed, not at decoration time.
  1206. The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
  1207. if patch is creating one for you.
  1208. In addition you can pass `spec=True` or `spec_set=True`, which causes
  1209. patch to pass in the object being mocked as the spec/spec_set object.
  1210. `new_callable` allows you to specify a different class, or callable object,
  1211. that will be called to create the `new` object. By default `MagicMock` is
  1212. used.
  1213. A more powerful form of `spec` is `autospec`. If you set `autospec=True`
  1214. then the mock with be created with a spec from the object being replaced.
  1215. All attributes of the mock will also have the spec of the corresponding
  1216. attribute of the object being replaced. Methods and functions being
  1217. mocked will have their arguments checked and will raise a `TypeError` if
  1218. they are called with the wrong signature. For mocks replacing a class,
  1219. their return value (the 'instance') will have the same spec as the class.
  1220. Instead of `autospec=True` you can pass `autospec=some_object` to use an
  1221. arbitrary object as the spec instead of the one being replaced