PageRenderTime 118ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/mock.py

https://code.google.com/p/mock/
Python | 2054 lines | 1886 code | 70 blank | 98 comment | 95 complexity | e87cabe85a846e6a81918ecf0d36940f MD5 | raw file
Possible License(s): BSD-2-Clause

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

Large files files are truncated, but you can click here to view the full file