mock.py 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045
  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. def copy(self):
  1083. patcher = _patch(
  1084. self.getter, self.attribute, self.new, self.spec,
  1085. self.create, self.spec_set,
  1086. self.autospec, self.new_callable, self.kwargs
  1087. )
  1088. patcher.attribute_name = self.attribute_name
  1089. patcher.additional_patchers = [
  1090. p.copy() for p in self.additional_patchers
  1091. ]
  1092. return patcher
  1093. def __call__(self, func):
  1094. if isinstance(func, type):
  1095. return self.decorate_class(func)
  1096. if inspect.iscoroutinefunction(func):
  1097. return self.decorate_async_callable(func)
  1098. return self.decorate_callable(func)
  1099. def decorate_class(self, klass):
  1100. for attr in dir(klass):
  1101. if not attr.startswith(patch.TEST_PREFIX):
  1102. continue
  1103. attr_value = getattr(klass, attr)
  1104. if not hasattr(attr_value, "__call__"):
  1105. continue
  1106. patcher = self.copy()
  1107. setattr(klass, attr, patcher(attr_value))
  1108. return klass
  1109. @contextlib.contextmanager
  1110. def decoration_helper(self, patched, args, keywargs):
  1111. extra_args = []
  1112. with contextlib.ExitStack() as exit_stack:
  1113. for patching in patched.patchings:
  1114. arg = exit_stack.enter_context(patching)
  1115. if patching.attribute_name is not None:
  1116. keywargs.update(arg)
  1117. elif patching.new is DEFAULT:
  1118. extra_args.append(arg)
  1119. args += tuple(extra_args)
  1120. yield (args, keywargs)
  1121. def decorate_callable(self, func):
  1122. # NB. Keep the method in sync with decorate_async_callable()
  1123. if hasattr(func, 'patchings'):
  1124. func.patchings.append(self)
  1125. return func
  1126. @wraps(func)
  1127. def patched(*args, **keywargs):
  1128. with self.decoration_helper(patched,
  1129. args,
  1130. keywargs) as (newargs, newkeywargs):
  1131. return func(*newargs, **newkeywargs)
  1132. patched.patchings = [self]
  1133. return patched
  1134. def decorate_async_callable(self, func):
  1135. # NB. Keep the method in sync with decorate_callable()
  1136. if hasattr(func, 'patchings'):
  1137. func.patchings.append(self)
  1138. return func
  1139. @wraps(func)
  1140. async def patched(*args, **keywargs):
  1141. with self.decoration_helper(patched,
  1142. args,
  1143. keywargs) as (newargs, newkeywargs):
  1144. return await func(*newargs, **newkeywargs)
  1145. patched.patchings = [self]
  1146. return patched
  1147. def get_original(self):
  1148. target = self.getter()
  1149. name = self.attribute
  1150. original = DEFAULT
  1151. local = False
  1152. try:
  1153. original = target.__dict__[name]
  1154. except (AttributeError, KeyError):
  1155. original = getattr(target, name, DEFAULT)
  1156. else:
  1157. local = True
  1158. if name in _builtins and isinstance(target, ModuleType):
  1159. self.create = True
  1160. if not self.create and original is DEFAULT:
  1161. raise AttributeError(
  1162. "%s does not have the attribute %r" % (target, name)
  1163. )
  1164. return original, local
  1165. def __enter__(self):
  1166. """Perform the patch."""
  1167. new, spec, spec_set = self.new, self.spec, self.spec_set
  1168. autospec, kwargs = self.autospec, self.kwargs
  1169. new_callable = self.new_callable
  1170. self.target = self.getter()
  1171. # normalise False to None
  1172. if spec is False:
  1173. spec = None
  1174. if spec_set is False:
  1175. spec_set = None
  1176. if autospec is False:
  1177. autospec = None
  1178. if spec is not None and autospec is not None:
  1179. raise TypeError("Can't specify spec and autospec")
  1180. if ((spec is not None or autospec is not None) and
  1181. spec_set not in (True, None)):
  1182. raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
  1183. original, local = self.get_original()
  1184. if new is DEFAULT and autospec is None:
  1185. inherit = False
  1186. if spec is True:
  1187. # set spec to the object we are replacing
  1188. spec = original
  1189. if spec_set is True:
  1190. spec_set = original
  1191. spec = None
  1192. elif spec is not None:
  1193. if spec_set is True:
  1194. spec_set = spec
  1195. spec = None
  1196. elif spec_set is True:
  1197. spec_set = original
  1198. if spec is not None or spec_set is not None:
  1199. if original is DEFAULT:
  1200. raise TypeError("Can't use 'spec' with create=True")
  1201. if isinstance(original, type):
  1202. # If we're patching out a class and there is a spec
  1203. inherit = True
  1204. # Determine the Klass to use
  1205. if new_callable is not None:
  1206. Klass = new_callable
  1207. elif spec is None and _is_async_obj(original):
  1208. Klass = AsyncMock
  1209. elif spec is not None or spec_set is not None:
  1210. this_spec = spec
  1211. if spec_set is not None:
  1212. this_spec = spec_set
  1213. if _is_list(this_spec):
  1214. not_callable = '__call__' not in this_spec
  1215. else:
  1216. not_callable = not callable(this_spec)
  1217. if _is_async_obj(this_spec):
  1218. Klass = AsyncMock
  1219. elif not_callable:
  1220. Klass = NonCallableMagicMock
  1221. else:
  1222. Klass = MagicMock
  1223. else:
  1224. Klass = MagicMock
  1225. _kwargs = {}
  1226. if spec is not None:
  1227. _kwargs['spec'] = spec
  1228. if spec_set is not None:
  1229. _kwargs['spec_set'] = spec_set
  1230. # add a name to mocks
  1231. if (isinstance(Klass, type) and
  1232. issubclass(Klass, NonCallableMock) and self.attribute):
  1233. _kwargs['name'] = self.attribute
  1234. _kwargs.update(kwargs)
  1235. new = Klass(**_kwargs)
  1236. if inherit and _is_instance_mock(new):
  1237. # we can only tell if the instance should be callable if the
  1238. # spec is not a list
  1239. this_spec = spec
  1240. if spec_set is not None:
  1241. this_spec = spec_set
  1242. if (not _is_list(this_spec) and not
  1243. _instance_callable(this_spec)):
  1244. Klass = NonCallableMagicMock
  1245. _kwargs.pop('name')
  1246. new.return_value = Klass(_new_parent=new, _new_name='()',
  1247. **_kwargs)
  1248. elif autospec is not None:
  1249. # spec is ignored, new *must* be default, spec_set is treated
  1250. # as a boolean. Should we check spec is not None and that spec_set
  1251. # is a bool?
  1252. if new is not DEFAULT:
  1253. raise TypeError(
  1254. "autospec creates the mock for you. Can't specify "
  1255. "autospec and new."
  1256. )
  1257. if original is DEFAULT:
  1258. raise TypeError("Can't use 'autospec' with create=True")
  1259. spec_set = bool(spec_set)
  1260. if autospec is True:
  1261. autospec = original
  1262. if _is_instance_mock(self.target):
  1263. raise InvalidSpecError(
  1264. f'Cannot autospec attr {self.attribute!r} as the patch '
  1265. f'target has already been mocked out. '
  1266. f'[target={self.target!r}, attr={autospec!r}]')
  1267. if _is_instance_mock(autospec):
  1268. target_name = getattr(self.target, '__name__', self.target)
  1269. raise InvalidSpecError(
  1270. f'Cannot autospec attr {self.attribute!r} from target '
  1271. f'{target_name!r} as it has already been mocked out. '
  1272. f'[target={self.target!r}, attr={autospec!r}]')
  1273. new = create_autospec(autospec, spec_set=spec_set,
  1274. _name=self.attribute, **kwargs)
  1275. elif kwargs:
  1276. # can't set keyword args when we aren't creating the mock
  1277. # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
  1278. raise TypeError("Can't pass kwargs to a mock we aren't creating")
  1279. new_attr = new
  1280. self.temp_original = original
  1281. self.is_local = local
  1282. self._exit_stack = contextlib.ExitStack()
  1283. try:
  1284. setattr(self.target, self.attribute, new_attr)
  1285. if self.attribute_name is not None:
  1286. extra_args = {}
  1287. if self.new is DEFAULT:
  1288. extra_args[self.attribute_name] = new
  1289. for patching in self.additional_patchers:
  1290. arg = self._exit_stack.enter_context(patching)
  1291. if patching.new is DEFAULT:
  1292. extra_args.update(arg)
  1293. return extra_args
  1294. return new
  1295. except:
  1296. if not self.__exit__(*sys.exc_info()):
  1297. raise
  1298. def __exit__(self, *exc_info):
  1299. """Undo the patch."""
  1300. if self.is_local and self.temp_original is not DEFAULT:
  1301. setattr(self.target, self.attribute, self.temp_original)
  1302. else:
  1303. delattr(self.target, self.attribute)
  1304. if not self.create and (not hasattr(self.target, self.attribute) or
  1305. self.attribute in ('__doc__', '__module__',
  1306. '__defaults__', '__annotations__',
  1307. '__kwdefaults__')):
  1308. # needed for proxy objects like django settings
  1309. setattr(self.target, self.attribute, self.temp_original)
  1310. del self.temp_original
  1311. del self.is_local
  1312. del self.target
  1313. exit_stack = self._exit_stack
  1314. del self._exit_stack
  1315. return exit_stack.__exit__(*exc_info)
  1316. def start(self):
  1317. """Activate a patch, returning any created mock."""
  1318. result = self.__enter__()
  1319. self._active_patches.append(self)
  1320. return result
  1321. def stop(self):
  1322. """Stop an active patch."""
  1323. try:
  1324. self._active_patches.remove(self)
  1325. except ValueError:
  1326. # If the patch hasn't been started this will fail
  1327. return None
  1328. return self.__exit__(None, None, None)
  1329. def _get_target(target):
  1330. try:
  1331. target, attribute = target.rsplit('.', 1)
  1332. except (TypeError, ValueError, AttributeError):
  1333. raise TypeError(
  1334. f"Need a valid target to patch. You supplied: {target!r}")
  1335. return partial(pkgutil.resolve_name, target), attribute
  1336. def _patch_object(
  1337. target, attribute, new=DEFAULT, spec=None,
  1338. create=False, spec_set=None, autospec=None,
  1339. new_callable=None, *, unsafe=False, **kwargs
  1340. ):
  1341. """
  1342. patch the named member (`attribute`) on an object (`target`) with a mock
  1343. object.
  1344. `patch.object` can be used as a decorator, class decorator or a context
  1345. manager. Arguments `new`, `spec`, `create`, `spec_set`,
  1346. `autospec` and `new_callable` have the same meaning as for `patch`. Like
  1347. `patch`, `patch.object` takes arbitrary keyword arguments for configuring
  1348. the mock object it creates.
  1349. When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
  1350. for choosing which methods to wrap.
  1351. """
  1352. if type(target) is str:
  1353. raise TypeError(
  1354. f"{target!r} must be the actual object to be patched, not a str"
  1355. )
  1356. getter = lambda: target
  1357. return _patch(
  1358. getter, attribute, new, spec, create,
  1359. spec_set, autospec, new_callable, kwargs, unsafe=unsafe
  1360. )
  1361. def _patch_multiple(target, spec=None, create=False, spec_set=None,
  1362. autospec=None, new_callable=None, **kwargs):
  1363. """Perform multiple patches in a single call. It takes the object to be
  1364. patched (either as an object or a string to fetch the object by importing)
  1365. and keyword arguments for the patches::
  1366. with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
  1367. ...
  1368. Use `DEFAULT` as the value if you want `patch.multiple` to create
  1369. mocks for you. In this case the created mocks are passed into a decorated
  1370. function by keyword, and a dictionary is returned when `patch.multiple` is
  1371. used as a context manager.
  1372. `patch.multiple` can be used as a decorator, class decorator or a context
  1373. manager. The arguments `spec`, `spec_set`, `create`,
  1374. `autospec` and `new_callable` have the same meaning as for `patch`. These
  1375. arguments will be applied to *all* patches done by `patch.multiple`.
  1376. When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
  1377. for choosing which methods to wrap.
  1378. """
  1379. if type(target) is str:
  1380. getter = partial(pkgutil.resolve_name, target)
  1381. else:
  1382. getter = lambda: target
  1383. if not kwargs:
  1384. raise ValueError(
  1385. 'Must supply at least one keyword argument with patch.multiple'
  1386. )
  1387. # need to wrap in a list for python 3, where items is a view
  1388. items = list(kwargs.items())
  1389. attribute, new = items[0]
  1390. patcher = _patch(
  1391. getter, attribute, new, spec, create, spec_set,
  1392. autospec, new_callable, {}
  1393. )
  1394. patcher.attribute_name = attribute
  1395. for attribute, new in items[1:]:
  1396. this_patcher = _patch(
  1397. getter, attribute, new, spec, create, spec_set,
  1398. autospec, new_callable, {}
  1399. )
  1400. this_patcher.attribute_name = attribute
  1401. patcher.additional_patchers.append(this_patcher)
  1402. return patcher
  1403. def patch(
  1404. target, new=DEFAULT, spec=None, create=False,
  1405. spec_set=None, autospec=None, new_callable=None, *, unsafe=False, **kwargs
  1406. ):
  1407. """
  1408. `patch` acts as a function decorator, class decorator or a context
  1409. manager. Inside the body of the function or with statement, the `target`
  1410. is patched with a `new` object. When the function/with statement exits
  1411. the patch is undone.
  1412. If `new` is omitted, then the target is replaced with an
  1413. `AsyncMock if the patched object is an async function or a
  1414. `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
  1415. omitted, the created mock is passed in as an extra argument to the
  1416. decorated function. If `patch` is used as a context manager the created
  1417. mock is returned by the context manager.
  1418. `target` should be a string in the form `'package.module.ClassName'`. The
  1419. `target` is imported and the specified object replaced with the `new`
  1420. object, so the `target` must be importable from the environment you are
  1421. calling `patch` from. The target is imported when the decorated function
  1422. is executed, not at decoration time.
  1423. The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
  1424. if patch is creating one for you.
  1425. In addition you can pass `spec=True` or `spec_set=True`, which causes
  1426. patch to pass in the object being mocked as the spec/spec_set object.
  1427. `new_callable` allows you to specify a different class, or callable object,
  1428. that will be called to create the `new` object. By default `AsyncMock` is
  1429. used for async functions and `MagicMock` for the rest.
  1430. A more powerful form of `spec` is `autospec`. If you set `autospec=True`
  1431. then the mock will be created with a spec from the object being replaced.
  1432. All attributes of the mock will also have the spec of the corresponding
  1433. attribute of the object being replaced. Methods and functions being
  1434. mocked will have their arguments checked and will raise a `TypeError` if
  1435. they are called with the wrong signature. For mocks replacing a class,
  1436. their return value (the 'instance') will have the same spec as the class.
  1437. Instead of `autospec=True` you can pass `autospec=some_object` to use an
  1438. arbitrary object as the spec instead of the one being replaced.
  1439. By default `patch` will fail to replace attributes that don't exist. If
  1440. you pass in `create=True`, and the attribute doesn't exist, patch will
  1441. create the attribute for you when the patched function is called, and
  1442. delete it again afterwards. This is useful for writing tests against
  1443. attributes that your production code creates at runtime. It is off by
  1444. default because it can be dangerous. With it switched on you can write
  1445. passing tests against APIs that don't actually exist!
  1446. Patch can be used as a `TestCase` class decorator. It works by
  1447. decorating each test method in the class. This reduces the boilerplate
  1448. code when your test methods share a common patchings set. `patch` finds
  1449. tests by looking for method names that start with `patch.TEST_PREFIX`.
  1450. By default this is `test`, which matches the way `unittest` finds tests.
  1451. You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
  1452. Patch can be used as a context manager, with the with statement. Here the
  1453. patching applies to the indented block after the with statement. If you
  1454. use "as" then the patched object will be bound to the name after the
  1455. "as"; very useful if `patch` is creating a mock object for you.
  1456. Patch will raise a `RuntimeError` if passed some common misspellings of
  1457. the arguments autospec and spec_set. Pass the argument `unsafe` with the
  1458. value True to disable that check.
  1459. `patch` takes arbitrary keyword arguments. These will be passed to
  1460. `AsyncMock` if the patched object is asynchronous, to `MagicMock`
  1461. otherwise or to `new_callable` if specified.
  1462. `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
  1463. available for alternate use-cases.
  1464. """
  1465. getter, attribute = _get_target(target)
  1466. return _patch(
  1467. getter, attribute, new, spec, create,
  1468. spec_set, autospec, new_callable, kwargs, unsafe=unsafe
  1469. )
  1470. class _patch_dict(object):
  1471. """
  1472. Patch a dictionary, or dictionary like object, and restore the dictionary
  1473. to its original state after the test.
  1474. `in_dict` can be a dictionary or a mapping like container. If it is a
  1475. mapping then it must at least support getting, setting and deleting items
  1476. plus iterating over keys.
  1477. `in_dict` can also be a string specifying the name of the dictionary, which
  1478. will then be fetched by importing it.
  1479. `values` can be a dictionary of values to set in the dictionary. `values`
  1480. can also be an iterable of `(key, value)` pairs.
  1481. If `clear` is True then the dictionary will be cleared before the new
  1482. values are set.
  1483. `patch.dict` can also be called with arbitrary keyword arguments to set
  1484. values in the dictionary::
  1485. with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
  1486. ...
  1487. `patch.dict` can be used as a context manager, decorator or class
  1488. decorator. When used as a class decorator `patch.dict` honours
  1489. `patch.TEST_PREFIX` for choosing which methods to wrap.
  1490. """
  1491. def __init__(self, in_dict, values=(), clear=False, **kwargs):
  1492. self.in_dict = in_dict
  1493. # support any argument supported by dict(...) constructor
  1494. self.values = dict(values)
  1495. self.values.update(kwargs)
  1496. self.clear = clear
  1497. self._original = None
  1498. def __call__(self, f):
  1499. if isinstance(f, type):
  1500. return self.decorate_class(f)
  1501. if inspect.iscoroutinefunction(f):
  1502. return self.decorate_async_callable(f)
  1503. return self.decorate_callable(f)
  1504. def decorate_callable(self, f):
  1505. @wraps(f)
  1506. def _inner(*args, **kw):
  1507. self._patch_dict()
  1508. try:
  1509. return f(*args, **kw)
  1510. finally:
  1511. self._unpatch_dict()
  1512. return _inner
  1513. def decorate_async_callable(self, f):
  1514. @wraps(f)
  1515. async def _inner(*args, **kw):
  1516. self._patch_dict()
  1517. try:
  1518. return await f(*args, **kw)
  1519. finally:
  1520. self._unpatch_dict()
  1521. return _inner
  1522. def decorate_class(self, klass):
  1523. for attr in dir(klass):
  1524. attr_value = getattr(klass, attr)
  1525. if (attr.startswith(patch.TEST_PREFIX) and
  1526. hasattr(attr_value, "__call__")):
  1527. decorator = _patch_dict(self.in_dict, self.values, self.clear)
  1528. decorated = decorator(attr_value)
  1529. setattr(klass, attr, decorated)
  1530. return klass
  1531. def __enter__(self):
  1532. """Patch the dict."""
  1533. self._patch_dict()
  1534. return self.in_dict
  1535. def _patch_dict(self):
  1536. values = self.values
  1537. if isinstance(self.in_dict, str):
  1538. self.in_dict = pkgutil.resolve_name(self.in_dict)
  1539. in_dict = self.in_dict
  1540. clear = self.clear
  1541. try:
  1542. original = in_dict.copy()
  1543. except AttributeError:
  1544. # dict like object with no copy method
  1545. # must support iteration over keys
  1546. original = {}
  1547. for key in in_dict:
  1548. original[key] = in_dict[key]
  1549. self._original = original
  1550. if clear:
  1551. _clear_dict(in_dict)
  1552. try:
  1553. in_dict.update(values)
  1554. except AttributeError:
  1555. # dict like object with no update method
  1556. for key in values:
  1557. in_dict[key] = values[key]
  1558. def _unpatch_dict(self):
  1559. in_dict = self.in_dict
  1560. original = self._original
  1561. _clear_dict(in_dict)
  1562. try:
  1563. in_dict.update(original)
  1564. except AttributeError:
  1565. for key in original:
  1566. in_dict[key] = original[key]
  1567. def __exit__(self, *args):
  1568. """Unpatch the dict."""
  1569. if self._original is not None:
  1570. self._unpatch_dict()
  1571. return False
  1572. def start(self):
  1573. """Activate a patch, returning any created mock."""
  1574. result = self.__enter__()
  1575. _patch._active_patches.append(self)
  1576. return result
  1577. def stop(self):
  1578. """Stop an active patch."""
  1579. try:
  1580. _patch._active_patches.remove(self)
  1581. except ValueError:
  1582. # If the patch hasn't been started this will fail
  1583. return None
  1584. return self.__exit__(None, None, None)
  1585. def _clear_dict(in_dict):
  1586. try:
  1587. in_dict.clear()
  1588. except AttributeError:
  1589. keys = list(in_dict)
  1590. for key in keys:
  1591. del in_dict[key]
  1592. def _patch_stopall():
  1593. """Stop all active patches. LIFO to unroll nested patches."""
  1594. for patch in reversed(_patch._active_patches):
  1595. patch.stop()
  1596. patch.object = _patch_object
  1597. patch.dict = _patch_dict
  1598. patch.multiple = _patch_multiple
  1599. patch.stopall = _patch_stopall
  1600. patch.TEST_PREFIX = 'test'
  1601. magic_methods = (
  1602. "lt le gt ge eq ne "
  1603. "getitem setitem delitem "
  1604. "len contains iter "
  1605. "hash str sizeof "
  1606. "enter exit "
  1607. # we added divmod and rdivmod here instead of numerics
  1608. # because there is no idivmod
  1609. "divmod rdivmod neg pos abs invert "
  1610. "complex int float index "
  1611. "round trunc floor ceil "
  1612. "bool next "
  1613. "fspath "
  1614. "aiter "
  1615. )
  1616. numerics = (
  1617. "add sub mul matmul truediv floordiv mod lshift rshift and xor or pow"
  1618. )
  1619. inplace = ' '.join('i%s' % n for n in numerics.split())
  1620. right = ' '.join('r%s' % n for n in numerics.split())
  1621. # not including __prepare__, __instancecheck__, __subclasscheck__
  1622. # (as they are metaclass methods)
  1623. # __del__ is not supported at all as it causes problems if it exists
  1624. _non_defaults = {
  1625. '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
  1626. '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
  1627. '__getstate__', '__setstate__', '__getformat__',
  1628. '__repr__', '__dir__', '__subclasses__', '__format__',
  1629. '__getnewargs_ex__',
  1630. }
  1631. def _get_method(name, func):
  1632. "Turns a callable object (like a mock) into a real function"
  1633. def method(self, /, *args, **kw):
  1634. return func(self, *args, **kw)
  1635. method.__name__ = name
  1636. return method
  1637. _magics = {
  1638. '__%s__' % method for method in
  1639. ' '.join([magic_methods, numerics, inplace, right]).split()
  1640. }
  1641. # Magic methods used for async `with` statements
  1642. _async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
  1643. # Magic methods that are only used with async calls but are synchronous functions themselves
  1644. _sync_async_magics = {"__aiter__"}
  1645. _async_magics = _async_method_magics | _sync_async_magics
  1646. _all_sync_magics = _magics | _non_defaults
  1647. _all_magics = _all_sync_magics | _async_magics
  1648. _unsupported_magics = {
  1649. '__getattr__', '__setattr__',
  1650. '__init__', '__new__', '__prepare__',
  1651. '__instancecheck__', '__subclasscheck__',
  1652. '__del__'
  1653. }
  1654. _calculate_return_value = {
  1655. '__hash__': lambda self: object.__hash__(self),
  1656. '__str__': lambda self: object.__str__(self),
  1657. '__sizeof__': lambda self: object.__sizeof__(self),
  1658. '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
  1659. }
  1660. _return_values = {
  1661. '__lt__': NotImplemented,
  1662. '__gt__': NotImplemented,
  1663. '__le__': NotImplemented,
  1664. '__ge__': NotImplemented,
  1665. '__int__': 1,
  1666. '__contains__': False,
  1667. '__len__': 0,
  1668. '__exit__': False,
  1669. '__complex__': 1j,
  1670. '__float__': 1.0,
  1671. '__bool__': True,
  1672. '__index__': 1,
  1673. '__aexit__': False,
  1674. }
  1675. def _get_eq(self):
  1676. def __eq__(other):
  1677. ret_val = self.__eq__._mock_return_value
  1678. if ret_val is not DEFAULT:
  1679. return ret_val
  1680. if self is other:
  1681. return True
  1682. return NotImplemented
  1683. return __eq__
  1684. def _get_ne(self):
  1685. def __ne__(other):
  1686. if self.__ne__._mock_return_value is not DEFAULT:
  1687. return DEFAULT
  1688. if self is other:
  1689. return False
  1690. return NotImplemented
  1691. return __ne__
  1692. def _get_iter(self):
  1693. def __iter__():
  1694. ret_val = self.__iter__._mock_return_value
  1695. if ret_val is DEFAULT:
  1696. return iter([])
  1697. # if ret_val was already an iterator, then calling iter on it should
  1698. # return the iterator unchanged
  1699. return iter(ret_val)
  1700. return __iter__
  1701. def _get_async_iter(self):
  1702. def __aiter__():
  1703. ret_val = self.__aiter__._mock_return_value
  1704. if ret_val is DEFAULT:
  1705. return _AsyncIterator(iter([]))
  1706. return _AsyncIterator(iter(ret_val))
  1707. return __aiter__
  1708. _side_effect_methods = {
  1709. '__eq__': _get_eq,
  1710. '__ne__': _get_ne,
  1711. '__iter__': _get_iter,
  1712. '__aiter__': _get_async_iter
  1713. }
  1714. def _set_return_value(mock, method, name):
  1715. fixed = _return_values.get(name, DEFAULT)
  1716. if fixed is not DEFAULT:
  1717. method.return_value = fixed
  1718. return
  1719. return_calculator = _calculate_return_value.get(name)
  1720. if return_calculator is not None:
  1721. return_value = return_calculator(mock)
  1722. method.return_value = return_value
  1723. return
  1724. side_effector = _side_effect_methods.get(name)
  1725. if side_effector is not None:
  1726. method.side_effect = side_effector(mock)
  1727. class MagicMixin(Base):
  1728. def __init__(self, /, *args, **kw):
  1729. self._mock_set_magics() # make magic work for kwargs in init
  1730. _safe_super(MagicMixin, self).__init__(*args, **kw)
  1731. self._mock_set_magics() # fix magic broken by upper level init
  1732. def _mock_set_magics(self):
  1733. orig_magics = _magics | _async_method_magics
  1734. these_magics = orig_magics
  1735. if getattr(self, "_mock_methods", None) is not None:
  1736. these_magics = orig_magics.intersection(self._mock_methods)
  1737. remove_magics = set()
  1738. remove_magics = orig_magics - these_magics
  1739. for entry in remove_magics:
  1740. if entry in type(self).__dict__:
  1741. # remove unneeded magic methods
  1742. delattr(self, entry)
  1743. # don't overwrite existing attributes if called a second time
  1744. these_magics = these_magics - set(type(self).__dict__)
  1745. _type = type(self)
  1746. for entry in these_magics:
  1747. setattr(_type, entry, MagicProxy(entry, self))
  1748. class NonCallableMagicMock(MagicMixin, NonCallableMock):
  1749. """A version of `MagicMock` that isn't callable."""
  1750. def mock_add_spec(self, spec, spec_set=False):
  1751. """Add a spec to a mock. `spec` can either be an object or a
  1752. list of strings. Only attributes on the `spec` can be fetched as
  1753. attributes from the mock.
  1754. If `spec_set` is True then only attributes on the spec can be set."""
  1755. self._mock_add_spec(spec, spec_set)
  1756. self._mock_set_magics()
  1757. class AsyncMagicMixin(MagicMixin):
  1758. pass
  1759. class MagicMock(MagicMixin, Mock):
  1760. """
  1761. MagicMock is a subclass of Mock with default implementations
  1762. of most of the magic methods. You can use MagicMock without having to
  1763. configure the magic methods yourself.
  1764. If you use the `spec` or `spec_set` arguments then *only* magic
  1765. methods that exist in the spec will be created.
  1766. Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
  1767. """
  1768. def mock_add_spec(self, spec, spec_set=False):
  1769. """Add a spec to a mock. `spec` can either be an object or a
  1770. list of strings. Only attributes on the `spec` can be fetched as
  1771. attributes from the mock.
  1772. If `spec_set` is True then only attributes on the spec can be set."""
  1773. self._mock_add_spec(spec, spec_set)
  1774. self._mock_set_magics()
  1775. def reset_mock(self, /, *args, return_value: bool = False, **kwargs):
  1776. if (
  1777. return_value
  1778. and self._mock_name
  1779. and _is_magic(self._mock_name)
  1780. ):
  1781. # Don't reset return values for magic methods,
  1782. # otherwise `m.__str__` will start
  1783. # to return `MagicMock` instances, instead of `str` instances.
  1784. return_value = False
  1785. super().reset_mock(*args, return_value=return_value, **kwargs)
  1786. class MagicProxy(Base):
  1787. def __init__(self, name, parent):
  1788. self.name = name
  1789. self.parent = parent
  1790. def create_mock(self):
  1791. entry = self.name
  1792. parent = self.parent
  1793. m = parent._get_child_mock(name=entry, _new_name=entry,
  1794. _new_parent=parent)
  1795. setattr(parent, entry, m)
  1796. _set_return_value(parent, m, entry)
  1797. return m
  1798. def __get__(self, obj, _type=None):
  1799. return self.create_mock()
  1800. try:
  1801. _CODE_SIG = inspect.signature(partial(CodeType.__init__, None))
  1802. _CODE_ATTRS = dir(CodeType)
  1803. except ValueError:
  1804. _CODE_SIG = None
  1805. class AsyncMockMixin(Base):
  1806. await_count = _delegating_property('await_count')
  1807. await_args = _delegating_property('await_args')
  1808. await_args_list = _delegating_property('await_args_list')
  1809. def __init__(self, /, *args, **kwargs):
  1810. super().__init__(*args, **kwargs)
  1811. # iscoroutinefunction() checks _is_coroutine property to say if an
  1812. # object is a coroutine. Without this check it looks to see if it is a
  1813. # function/method, which in this case it is not (since it is an
  1814. # AsyncMock).
  1815. # It is set through __dict__ because when spec_set is True, this
  1816. # attribute is likely undefined.
  1817. self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
  1818. self.__dict__['_mock_await_count'] = 0
  1819. self.__dict__['_mock_await_args'] = None
  1820. self.__dict__['_mock_await_args_list'] = _CallList()
  1821. if _CODE_SIG:
  1822. code_mock = NonCallableMock(spec_set=_CODE_ATTRS)
  1823. code_mock.__dict__["_spec_class"] = CodeType
  1824. code_mock.__dict__["_spec_signature"] = _CODE_SIG
  1825. else:
  1826. code_mock = NonCallableMock(spec_set=CodeType)
  1827. code_mock.co_flags = (
  1828. inspect.CO_COROUTINE
  1829. + inspect.CO_VARARGS
  1830. + inspect.CO_VARKEYWORDS
  1831. )
  1832. code_mock.co_argcount = 0
  1833. code_mock.co_varnames = ('args', 'kwargs')
  1834. code_mock.co_posonlyargcount = 0
  1835. code_mock.co_kwonlyargcount = 0
  1836. self.__dict__['__code__'] = code_mock
  1837. self.__dict__['__name__'] = 'AsyncMock'
  1838. self.__dict__['__defaults__'] = tuple()
  1839. self.__dict__['__kwdefaults__'] = {}
  1840. self.__dict__['__annotations__'] = None
  1841. async def _execute_mock_call(self, /, *args, **kwargs):
  1842. # This is nearly just like super(), except for special handling
  1843. # of coroutines
  1844. _call = _Call((args, kwargs), two=True)
  1845. self.await_count += 1
  1846. self.await_args = _call
  1847. self.await_args_list.append(_call)
  1848. effect = self.side_effect
  1849. if effect is not None:
  1850. if _is_exception(effect):
  1851. raise effect
  1852. elif not _callable(effect):
  1853. try:
  1854. result = next(effect)
  1855. except StopIteration:
  1856. # It is impossible to propagate a StopIteration
  1857. # through coroutines because of PEP 479
  1858. raise StopAsyncIteration
  1859. if _is_exception(result):
  1860. raise result
  1861. elif iscoroutinefunction(effect):
  1862. result = await effect(*args, **kwargs)
  1863. else:
  1864. result = effect(*args, **kwargs)
  1865. if result is not DEFAULT:
  1866. return result
  1867. if self._mock_return_value is not DEFAULT:
  1868. return self.return_value
  1869. if self._mock_wraps is not None:
  1870. if iscoroutinefunction(self._mock_wraps):
  1871. return await self._mock_wraps(*args, **kwargs)
  1872. return self._mock_wraps(*args, **kwargs)
  1873. return self.return_value
  1874. def assert_awaited(self):
  1875. """
  1876. Assert that the mock was awaited at least once.
  1877. """
  1878. if self.await_count == 0:
  1879. msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
  1880. raise AssertionError(msg)
  1881. def assert_awaited_once(self):
  1882. """
  1883. Assert that the mock was awaited exactly once.
  1884. """
  1885. if not self.await_count == 1:
  1886. msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
  1887. f" Awaited {self.await_count} times.")
  1888. raise AssertionError(msg)
  1889. def assert_awaited_with(self, /, *args, **kwargs):
  1890. """
  1891. Assert that the last await was with the specified arguments.
  1892. """
  1893. if self.await_args is None:
  1894. expected = self._format_mock_call_signature(args, kwargs)
  1895. raise AssertionError(f'Expected await: {expected}\nNot awaited')
  1896. def _error_message():
  1897. msg = self._format_mock_failure_message(args, kwargs, action='await')
  1898. return msg
  1899. expected = self._call_matcher(_Call((args, kwargs), two=True))
  1900. actual = self._call_matcher(self.await_args)
  1901. if actual != expected:
  1902. cause = expected if isinstance(expected, Exception) else None
  1903. raise AssertionError(_error_message()) from cause
  1904. def assert_awaited_once_with(self, /, *args, **kwargs):
  1905. """
  1906. Assert that the mock was awaited exactly once and with the specified
  1907. arguments.
  1908. """
  1909. if not self.await_count == 1:
  1910. msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
  1911. f" Awaited {self.await_count} times.")
  1912. raise AssertionError(msg)
  1913. return self.assert_awaited_with(*args, **kwargs)
  1914. def assert_any_await(self, /, *args, **kwargs):
  1915. """
  1916. Assert the mock has ever been awaited with the specified arguments.
  1917. """
  1918. expected = self._call_matcher(_Call((args, kwargs), two=True))
  1919. cause = expected if isinstance(expected, Exception) else None
  1920. actual = [self._call_matcher(c) for c in self.await_args_list]
  1921. if cause or expected not in _AnyComparer(actual):
  1922. expected_string = self._format_mock_call_signature(args, kwargs)
  1923. raise AssertionError(
  1924. '%s await not found' % expected_string
  1925. ) from cause
  1926. def assert_has_awaits(self, calls, any_order=False):
  1927. """
  1928. Assert the mock has been awaited with the specified calls.
  1929. The :attr:`await_args_list` list is checked for the awaits.
  1930. If `any_order` is False (the default) then the awaits must be
  1931. sequential. There can be extra calls before or after the
  1932. specified awaits.
  1933. If `any_order` is True then the awaits can be in any order, but
  1934. they must all appear in :attr:`await_args_list`.
  1935. """
  1936. expected = [self._call_matcher(c) for c in calls]
  1937. cause = next((e for e in expected if isinstance(e, Exception)), None)
  1938. all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
  1939. if not any_order:
  1940. if expected not in all_awaits:
  1941. if cause is None:
  1942. problem = 'Awaits not found.'
  1943. else:
  1944. problem = ('Error processing expected awaits.\n'
  1945. 'Errors: {}').format(
  1946. [e if isinstance(e, Exception) else None
  1947. for e in expected])
  1948. raise AssertionError(
  1949. f'{problem}\n'
  1950. f'Expected: {_CallList(calls)}\n'
  1951. f'Actual: {self.await_args_list}'
  1952. ) from cause
  1953. return
  1954. all_awaits = list(all_awaits)
  1955. not_found = []
  1956. for kall in expected:
  1957. try:
  1958. all_awaits.remove(kall)
  1959. except ValueError:
  1960. not_found.append(kall)
  1961. if not_found:
  1962. raise AssertionError(
  1963. '%r not all found in await list' % (tuple(not_found),)
  1964. ) from cause
  1965. def assert_not_awaited(self):
  1966. """
  1967. Assert that the mock was never awaited.
  1968. """
  1969. if self.await_count != 0:
  1970. msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
  1971. f" Awaited {self.await_count} times.")
  1972. raise AssertionError(msg)
  1973. def reset_mock(self, /, *args, **kwargs):
  1974. """
  1975. See :func:`.Mock.reset_mock()`
  1976. """
  1977. super().reset_mock(*args, **kwargs)
  1978. self.await_count = 0
  1979. self.await_args = None
  1980. self.await_args_list = _CallList()
  1981. class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
  1982. """
  1983. Enhance :class:`Mock` with features allowing to mock
  1984. an async function.
  1985. The :class:`AsyncMock` object will behave so the object is
  1986. recognized as an async function, and the result of a call is an awaitable:
  1987. >>> mock = AsyncMock()
  1988. >>> iscoroutinefunction(mock)
  1989. True
  1990. >>> inspect.isawaitable(mock())
  1991. True
  1992. The result of ``mock()`` is an async function which will have the outcome
  1993. of ``side_effect`` or ``return_value``:
  1994. - if ``side_effect`` is a function, the async function will return the
  1995. result of that function,
  1996. - if ``side_effect`` is an exception, the async function will raise the
  1997. exception,
  1998. - if ``side_effect`` is an iterable, the async function will return the
  1999. next value of the iterable, however, if the sequence of result is
  2000. exhausted, ``StopIteration`` is raised immediately,
  2001. - if ``side_effect`` is not defined, the async function will return the
  2002. value defined by ``return_value``, hence, by default, the async function
  2003. returns a new :class:`AsyncMock` object.
  2004. If the outcome of ``side_effect`` or ``return_value`` is an async function,
  2005. the mock async function obtained when the mock object is called will be this
  2006. async function itself (and not an async function returning an async
  2007. function).
  2008. The test author can also specify a wrapped object with ``wraps``. In this
  2009. case, the :class:`Mock` object behavior is the same as with an
  2010. :class:`.Mock` object: the wrapped object may have methods
  2011. defined as async function functions.
  2012. Based on Martin Richard's asynctest project.
  2013. """
  2014. class _ANY(object):
  2015. "A helper object that compares equal to everything."
  2016. def __eq__(self, other):
  2017. return True
  2018. def __ne__(self, other):
  2019. return False
  2020. def __repr__(self):
  2021. return '<ANY>'
  2022. ANY = _ANY()
  2023. def _format_call_signature(name, args, kwargs):
  2024. message = '%s(%%s)' % name
  2025. formatted_args = ''
  2026. args_string = ', '.join([repr(arg) for arg in args])
  2027. kwargs_string = ', '.join([
  2028. '%s=%r' % (key, value) for key, value in kwargs.items()
  2029. ])
  2030. if args_string:
  2031. formatted_args = args_string
  2032. if kwargs_string:
  2033. if formatted_args:
  2034. formatted_args += ', '
  2035. formatted_args += kwargs_string
  2036. return message % formatted_args
  2037. class _Call(tuple):
  2038. """
  2039. A tuple for holding the results of a call to a mock, either in the form
  2040. `(args, kwargs)` or `(name, args, kwargs)`.
  2041. If args or kwargs are empty then a call tuple will compare equal to
  2042. a tuple without those values. This makes comparisons less verbose::
  2043. _Call(('name', (), {})) == ('name',)
  2044. _Call(('name', (1,), {})) == ('name', (1,))
  2045. _Call(((), {'a': 'b'})) == ({'a': 'b'},)
  2046. The `_Call` object provides a useful shortcut for comparing with call::
  2047. _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
  2048. _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
  2049. If the _Call has no name then it will match any name.
  2050. """
  2051. def __new__(cls, value=(), name='', parent=None, two=False,
  2052. from_kall=True):
  2053. args = ()
  2054. kwargs = {}
  2055. _len = len(value)
  2056. if _len == 3:
  2057. name, args, kwargs = value
  2058. elif _len == 2:
  2059. first, second = value
  2060. if isinstance(first, str):
  2061. name = first
  2062. if isinstance(second, tuple):
  2063. args = second
  2064. else:
  2065. kwargs = second
  2066. else:
  2067. args, kwargs = first, second
  2068. elif _len == 1:
  2069. value, = value
  2070. if isinstance(value, str):
  2071. name = value
  2072. elif isinstance(value, tuple):
  2073. args = value
  2074. else:
  2075. kwargs = value
  2076. if two:
  2077. return tuple.__new__(cls, (args, kwargs))
  2078. return tuple.__new__(cls, (name, args, kwargs))
  2079. def __init__(self, value=(), name=None, parent=None, two=False,
  2080. from_kall=True):
  2081. self._mock_name = name
  2082. self._mock_parent = parent
  2083. self._mock_from_kall = from_kall
  2084. def __eq__(self, other):
  2085. try:
  2086. len_other = len(other)
  2087. except TypeError:
  2088. return NotImplemented
  2089. self_name = ''
  2090. if len(self) == 2:
  2091. self_args, self_kwargs = self
  2092. else:
  2093. self_name, self_args, self_kwargs = self
  2094. if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
  2095. and self._mock_parent != other._mock_parent):
  2096. return False
  2097. other_name = ''
  2098. if len_other == 0:
  2099. other_args, other_kwargs = (), {}
  2100. elif len_other == 3:
  2101. other_name, other_args, other_kwargs = other
  2102. elif len_other == 1:
  2103. value, = other
  2104. if isinstance(value, tuple):
  2105. other_args = value
  2106. other_kwargs = {}
  2107. elif isinstance(value, str):
  2108. other_name = value
  2109. other_args, other_kwargs = (), {}
  2110. else:
  2111. other_args = ()
  2112. other_kwargs = value
  2113. elif len_other == 2:
  2114. # could be (name, args) or (name, kwargs) or (args, kwargs)
  2115. first, second = other
  2116. if isinstance(first, str):
  2117. other_name = first
  2118. if isinstance(second, tuple):
  2119. other_args, other_kwargs = second, {}
  2120. else:
  2121. other_args, other_kwargs = (), second
  2122. else:
  2123. other_args, other_kwargs = first, second
  2124. else:
  2125. return False
  2126. if self_name and other_name != self_name:
  2127. return False
  2128. # this order is important for ANY to work!
  2129. return (other_args, other_kwargs) == (self_args, self_kwargs)
  2130. __ne__ = object.__ne__
  2131. def __call__(self, /, *args, **kwargs):
  2132. if self._mock_name is None:
  2133. return _Call(('', args, kwargs), name='()')
  2134. name = self._mock_name + '()'
  2135. return _Call((self._mock_name, args, kwargs), name=name, parent=self)
  2136. def __getattr__(self, attr):
  2137. if self._mock_name is None:
  2138. return _Call(name=attr, from_kall=False)
  2139. name = '%s.%s' % (self._mock_name, attr)
  2140. return _Call(name=name, parent=self, from_kall=False)
  2141. def __getattribute__(self, attr):
  2142. if attr in tuple.__dict__:
  2143. raise AttributeError
  2144. return tuple.__getattribute__(self, attr)
  2145. def _get_call_arguments(self):
  2146. if len(self) == 2:
  2147. args, kwargs = self
  2148. else:
  2149. name, args, kwargs = self
  2150. return args, kwargs
  2151. @property
  2152. def args(self):
  2153. return self._get_call_arguments()[0]
  2154. @property
  2155. def kwargs(self):
  2156. return self._get_call_arguments()[1]
  2157. def __repr__(self):
  2158. if not self._mock_from_kall:
  2159. name = self._mock_name or 'call'
  2160. if name.startswith('()'):
  2161. name = 'call%s' % name
  2162. return name
  2163. if len(self) == 2:
  2164. name = 'call'
  2165. args, kwargs = self
  2166. else:
  2167. name, args, kwargs = self
  2168. if not name:
  2169. name = 'call'
  2170. elif not name.startswith('()'):
  2171. name = 'call.%s' % name
  2172. else:
  2173. name = 'call%s' % name
  2174. return _format_call_signature(name, args, kwargs)
  2175. def call_list(self):
  2176. """For a call object that represents multiple calls, `call_list`
  2177. returns a list of all the intermediate calls as well as the
  2178. final call."""
  2179. vals = []
  2180. thing = self
  2181. while thing is not None:
  2182. if thing._mock_from_kall:
  2183. vals.append(thing)
  2184. thing = thing._mock_parent
  2185. return _CallList(reversed(vals))
  2186. call = _Call(from_kall=False)
  2187. def create_autospec(spec, spec_set=False, instance=False, _parent=None,
  2188. _name=None, *, unsafe=False, **kwargs):
  2189. """Create a mock object using another object as a spec. Attributes on the
  2190. mock will use the corresponding attribute on the `spec` object as their
  2191. spec.
  2192. Functions or methods being mocked will have their arguments checked
  2193. to check that they are called with the correct signature.
  2194. If `spec_set` is True then attempting to set attributes that don't exist
  2195. on the spec object will raise an `AttributeError`.
  2196. If a class is used as a spec then the return value of the mock (the
  2197. instance of the class) will have the same spec. You can use a class as the
  2198. spec for an instance object by passing `instance=True`. The returned mock
  2199. will only be callable if instances of the mock are callable.
  2200. `create_autospec` will raise a `RuntimeError` if passed some common
  2201. misspellings of the arguments autospec and spec_set. Pass the argument
  2202. `unsafe` with the value True to disable that check.
  2203. `create_autospec` also takes arbitrary keyword arguments that are passed to
  2204. the constructor of the created mock."""
  2205. if _is_list(spec):
  2206. # can't pass a list instance to the mock constructor as it will be
  2207. # interpreted as a list of strings
  2208. spec = type(spec)
  2209. is_type = isinstance(spec, type)
  2210. if _is_instance_mock(spec):
  2211. raise InvalidSpecError(f'Cannot autospec a Mock object. '
  2212. f'[object={spec!r}]')
  2213. is_async_func = _is_async_func(spec)
  2214. _kwargs = {'spec': spec}
  2215. if spec_set:
  2216. _kwargs = {'spec_set': spec}
  2217. elif spec is None:
  2218. # None we mock with a normal mock without a spec
  2219. _kwargs = {}
  2220. if _kwargs and instance:
  2221. _kwargs['_spec_as_instance'] = True
  2222. if not unsafe:
  2223. _check_spec_arg_typos(kwargs)
  2224. _name = kwargs.pop('name', _name)
  2225. _new_name = _name
  2226. if _parent is None:
  2227. # for a top level object no _new_name should be set
  2228. _new_name = ''
  2229. _kwargs.update(kwargs)
  2230. Klass = MagicMock
  2231. if inspect.isdatadescriptor(spec):
  2232. # descriptors don't have a spec
  2233. # because we don't know what type they return
  2234. _kwargs = {}
  2235. elif is_async_func:
  2236. if instance:
  2237. raise RuntimeError("Instance can not be True when create_autospec "
  2238. "is mocking an async function")
  2239. Klass = AsyncMock
  2240. elif not _callable(spec):
  2241. Klass = NonCallableMagicMock
  2242. elif is_type and instance and not _instance_callable(spec):
  2243. Klass = NonCallableMagicMock
  2244. mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
  2245. name=_name, **_kwargs)
  2246. if isinstance(spec, FunctionTypes):
  2247. # should only happen at the top level because we don't
  2248. # recurse for functions
  2249. mock = _set_signature(mock, spec)
  2250. if is_async_func:
  2251. _setup_async_mock(mock)
  2252. else:
  2253. _check_signature(spec, mock, is_type, instance)
  2254. if _parent is not None and not instance:
  2255. _parent._mock_children[_name] = mock
  2256. # Pop wraps from kwargs because it must not be passed to configure_mock.
  2257. wrapped = kwargs.pop('wraps', None)
  2258. if is_type and not instance and 'return_value' not in kwargs:
  2259. mock.return_value = create_autospec(spec, spec_set, instance=True,
  2260. _name='()', _parent=mock,
  2261. wraps=wrapped)
  2262. for entry in dir(spec):
  2263. if _is_magic(entry):
  2264. # MagicMock already does the useful magic methods for us
  2265. continue
  2266. # XXXX do we need a better way of getting attributes without
  2267. # triggering code execution (?) Probably not - we need the actual
  2268. # object to mock it so we would rather trigger a property than mock
  2269. # the property descriptor. Likewise we want to mock out dynamically
  2270. # provided attributes.
  2271. # XXXX what about attributes that raise exceptions other than
  2272. # AttributeError on being fetched?
  2273. # we could be resilient against it, or catch and propagate the
  2274. # exception when the attribute is fetched from the mock
  2275. try:
  2276. original = getattr(spec, entry)
  2277. except AttributeError:
  2278. continue
  2279. child_kwargs = {'spec': original}
  2280. # Wrap child attributes also.
  2281. if wrapped and hasattr(wrapped, entry):
  2282. child_kwargs.update(wraps=original)
  2283. if spec_set:
  2284. child_kwargs = {'spec_set': original}
  2285. if not isinstance(original, FunctionTypes):
  2286. new = _SpecState(original, spec_set, mock, entry, instance)
  2287. mock._mock_children[entry] = new
  2288. else:
  2289. parent = mock
  2290. if isinstance(spec, FunctionTypes):
  2291. parent = mock.mock
  2292. skipfirst = _must_skip(spec, entry, is_type)
  2293. child_kwargs['_eat_self'] = skipfirst
  2294. if iscoroutinefunction(original):
  2295. child_klass = AsyncMock
  2296. else:
  2297. child_klass = MagicMock
  2298. new = child_klass(parent=parent, name=entry, _new_name=entry,
  2299. _new_parent=parent, **child_kwargs)
  2300. mock._mock_children[entry] = new
  2301. new.return_value = child_klass()
  2302. _check_signature(original, new, skipfirst=skipfirst)
  2303. # so functions created with _set_signature become instance attributes,
  2304. # *plus* their underlying mock exists in _mock_children of the parent
  2305. # mock. Adding to _mock_children may be unnecessary where we are also
  2306. # setting as an instance attribute?
  2307. if isinstance(new, FunctionTypes):
  2308. setattr(mock, entry, new)
  2309. # kwargs are passed with respect to the parent mock so, they are not used
  2310. # for creating return_value of the parent mock. So, this condition
  2311. # should be true only for the parent mock if kwargs are given.
  2312. if _is_instance_mock(mock) and kwargs:
  2313. mock.configure_mock(**kwargs)
  2314. return mock
  2315. def _must_skip(spec, entry, is_type):
  2316. """
  2317. Return whether we should skip the first argument on spec's `entry`
  2318. attribute.
  2319. """
  2320. if not isinstance(spec, type):
  2321. if entry in getattr(spec, '__dict__', {}):
  2322. # instance attribute - shouldn't skip
  2323. return False
  2324. spec = spec.__class__
  2325. for klass in spec.__mro__:
  2326. result = klass.__dict__.get(entry, DEFAULT)
  2327. if result is DEFAULT:
  2328. continue
  2329. if isinstance(result, (staticmethod, classmethod)):
  2330. return False
  2331. elif isinstance(result, FunctionTypes):
  2332. # Normal method => skip if looked up on type
  2333. # (if looked up on instance, self is already skipped)
  2334. return is_type
  2335. else:
  2336. return False
  2337. # function is a dynamically provided attribute
  2338. return is_type
  2339. class _SpecState(object):
  2340. def __init__(self, spec, spec_set=False, parent=None,
  2341. name=None, ids=None, instance=False):
  2342. self.spec = spec
  2343. self.ids = ids
  2344. self.spec_set = spec_set
  2345. self.parent = parent
  2346. self.instance = instance
  2347. self.name = name
  2348. FunctionTypes = (
  2349. # python function
  2350. type(create_autospec),
  2351. # instance method
  2352. type(ANY.__eq__),
  2353. )
  2354. file_spec = None
  2355. open_spec = None
  2356. def _to_stream(read_data):
  2357. if isinstance(read_data, bytes):
  2358. return io.BytesIO(read_data)
  2359. else:
  2360. return io.StringIO(read_data)
  2361. def mock_open(mock=None, read_data=''):
  2362. """
  2363. A helper function to create a mock to replace the use of `open`. It works
  2364. for `open` called directly or used as a context manager.
  2365. The `mock` argument is the mock object to configure. If `None` (the
  2366. default) then a `MagicMock` will be created for you, with the API limited
  2367. to methods or attributes available on standard file handles.
  2368. `read_data` is a string for the `read`, `readline` and `readlines` of the
  2369. file handle to return. This is an empty string by default.
  2370. """
  2371. _read_data = _to_stream(read_data)
  2372. _state = [_read_data, None]
  2373. def _readlines_side_effect(*args, **kwargs):
  2374. if handle.readlines.return_value is not None:
  2375. return handle.readlines.return_value
  2376. return _state[0].readlines(*args, **kwargs)
  2377. def _read_side_effect(*args, **kwargs):
  2378. if handle.read.return_value is not None:
  2379. return handle.read.return_value
  2380. return _state[0].read(*args, **kwargs)
  2381. def _readline_side_effect(*args, **kwargs):
  2382. yield from _iter_side_effect()
  2383. while True:
  2384. yield _state[0].readline(*args, **kwargs)
  2385. def _iter_side_effect():
  2386. if handle.readline.return_value is not None:
  2387. while True:
  2388. yield handle.readline.return_value
  2389. for line in _state[0]:
  2390. yield line
  2391. def _next_side_effect():
  2392. if handle.readline.return_value is not None:
  2393. return handle.readline.return_value
  2394. return next(_state[0])
  2395. global file_spec
  2396. if file_spec is None:
  2397. import _io
  2398. file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
  2399. global open_spec
  2400. if open_spec is None:
  2401. import _io
  2402. open_spec = list(set(dir(_io.open)))
  2403. if mock is None:
  2404. mock = MagicMock(name='open', spec=open_spec)
  2405. handle = MagicMock(spec=file_spec)
  2406. handle.__enter__.return_value = handle
  2407. handle.write.return_value = None
  2408. handle.read.return_value = None
  2409. handle.readline.return_value = None
  2410. handle.readlines.return_value = None
  2411. handle.read.side_effect = _read_side_effect
  2412. _state[1] = _readline_side_effect()
  2413. handle.readline.side_effect = _state[1]
  2414. handle.readlines.side_effect = _readlines_side_effect
  2415. handle.__iter__.side_effect = _iter_side_effect
  2416. handle.__next__.side_effect = _next_side_effect
  2417. def reset_data(*args, **kwargs):
  2418. _state[0] = _to_stream(read_data)
  2419. if handle.readline.side_effect == _state[1]:
  2420. # Only reset the side effect if the user hasn't overridden it.
  2421. _state[1] = _readline_side_effect()
  2422. handle.readline.side_effect = _state[1]
  2423. return DEFAULT
  2424. mock.side_effect = reset_data
  2425. mock.return_value = handle
  2426. return mock
  2427. class PropertyMock(Mock):
  2428. """
  2429. A mock intended to be used as a property, or other descriptor, on a class.
  2430. `PropertyMock` provides `__get__` and `__set__` methods so you can specify
  2431. a return value when it is fetched.
  2432. Fetching a `PropertyMock` instance from an object calls the mock, with
  2433. no args. Setting it calls the mock with the value being set.
  2434. """
  2435. def _get_child_mock(self, /, **kwargs):
  2436. return MagicMock(**kwargs)
  2437. def __get__(self, obj, obj_type=None):
  2438. return self()
  2439. def __set__(self, obj, val):
  2440. self(val)
  2441. def seal(mock):
  2442. """Disable the automatic generation of child mocks.
  2443. Given an input Mock, seals it to ensure no further mocks will be generated
  2444. when accessing an attribute that was not already defined.
  2445. The operation recursively seals the mock passed in, meaning that
  2446. the mock itself, any mocks generated by accessing one of its attributes,
  2447. and all assigned mocks without a name or spec will be sealed.
  2448. """
  2449. mock._mock_sealed = True
  2450. for attr in dir(mock):
  2451. try:
  2452. m = getattr(mock, attr)
  2453. except AttributeError:
  2454. continue
  2455. if not isinstance(m, NonCallableMock):
  2456. continue
  2457. if isinstance(m._mock_children.get(attr), _SpecState):
  2458. continue
  2459. if m._mock_new_parent is mock:
  2460. seal(m)
  2461. class _AsyncIterator:
  2462. """
  2463. Wraps an iterator in an asynchronous iterator.
  2464. """
  2465. def __init__(self, iterator):
  2466. self.iterator = iterator
  2467. code_mock = NonCallableMock(spec_set=CodeType)
  2468. code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
  2469. self.__dict__['__code__'] = code_mock
  2470. async def __anext__(self):
  2471. try:
  2472. return next(self.iterator)
  2473. except StopIteration:
  2474. pass
  2475. raise StopAsyncIteration