mock.py 102 KB

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