mock.py 81 KB

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