mock.py 81 KB

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