mock.py 104 KB

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