mock.py 101 KB

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