mock.py 76 KB

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