mock.py 97 KB

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