Plex plugin to to play various online streams (mostly Latvian).

mock.py 82KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556
  1. # mock.py
  2. # Test tools for mocking and patching.
  3. # E-mail: fuzzyman AT voidspace DOT org DOT uk
  4. #
  5. # mock 2.0.0
  6. # http://www.voidspace.org.uk/python/mock/
  7. #
  8. # Copyright (c) 2007-2013, Michael Foord & the mock team
  9. # All rights reserved.
  10. #
  11. # Redistribution and use in source and binary forms, with or without
  12. # modification, are permitted provided that the following conditions are
  13. # met:
  14. #
  15. # * Redistributions of source code must retain the above copyright
  16. # notice, this list of conditions and the following disclaimer.
  17. #
  18. # * Redistributions in binary form must reproduce the above
  19. # copyright notice, this list of conditions and the following
  20. # disclaimer in the documentation and/or other materials provided
  21. # with the distribution.
  22. #
  23. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  25. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  26. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  27. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  28. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  29. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  30. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  31. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  32. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  33. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34. from __future__ import absolute_import
  35. __all__ = (
  36. '__version__',
  37. 'version_info',
  38. 'Mock',
  39. 'MagicMock',
  40. 'patch',
  41. 'sentinel',
  42. 'DEFAULT',
  43. 'ANY',
  44. 'call',
  45. 'create_autospec',
  46. 'FILTER_DIR',
  47. 'CallableMixin',
  48. 'NonCallableMock',
  49. 'NonCallableMagicMock',
  50. 'mock_open',
  51. 'PropertyMock',
  52. )
  53. from functools import partial
  54. import inspect
  55. import pprint
  56. import sys
  57. try:
  58. import builtins
  59. except ImportError:
  60. import __builtin__ as builtins
  61. from types import ModuleType
  62. import six
  63. from six import wraps
  64. from pbr.version import VersionInfo
  65. _v = VersionInfo('mock').semantic_version()
  66. __version__ = _v.release_string()
  67. version_info = _v.version_tuple()
  68. import mock
  69. try:
  70. inspectsignature = inspect.signature
  71. except AttributeError:
  72. import funcsigs
  73. inspectsignature = funcsigs.signature
  74. # TODO: use six.
  75. try:
  76. unicode
  77. except NameError:
  78. # Python 3
  79. basestring = unicode = str
  80. try:
  81. long
  82. except NameError:
  83. # Python 3
  84. long = int
  85. try:
  86. BaseException
  87. except NameError:
  88. # Python 2.4 compatibility
  89. BaseException = Exception
  90. if six.PY2:
  91. # Python 2's next() can't handle a non-iterator with a __next__ method.
  92. _next = next
  93. def next(obj, _next=_next):
  94. if getattr(obj, '__next__', None):
  95. return obj.__next__()
  96. return _next(obj)
  97. del _next
  98. _builtins = set(name for name in dir(builtins) if not name.startswith('_'))
  99. BaseExceptions = (BaseException,)
  100. if 'java' in sys.platform:
  101. # jython
  102. import java
  103. BaseExceptions = (BaseException, java.lang.Throwable)
  104. try:
  105. _isidentifier = str.isidentifier
  106. except AttributeError:
  107. # Python 2.X
  108. import keyword
  109. import re
  110. regex = re.compile(r'^[a-z_][a-z0-9_]*$', re.I)
  111. def _isidentifier(string):
  112. if string in keyword.kwlist:
  113. return False
  114. return regex.match(string)
  115. self = 'im_self'
  116. builtin = '__builtin__'
  117. if six.PY3:
  118. self = '__self__'
  119. builtin = 'builtins'
  120. # NOTE: This FILTER_DIR is not used. The binding in mock.FILTER_DIR is.
  121. FILTER_DIR = True
  122. # Workaround for Python issue #12370
  123. # Without this, the __class__ properties wouldn't be set correctly
  124. _safe_super = super
  125. def _is_instance_mock(obj):
  126. # can't use isinstance on Mock objects because they override __class__
  127. # The base class for all mocks is NonCallableMock
  128. return issubclass(type(obj), NonCallableMock)
  129. def _is_exception(obj):
  130. return (
  131. isinstance(obj, BaseExceptions) or
  132. isinstance(obj, ClassTypes) and issubclass(obj, BaseExceptions)
  133. )
  134. class _slotted(object):
  135. __slots__ = ['a']
  136. DescriptorTypes = (
  137. type(_slotted.a),
  138. property,
  139. )
  140. def _get_signature_object(func, as_instance, eat_self):
  141. """
  142. Given an arbitrary, possibly callable object, try to create a suitable
  143. signature object.
  144. Return a (reduced func, signature) tuple, or None.
  145. """
  146. if isinstance(func, ClassTypes) and not as_instance:
  147. # If it's a type and should be modelled as a type, use __init__.
  148. try:
  149. func = func.__init__
  150. except AttributeError:
  151. return None
  152. # Skip the `self` argument in __init__
  153. eat_self = True
  154. elif not isinstance(func, FunctionTypes):
  155. # If we really want to model an instance of the passed type,
  156. # __call__ should be looked up, not __init__.
  157. try:
  158. func = func.__call__
  159. except AttributeError:
  160. return None
  161. if eat_self:
  162. sig_func = partial(func, None)
  163. else:
  164. sig_func = func
  165. try:
  166. return func, inspectsignature(sig_func)
  167. except ValueError:
  168. # Certain callable types are not supported by inspect.signature()
  169. return None
  170. def _check_signature(func, mock, skipfirst, instance=False):
  171. sig = _get_signature_object(func, instance, skipfirst)
  172. if sig is None:
  173. return
  174. func, sig = sig
  175. def checksig(_mock_self, *args, **kwargs):
  176. sig.bind(*args, **kwargs)
  177. _copy_func_details(func, checksig)
  178. type(mock)._mock_check_sig = checksig
  179. def _copy_func_details(func, funcopy):
  180. funcopy.__name__ = func.__name__
  181. funcopy.__doc__ = func.__doc__
  182. try:
  183. funcopy.__text_signature__ = func.__text_signature__
  184. except AttributeError:
  185. pass
  186. # we explicitly don't copy func.__dict__ into this copy as it would
  187. # expose original attributes that should be mocked
  188. try:
  189. funcopy.__module__ = func.__module__
  190. except AttributeError:
  191. pass
  192. try:
  193. funcopy.__defaults__ = func.__defaults__
  194. except AttributeError:
  195. pass
  196. try:
  197. funcopy.__kwdefaults__ = func.__kwdefaults__
  198. except AttributeError:
  199. pass
  200. if six.PY2:
  201. funcopy.func_defaults = func.func_defaults
  202. return
  203. def _callable(obj):
  204. if isinstance(obj, ClassTypes):
  205. return True
  206. if getattr(obj, '__call__', None) is not None:
  207. return True
  208. return False
  209. def _is_list(obj):
  210. # checks for list or tuples
  211. # XXXX badly named!
  212. return type(obj) in (list, tuple)
  213. def _instance_callable(obj):
  214. """Given an object, return True if the object is callable.
  215. For classes, return True if instances would be callable."""
  216. if not isinstance(obj, ClassTypes):
  217. # already an instance
  218. return getattr(obj, '__call__', None) is not None
  219. if six.PY3:
  220. # *could* be broken by a class overriding __mro__ or __dict__ via
  221. # a metaclass
  222. for base in (obj,) + obj.__mro__:
  223. if base.__dict__.get('__call__') is not None:
  224. return True
  225. else:
  226. klass = obj
  227. # uses __bases__ instead of __mro__ so that we work with old style classes
  228. if klass.__dict__.get('__call__') is not None:
  229. return True
  230. for base in klass.__bases__:
  231. if _instance_callable(base):
  232. return True
  233. return False
  234. def _set_signature(mock, original, instance=False):
  235. # creates a function with signature (*args, **kwargs) that delegates to a
  236. # mock. It still does signature checking by calling a lambda with the same
  237. # signature as the original.
  238. if not _callable(original):
  239. return
  240. skipfirst = isinstance(original, ClassTypes)
  241. result = _get_signature_object(original, instance, skipfirst)
  242. if result is None:
  243. return
  244. func, sig = result
  245. def checksig(*args, **kwargs):
  246. sig.bind(*args, **kwargs)
  247. _copy_func_details(func, checksig)
  248. name = original.__name__
  249. if not _isidentifier(name):
  250. name = 'funcopy'
  251. context = {'_checksig_': checksig, 'mock': mock}
  252. src = """def %s(*args, **kwargs):
  253. _checksig_(*args, **kwargs)
  254. return mock(*args, **kwargs)""" % name
  255. six.exec_(src, context)
  256. funcopy = context[name]
  257. _setup_func(funcopy, mock)
  258. return funcopy
  259. def _setup_func(funcopy, mock):
  260. funcopy.mock = mock
  261. # can't use isinstance with mocks
  262. if not _is_instance_mock(mock):
  263. return
  264. def assert_called_with(*args, **kwargs):
  265. return mock.assert_called_with(*args, **kwargs)
  266. def assert_called_once_with(*args, **kwargs):
  267. return mock.assert_called_once_with(*args, **kwargs)
  268. def assert_has_calls(*args, **kwargs):
  269. return mock.assert_has_calls(*args, **kwargs)
  270. def assert_any_call(*args, **kwargs):
  271. return mock.assert_any_call(*args, **kwargs)
  272. def reset_mock():
  273. funcopy.method_calls = _CallList()
  274. funcopy.mock_calls = _CallList()
  275. mock.reset_mock()
  276. ret = funcopy.return_value
  277. if _is_instance_mock(ret) and not ret is mock:
  278. ret.reset_mock()
  279. funcopy.called = False
  280. funcopy.call_count = 0
  281. funcopy.call_args = None
  282. funcopy.call_args_list = _CallList()
  283. funcopy.method_calls = _CallList()
  284. funcopy.mock_calls = _CallList()
  285. funcopy.return_value = mock.return_value
  286. funcopy.side_effect = mock.side_effect
  287. funcopy._mock_children = mock._mock_children
  288. funcopy.assert_called_with = assert_called_with
  289. funcopy.assert_called_once_with = assert_called_once_with
  290. funcopy.assert_has_calls = assert_has_calls
  291. funcopy.assert_any_call = assert_any_call
  292. funcopy.reset_mock = reset_mock
  293. mock._mock_delegate = funcopy
  294. def _is_magic(name):
  295. return '__%s__' % name[2:-2] == name
  296. class _SentinelObject(object):
  297. "A unique, named, sentinel object."
  298. def __init__(self, name):
  299. self.name = name
  300. def __repr__(self):
  301. return 'sentinel.%s' % self.name
  302. class _Sentinel(object):
  303. """Access attributes to return a named object, usable as a sentinel."""
  304. def __init__(self):
  305. self._sentinels = {}
  306. def __getattr__(self, name):
  307. if name == '__bases__':
  308. # Without this help(unittest.mock) raises an exception
  309. raise AttributeError
  310. return self._sentinels.setdefault(name, _SentinelObject(name))
  311. sentinel = _Sentinel()
  312. DEFAULT = sentinel.DEFAULT
  313. _missing = sentinel.MISSING
  314. _deleted = sentinel.DELETED
  315. class OldStyleClass:
  316. pass
  317. ClassType = type(OldStyleClass)
  318. def _copy(value):
  319. if type(value) in (dict, list, tuple, set):
  320. return type(value)(value)
  321. return value
  322. ClassTypes = (type,)
  323. if six.PY2:
  324. ClassTypes = (type, ClassType)
  325. _allowed_names = set((
  326. 'return_value', '_mock_return_value', 'side_effect',
  327. '_mock_side_effect', '_mock_parent', '_mock_new_parent',
  328. '_mock_name', '_mock_new_name'
  329. ))
  330. def _delegating_property(name):
  331. _allowed_names.add(name)
  332. _the_name = '_mock_' + name
  333. def _get(self, name=name, _the_name=_the_name):
  334. sig = self._mock_delegate
  335. if sig is None:
  336. return getattr(self, _the_name)
  337. return getattr(sig, name)
  338. def _set(self, value, name=name, _the_name=_the_name):
  339. sig = self._mock_delegate
  340. if sig is None:
  341. self.__dict__[_the_name] = value
  342. else:
  343. setattr(sig, name, value)
  344. return property(_get, _set)
  345. class _CallList(list):
  346. def __contains__(self, value):
  347. if not isinstance(value, list):
  348. return list.__contains__(self, value)
  349. len_value = len(value)
  350. len_self = len(self)
  351. if len_value > len_self:
  352. return False
  353. for i in range(0, len_self - len_value + 1):
  354. sub_list = self[i:i+len_value]
  355. if sub_list == value:
  356. return True
  357. return False
  358. def __repr__(self):
  359. return pprint.pformat(list(self))
  360. def _check_and_set_parent(parent, value, name, new_name):
  361. if not _is_instance_mock(value):
  362. return False
  363. if ((value._mock_name or value._mock_new_name) or
  364. (value._mock_parent is not None) or
  365. (value._mock_new_parent is not None)):
  366. return False
  367. _parent = parent
  368. while _parent is not None:
  369. # setting a mock (value) as a child or return value of itself
  370. # should not modify the mock
  371. if _parent is value:
  372. return False
  373. _parent = _parent._mock_new_parent
  374. if new_name:
  375. value._mock_new_parent = parent
  376. value._mock_new_name = new_name
  377. if name:
  378. value._mock_parent = parent
  379. value._mock_name = name
  380. return True
  381. # Internal class to identify if we wrapped an iterator object or not.
  382. class _MockIter(object):
  383. def __init__(self, obj):
  384. self.obj = iter(obj)
  385. def __iter__(self):
  386. return self
  387. def __next__(self):
  388. return next(self.obj)
  389. class Base(object):
  390. _mock_return_value = DEFAULT
  391. _mock_side_effect = None
  392. def __init__(self, *args, **kwargs):
  393. pass
  394. class NonCallableMock(Base):
  395. """A non-callable version of `Mock`"""
  396. def __new__(cls, *args, **kw):
  397. # every instance has its own class
  398. # so we can create magic methods on the
  399. # class without stomping on other mocks
  400. new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
  401. instance = object.__new__(new)
  402. return instance
  403. def __init__(
  404. self, spec=None, wraps=None, name=None, spec_set=None,
  405. parent=None, _spec_state=None, _new_name='', _new_parent=None,
  406. _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
  407. ):
  408. if _new_parent is None:
  409. _new_parent = parent
  410. __dict__ = self.__dict__
  411. __dict__['_mock_parent'] = parent
  412. __dict__['_mock_name'] = name
  413. __dict__['_mock_new_name'] = _new_name
  414. __dict__['_mock_new_parent'] = _new_parent
  415. if spec_set is not None:
  416. spec = spec_set
  417. spec_set = True
  418. if _eat_self is None:
  419. _eat_self = parent is not None
  420. self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
  421. __dict__['_mock_children'] = {}
  422. __dict__['_mock_wraps'] = wraps
  423. __dict__['_mock_delegate'] = None
  424. __dict__['_mock_called'] = False
  425. __dict__['_mock_call_args'] = None
  426. __dict__['_mock_call_count'] = 0
  427. __dict__['_mock_call_args_list'] = _CallList()
  428. __dict__['_mock_mock_calls'] = _CallList()
  429. __dict__['method_calls'] = _CallList()
  430. __dict__['_mock_unsafe'] = unsafe
  431. if kwargs:
  432. self.configure_mock(**kwargs)
  433. _safe_super(NonCallableMock, self).__init__(
  434. spec, wraps, name, spec_set, parent,
  435. _spec_state
  436. )
  437. def attach_mock(self, mock, attribute):
  438. """
  439. Attach a mock as an attribute of this one, replacing its name and
  440. parent. Calls to the attached mock will be recorded in the
  441. `method_calls` and `mock_calls` attributes of this one."""
  442. mock._mock_parent = None
  443. mock._mock_new_parent = None
  444. mock._mock_name = ''
  445. mock._mock_new_name = None
  446. setattr(self, attribute, mock)
  447. def mock_add_spec(self, spec, spec_set=False):
  448. """Add a spec to a mock. `spec` can either be an object or a
  449. list of strings. Only attributes on the `spec` can be fetched as
  450. attributes from the mock.
  451. If `spec_set` is True then only attributes on the spec can be set."""
  452. self._mock_add_spec(spec, spec_set)
  453. def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
  454. _eat_self=False):
  455. _spec_class = None
  456. _spec_signature = None
  457. if spec is not None and not _is_list(spec):
  458. if isinstance(spec, ClassTypes):
  459. _spec_class = spec
  460. else:
  461. _spec_class = _get_class(spec)
  462. res = _get_signature_object(spec,
  463. _spec_as_instance, _eat_self)
  464. _spec_signature = res and res[1]
  465. spec = dir(spec)
  466. __dict__ = self.__dict__
  467. __dict__['_spec_class'] = _spec_class
  468. __dict__['_spec_set'] = spec_set
  469. __dict__['_spec_signature'] = _spec_signature
  470. __dict__['_mock_methods'] = spec
  471. def __get_return_value(self):
  472. ret = self._mock_return_value
  473. if self._mock_delegate is not None:
  474. ret = self._mock_delegate.return_value
  475. if ret is DEFAULT:
  476. ret = self._get_child_mock(
  477. _new_parent=self, _new_name='()'
  478. )
  479. self.return_value = ret
  480. return ret
  481. def __set_return_value(self, value):
  482. if self._mock_delegate is not None:
  483. self._mock_delegate.return_value = value
  484. else:
  485. self._mock_return_value = value
  486. _check_and_set_parent(self, value, None, '()')
  487. __return_value_doc = "The value to be returned when the mock is called."
  488. return_value = property(__get_return_value, __set_return_value,
  489. __return_value_doc)
  490. @property
  491. def __class__(self):
  492. if self._spec_class is None:
  493. return type(self)
  494. return self._spec_class
  495. called = _delegating_property('called')
  496. call_count = _delegating_property('call_count')
  497. call_args = _delegating_property('call_args')
  498. call_args_list = _delegating_property('call_args_list')
  499. mock_calls = _delegating_property('mock_calls')
  500. def __get_side_effect(self):
  501. delegated = self._mock_delegate
  502. if delegated is None:
  503. return self._mock_side_effect
  504. sf = delegated.side_effect
  505. if (sf is not None and not callable(sf)
  506. and not isinstance(sf, _MockIter) and not _is_exception(sf)):
  507. sf = _MockIter(sf)
  508. delegated.side_effect = sf
  509. return sf
  510. def __set_side_effect(self, value):
  511. value = _try_iter(value)
  512. delegated = self._mock_delegate
  513. if delegated is None:
  514. self._mock_side_effect = value
  515. else:
  516. delegated.side_effect = value
  517. side_effect = property(__get_side_effect, __set_side_effect)
  518. def reset_mock(self, visited=None):
  519. "Restore the mock object to its initial state."
  520. if visited is None:
  521. visited = []
  522. if id(self) in visited:
  523. return
  524. visited.append(id(self))
  525. self.called = False
  526. self.call_args = None
  527. self.call_count = 0
  528. self.mock_calls = _CallList()
  529. self.call_args_list = _CallList()
  530. self.method_calls = _CallList()
  531. for child in self._mock_children.values():
  532. if isinstance(child, _SpecState):
  533. continue
  534. child.reset_mock(visited)
  535. ret = self._mock_return_value
  536. if _is_instance_mock(ret) and ret is not self:
  537. ret.reset_mock(visited)
  538. def configure_mock(self, **kwargs):
  539. """Set attributes on the mock through keyword arguments.
  540. Attributes plus return values and side effects can be set on child
  541. mocks using standard dot notation and unpacking a dictionary in the
  542. method call:
  543. >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
  544. >>> mock.configure_mock(**attrs)"""
  545. for arg, val in sorted(kwargs.items(),
  546. # we sort on the number of dots so that
  547. # attributes are set before we set attributes on
  548. # attributes
  549. key=lambda entry: entry[0].count('.')):
  550. args = arg.split('.')
  551. final = args.pop()
  552. obj = self
  553. for entry in args:
  554. obj = getattr(obj, entry)
  555. setattr(obj, final, val)
  556. def __getattr__(self, name):
  557. if name in ('_mock_methods', '_mock_unsafe'):
  558. raise AttributeError(name)
  559. elif self._mock_methods is not None:
  560. if name not in self._mock_methods or name in _all_magics:
  561. raise AttributeError("Mock object has no attribute %r" % name)
  562. elif _is_magic(name):
  563. raise AttributeError(name)
  564. if not self._mock_unsafe:
  565. if name.startswith(('assert', 'assret')):
  566. raise AttributeError(name)
  567. result = self._mock_children.get(name)
  568. if result is _deleted:
  569. raise AttributeError(name)
  570. elif result is None:
  571. wraps = None
  572. if self._mock_wraps is not None:
  573. # XXXX should we get the attribute without triggering code
  574. # execution?
  575. wraps = getattr(self._mock_wraps, name)
  576. result = self._get_child_mock(
  577. parent=self, name=name, wraps=wraps, _new_name=name,
  578. _new_parent=self
  579. )
  580. self._mock_children[name] = result
  581. elif isinstance(result, _SpecState):
  582. result = create_autospec(
  583. result.spec, result.spec_set, result.instance,
  584. result.parent, result.name
  585. )
  586. self._mock_children[name] = result
  587. return result
  588. def __repr__(self):
  589. _name_list = [self._mock_new_name]
  590. _parent = self._mock_new_parent
  591. last = self
  592. dot = '.'
  593. if _name_list == ['()']:
  594. dot = ''
  595. seen = set()
  596. while _parent is not None:
  597. last = _parent
  598. _name_list.append(_parent._mock_new_name + dot)
  599. dot = '.'
  600. if _parent._mock_new_name == '()':
  601. dot = ''
  602. _parent = _parent._mock_new_parent
  603. # use ids here so as not to call __hash__ on the mocks
  604. if id(_parent) in seen:
  605. break
  606. seen.add(id(_parent))
  607. _name_list = list(reversed(_name_list))
  608. _first = last._mock_name or 'mock'
  609. if len(_name_list) > 1:
  610. if _name_list[1] not in ('()', '().'):
  611. _first += '.'
  612. _name_list[0] = _first
  613. name = ''.join(_name_list)
  614. name_string = ''
  615. if name not in ('mock', 'mock.'):
  616. name_string = ' name=%r' % name
  617. spec_string = ''
  618. if self._spec_class is not None:
  619. spec_string = ' spec=%r'
  620. if self._spec_set:
  621. spec_string = ' spec_set=%r'
  622. spec_string = spec_string % self._spec_class.__name__
  623. return "<%s%s%s id='%s'>" % (
  624. type(self).__name__,
  625. name_string,
  626. spec_string,
  627. id(self)
  628. )
  629. def __dir__(self):
  630. """Filter the output of `dir(mock)` to only useful members."""
  631. if not mock.FILTER_DIR and getattr(object, '__dir__', None):
  632. # object.__dir__ is not in 2.7
  633. return object.__dir__(self)
  634. extras = self._mock_methods or []
  635. from_type = dir(type(self))
  636. from_dict = list(self.__dict__)
  637. if mock.FILTER_DIR:
  638. # object.__dir__ is not in 2.7
  639. from_type = [e for e in from_type if not e.startswith('_')]
  640. from_dict = [e for e in from_dict if not e.startswith('_') or
  641. _is_magic(e)]
  642. return sorted(set(extras + from_type + from_dict +
  643. list(self._mock_children)))
  644. def __setattr__(self, name, value):
  645. if name in _allowed_names:
  646. # property setters go through here
  647. return object.__setattr__(self, name, value)
  648. elif (self._spec_set and self._mock_methods is not None and
  649. name not in self._mock_methods and
  650. name not in self.__dict__):
  651. raise AttributeError("Mock object has no attribute '%s'" % name)
  652. elif name in _unsupported_magics:
  653. msg = 'Attempting to set unsupported magic method %r.' % name
  654. raise AttributeError(msg)
  655. elif name in _all_magics:
  656. if self._mock_methods is not None and name not in self._mock_methods:
  657. raise AttributeError("Mock object has no attribute '%s'" % name)
  658. if not _is_instance_mock(value):
  659. setattr(type(self), name, _get_method(name, value))
  660. original = value
  661. value = lambda *args, **kw: original(self, *args, **kw)
  662. else:
  663. # only set _new_name and not name so that mock_calls is tracked
  664. # but not method calls
  665. _check_and_set_parent(self, value, None, name)
  666. setattr(type(self), name, value)
  667. self._mock_children[name] = value
  668. elif name == '__class__':
  669. self._spec_class = value
  670. return
  671. else:
  672. if _check_and_set_parent(self, value, name, name):
  673. self._mock_children[name] = value
  674. return object.__setattr__(self, name, value)
  675. def __delattr__(self, name):
  676. if name in _all_magics and name in type(self).__dict__:
  677. delattr(type(self), name)
  678. if name not in self.__dict__:
  679. # for magic methods that are still MagicProxy objects and
  680. # not set on the instance itself
  681. return
  682. if name in self.__dict__:
  683. object.__delattr__(self, name)
  684. obj = self._mock_children.get(name, _missing)
  685. if obj is _deleted:
  686. raise AttributeError(name)
  687. if obj is not _missing:
  688. del self._mock_children[name]
  689. self._mock_children[name] = _deleted
  690. def _format_mock_call_signature(self, args, kwargs):
  691. name = self._mock_name or 'mock'
  692. return _format_call_signature(name, args, kwargs)
  693. def _format_mock_failure_message(self, args, kwargs):
  694. message = 'Expected call: %s\nActual call: %s'
  695. expected_string = self._format_mock_call_signature(args, kwargs)
  696. call_args = self.call_args
  697. if len(call_args) == 3:
  698. call_args = call_args[1:]
  699. actual_string = self._format_mock_call_signature(*call_args)
  700. return message % (expected_string, actual_string)
  701. def _call_matcher(self, _call):
  702. """
  703. Given a call (or simply a (args, kwargs) tuple), return a
  704. comparison key suitable for matching with other calls.
  705. This is a best effort method which relies on the spec's signature,
  706. if available, or falls back on the arguments themselves.
  707. """
  708. sig = self._spec_signature
  709. if sig is not None:
  710. if len(_call) == 2:
  711. name = ''
  712. args, kwargs = _call
  713. else:
  714. name, args, kwargs = _call
  715. try:
  716. return name, sig.bind(*args, **kwargs)
  717. except TypeError as e:
  718. e.__traceback__ = None
  719. return e
  720. else:
  721. return _call
  722. def assert_not_called(_mock_self):
  723. """assert that the mock was never called.
  724. """
  725. self = _mock_self
  726. if self.call_count != 0:
  727. msg = ("Expected '%s' to not have been called. Called %s times." %
  728. (self._mock_name or 'mock', self.call_count))
  729. raise AssertionError(msg)
  730. def assert_called(_mock_self):
  731. """assert that the mock was called at least once
  732. """
  733. self = _mock_self
  734. if self.call_count == 0:
  735. msg = ("Expected '%s' to have been called." %
  736. self._mock_name or 'mock')
  737. raise AssertionError(msg)
  738. def assert_called_once(_mock_self):
  739. """assert that the mock was called only once.
  740. """
  741. self = _mock_self
  742. if not self.call_count == 1:
  743. msg = ("Expected '%s' to have been called once. Called %s times." %
  744. (self._mock_name or 'mock', self.call_count))
  745. raise AssertionError(msg)
  746. def assert_called_with(_mock_self, *args, **kwargs):
  747. """assert that the mock was called with the specified arguments.
  748. Raises an AssertionError if the args and keyword args passed in are
  749. different to the last call to the mock."""
  750. self = _mock_self
  751. if self.call_args is None:
  752. expected = self._format_mock_call_signature(args, kwargs)
  753. raise AssertionError('Expected call: %s\nNot called' % (expected,))
  754. def _error_message(cause):
  755. msg = self._format_mock_failure_message(args, kwargs)
  756. if six.PY2 and cause is not None:
  757. # Tack on some diagnostics for Python without __cause__
  758. msg = '%s\n%s' % (msg, str(cause))
  759. return msg
  760. expected = self._call_matcher((args, kwargs))
  761. actual = self._call_matcher(self.call_args)
  762. if expected != actual:
  763. cause = expected if isinstance(expected, Exception) else None
  764. six.raise_from(AssertionError(_error_message(cause)), cause)
  765. def assert_called_once_with(_mock_self, *args, **kwargs):
  766. """assert that the mock was called exactly once and with the specified
  767. arguments."""
  768. self = _mock_self
  769. if not self.call_count == 1:
  770. msg = ("Expected '%s' to be called once. Called %s times." %
  771. (self._mock_name or 'mock', self.call_count))
  772. raise AssertionError(msg)
  773. return self.assert_called_with(*args, **kwargs)
  774. def assert_has_calls(self, calls, any_order=False):
  775. """assert the mock has been called with the specified calls.
  776. The `mock_calls` list is checked for the calls.
  777. If `any_order` is False (the default) then the calls must be
  778. sequential. There can be extra calls before or after the
  779. specified calls.
  780. If `any_order` is True then the calls can be in any order, but
  781. they must all appear in `mock_calls`."""
  782. expected = [self._call_matcher(c) for c in calls]
  783. cause = expected if isinstance(expected, Exception) else None
  784. all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
  785. if not any_order:
  786. if expected not in all_calls:
  787. six.raise_from(AssertionError(
  788. 'Calls not found.\nExpected: %r\n'
  789. 'Actual: %r' % (_CallList(calls), self.mock_calls)
  790. ), cause)
  791. return
  792. all_calls = list(all_calls)
  793. not_found = []
  794. for kall in expected:
  795. try:
  796. all_calls.remove(kall)
  797. except ValueError:
  798. not_found.append(kall)
  799. if not_found:
  800. six.raise_from(AssertionError(
  801. '%r not all found in call list' % (tuple(not_found),)
  802. ), cause)
  803. def assert_any_call(self, *args, **kwargs):
  804. """assert the mock has been called with the specified arguments.
  805. The assert passes if the mock has *ever* been called, unlike
  806. `assert_called_with` and `assert_called_once_with` that only pass if
  807. the call is the most recent one."""
  808. expected = self._call_matcher((args, kwargs))
  809. actual = [self._call_matcher(c) for c in self.call_args_list]
  810. if expected not in actual:
  811. cause = expected if isinstance(expected, Exception) else None
  812. expected_string = self._format_mock_call_signature(args, kwargs)
  813. six.raise_from(AssertionError(
  814. '%s call not found' % expected_string
  815. ), cause)
  816. def _get_child_mock(self, **kw):
  817. """Create the child mocks for attributes and return value.
  818. By default child mocks will be the same type as the parent.
  819. Subclasses of Mock may want to override this to customize the way
  820. child mocks are made.
  821. For non-callable mocks the callable variant will be used (rather than
  822. any custom subclass)."""
  823. _type = type(self)
  824. if not issubclass(_type, CallableMixin):
  825. if issubclass(_type, NonCallableMagicMock):
  826. klass = MagicMock
  827. elif issubclass(_type, NonCallableMock) :
  828. klass = Mock
  829. else:
  830. klass = _type.__mro__[1]
  831. return klass(**kw)
  832. def _try_iter(obj):
  833. if obj is None:
  834. return obj
  835. if _is_exception(obj):
  836. return obj
  837. if _callable(obj):
  838. return obj
  839. try:
  840. return iter(obj)
  841. except TypeError:
  842. # XXXX backwards compatibility
  843. # but this will blow up on first call - so maybe we should fail early?
  844. return obj
  845. class CallableMixin(Base):
  846. def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
  847. wraps=None, name=None, spec_set=None, parent=None,
  848. _spec_state=None, _new_name='', _new_parent=None, **kwargs):
  849. self.__dict__['_mock_return_value'] = return_value
  850. _safe_super(CallableMixin, self).__init__(
  851. spec, wraps, name, spec_set, parent,
  852. _spec_state, _new_name, _new_parent, **kwargs
  853. )
  854. self.side_effect = side_effect
  855. def _mock_check_sig(self, *args, **kwargs):
  856. # stub method that can be replaced with one with a specific signature
  857. pass
  858. def __call__(_mock_self, *args, **kwargs):
  859. # can't use self in-case a function / method we are mocking uses self
  860. # in the signature
  861. _mock_self._mock_check_sig(*args, **kwargs)
  862. return _mock_self._mock_call(*args, **kwargs)
  863. def _mock_call(_mock_self, *args, **kwargs):
  864. self = _mock_self
  865. self.called = True
  866. self.call_count += 1
  867. _new_name = self._mock_new_name
  868. _new_parent = self._mock_new_parent
  869. _call = _Call((args, kwargs), two=True)
  870. self.call_args = _call
  871. self.call_args_list.append(_call)
  872. self.mock_calls.append(_Call(('', args, kwargs)))
  873. seen = set()
  874. skip_next_dot = _new_name == '()'
  875. do_method_calls = self._mock_parent is not None
  876. name = self._mock_name
  877. while _new_parent is not None:
  878. this_mock_call = _Call((_new_name, args, kwargs))
  879. if _new_parent._mock_new_name:
  880. dot = '.'
  881. if skip_next_dot:
  882. dot = ''
  883. skip_next_dot = False
  884. if _new_parent._mock_new_name == '()':
  885. skip_next_dot = True
  886. _new_name = _new_parent._mock_new_name + dot + _new_name
  887. if do_method_calls:
  888. if _new_name == name:
  889. this_method_call = this_mock_call
  890. else:
  891. this_method_call = _Call((name, args, kwargs))
  892. _new_parent.method_calls.append(this_method_call)
  893. do_method_calls = _new_parent._mock_parent is not None
  894. if do_method_calls:
  895. name = _new_parent._mock_name + '.' + name
  896. _new_parent.mock_calls.append(this_mock_call)
  897. _new_parent = _new_parent._mock_new_parent
  898. # use ids here so as not to call __hash__ on the mocks
  899. _new_parent_id = id(_new_parent)
  900. if _new_parent_id in seen:
  901. break
  902. seen.add(_new_parent_id)
  903. ret_val = DEFAULT
  904. effect = self.side_effect
  905. if effect is not None:
  906. if _is_exception(effect):
  907. raise effect
  908. if not _callable(effect):
  909. result = next(effect)
  910. if _is_exception(result):
  911. raise result
  912. if result is DEFAULT:
  913. result = self.return_value
  914. return result
  915. ret_val = effect(*args, **kwargs)
  916. if (self._mock_wraps is not None and
  917. self._mock_return_value is DEFAULT):
  918. return self._mock_wraps(*args, **kwargs)
  919. if ret_val is DEFAULT:
  920. ret_val = self.return_value
  921. return ret_val
  922. class Mock(CallableMixin, NonCallableMock):
  923. """
  924. Create a new `Mock` object. `Mock` takes several optional arguments
  925. that specify the behaviour of the Mock object:
  926. * `spec`: This can be either a list of strings or an existing object (a
  927. class or instance) that acts as the specification for the mock object. If
  928. you pass in an object then a list of strings is formed by calling dir on
  929. the object (excluding unsupported magic attributes and methods). Accessing
  930. any attribute not in this list will raise an `AttributeError`.
  931. If `spec` is an object (rather than a list of strings) then
  932. `mock.__class__` returns the class of the spec object. This allows mocks
  933. to pass `isinstance` tests.
  934. * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
  935. or get an attribute on the mock that isn't on the object passed as
  936. `spec_set` will raise an `AttributeError`.
  937. * `side_effect`: A function to be called whenever the Mock is called. See
  938. the `side_effect` attribute. Useful for raising exceptions or
  939. dynamically changing return values. The function is called with the same
  940. arguments as the mock, and unless it returns `DEFAULT`, the return
  941. value of this function is used as the return value.
  942. Alternatively `side_effect` can be an exception class or instance. In
  943. this case the exception will be raised when the mock is called.
  944. If `side_effect` is an iterable then each call to the mock will return
  945. the next value from the iterable. If any of the members of the iterable
  946. are exceptions they will be raised instead of returned.
  947. * `return_value`: The value returned when the mock is called. By default
  948. this is a new Mock (created on first access). See the
  949. `return_value` attribute.
  950. * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
  951. calling the Mock will pass the call through to the wrapped object
  952. (returning the real result). Attribute access on the mock will return a
  953. Mock object that wraps the corresponding attribute of the wrapped object
  954. (so attempting to access an attribute that doesn't exist will raise an
  955. `AttributeError`).
  956. If the mock has an explicit `return_value` set then calls are not passed
  957. to the wrapped object and the `return_value` is returned instead.
  958. * `name`: If the mock has a name then it will be used in the repr of the
  959. mock. This can be useful for debugging. The name is propagated to child
  960. mocks.
  961. Mocks can also be called with arbitrary keyword arguments. These will be
  962. used to set attributes on the mock after it is created.
  963. """
  964. def _dot_lookup(thing, comp, import_path):
  965. try:
  966. return getattr(thing, comp)
  967. except AttributeError:
  968. __import__(import_path)
  969. return getattr(thing, comp)
  970. def _importer(target):
  971. components = target.split('.')
  972. import_path = components.pop(0)
  973. thing = __import__(import_path)
  974. for comp in components:
  975. import_path += ".%s" % comp
  976. thing = _dot_lookup(thing, comp, import_path)
  977. return thing
  978. def _is_started(patcher):
  979. # XXXX horrible
  980. return hasattr(patcher, 'is_local')
  981. class _patch(object):
  982. attribute_name = None
  983. _active_patches = []
  984. def __init__(
  985. self, getter, attribute, new, spec, create,
  986. spec_set, autospec, new_callable, kwargs
  987. ):
  988. if new_callable is not None:
  989. if new is not DEFAULT:
  990. raise ValueError(
  991. "Cannot use 'new' and 'new_callable' together"
  992. )
  993. if autospec is not None:
  994. raise ValueError(
  995. "Cannot use 'autospec' and 'new_callable' together"
  996. )
  997. self.getter = getter
  998. self.attribute = attribute
  999. self.new = new
  1000. self.new_callable = new_callable
  1001. self.spec = spec
  1002. self.create = create
  1003. self.has_local = False
  1004. self.spec_set = spec_set
  1005. self.autospec = autospec
  1006. self.kwargs = kwargs
  1007. self.additional_patchers = []
  1008. def copy(self):
  1009. patcher = _patch(
  1010. self.getter, self.attribute, self.new, self.spec,
  1011. self.create, self.spec_set,
  1012. self.autospec, self.new_callable, self.kwargs
  1013. )
  1014. patcher.attribute_name = self.attribute_name
  1015. patcher.additional_patchers = [
  1016. p.copy() for p in self.additional_patchers
  1017. ]
  1018. return patcher
  1019. def __call__(self, func):
  1020. if isinstance(func, ClassTypes):
  1021. return self.decorate_class(func)
  1022. return self.decorate_callable(func)
  1023. def decorate_class(self, klass):
  1024. for attr in dir(klass):
  1025. if not attr.startswith(patch.TEST_PREFIX):
  1026. continue
  1027. attr_value = getattr(klass, attr)
  1028. if not hasattr(attr_value, "__call__"):
  1029. continue
  1030. patcher = self.copy()
  1031. setattr(klass, attr, patcher(attr_value))
  1032. return klass
  1033. def decorate_callable(self, func):
  1034. if hasattr(func, 'patchings'):
  1035. func.patchings.append(self)
  1036. return func
  1037. @wraps(func)
  1038. def patched(*args, **keywargs):
  1039. extra_args = []
  1040. entered_patchers = []
  1041. exc_info = tuple()
  1042. try:
  1043. for patching in patched.patchings:
  1044. arg = patching.__enter__()
  1045. entered_patchers.append(patching)
  1046. if patching.attribute_name is not None:
  1047. keywargs.update(arg)
  1048. elif patching.new is DEFAULT:
  1049. extra_args.append(arg)
  1050. args += tuple(extra_args)
  1051. return func(*args, **keywargs)
  1052. except:
  1053. if (patching not in entered_patchers and
  1054. _is_started(patching)):
  1055. # the patcher may have been started, but an exception
  1056. # raised whilst entering one of its additional_patchers
  1057. entered_patchers.append(patching)
  1058. # Pass the exception to __exit__
  1059. exc_info = sys.exc_info()
  1060. # re-raise the exception
  1061. raise
  1062. finally:
  1063. for patching in reversed(entered_patchers):
  1064. patching.__exit__(*exc_info)
  1065. patched.patchings = [self]
  1066. return patched
  1067. def get_original(self):
  1068. target = self.getter()
  1069. name = self.attribute
  1070. original = DEFAULT
  1071. local = False
  1072. try:
  1073. original = target.__dict__[name]
  1074. except (AttributeError, KeyError):
  1075. original = getattr(target, name, DEFAULT)
  1076. else:
  1077. local = True
  1078. if name in _builtins and isinstance(target, ModuleType):
  1079. self.create = True
  1080. if not self.create and original is DEFAULT:
  1081. raise AttributeError(
  1082. "%s does not have the attribute %r" % (target, name)
  1083. )
  1084. return original, local
  1085. def __enter__(self):
  1086. """Perform the patch."""
  1087. new, spec, spec_set = self.new, self.spec, self.spec_set
  1088. autospec, kwargs = self.autospec, self.kwargs
  1089. new_callable = self.new_callable
  1090. self.target = self.getter()
  1091. # normalise False to None
  1092. if spec is False:
  1093. spec = None
  1094. if spec_set is False:
  1095. spec_set = None
  1096. if autospec is False:
  1097. autospec = None
  1098. if spec is not None and autospec is not None:
  1099. raise TypeError("Can't specify spec and autospec")
  1100. if ((spec is not None or autospec is not None) and
  1101. spec_set not in (True, None)):
  1102. raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
  1103. original, local = self.get_original()
  1104. if new is DEFAULT and autospec is None:
  1105. inherit = False
  1106. if spec is True:
  1107. # set spec to the object we are replacing
  1108. spec = original
  1109. if spec_set is True:
  1110. spec_set = original
  1111. spec = None
  1112. elif spec is not None:
  1113. if spec_set is True:
  1114. spec_set = spec
  1115. spec = None
  1116. elif spec_set is True:
  1117. spec_set = original
  1118. if spec is not None or spec_set is not None:
  1119. if original is DEFAULT:
  1120. raise TypeError("Can't use 'spec' with create=True")
  1121. if isinstance(original, ClassTypes):
  1122. # If we're patching out a class and there is a spec
  1123. inherit = True
  1124. Klass = MagicMock
  1125. _kwargs = {}
  1126. if new_callable is not None:
  1127. Klass = new_callable
  1128. elif spec is not None or spec_set is not None:
  1129. this_spec = spec
  1130. if spec_set is not None:
  1131. this_spec = spec_set
  1132. if _is_list(this_spec):
  1133. not_callable = '__call__' not in this_spec
  1134. else:
  1135. not_callable = not _callable(this_spec)
  1136. if not_callable:
  1137. Klass = NonCallableMagicMock
  1138. if spec is not None:
  1139. _kwargs['spec'] = spec
  1140. if spec_set is not None:
  1141. _kwargs['spec_set'] = spec_set
  1142. # add a name to mocks
  1143. if (isinstance(Klass, type) and
  1144. issubclass(Klass, NonCallableMock) and self.attribute):
  1145. _kwargs['name'] = self.attribute
  1146. _kwargs.update(kwargs)
  1147. new = Klass(**_kwargs)
  1148. if inherit and _is_instance_mock(new):
  1149. # we can only tell if the instance should be callable if the
  1150. # spec is not a list
  1151. this_spec = spec
  1152. if spec_set is not None:
  1153. this_spec = spec_set
  1154. if (not _is_list(this_spec) and not
  1155. _instance_callable(this_spec)):
  1156. Klass = NonCallableMagicMock
  1157. _kwargs.pop('name')
  1158. new.return_value = Klass(_new_parent=new, _new_name='()',
  1159. **_kwargs)
  1160. elif autospec is not None:
  1161. # spec is ignored, new *must* be default, spec_set is treated
  1162. # as a boolean. Should we check spec is not None and that spec_set
  1163. # is a bool?
  1164. if new is not DEFAULT:
  1165. raise TypeError(
  1166. "autospec creates the mock for you. Can't specify "
  1167. "autospec and new."
  1168. )
  1169. if original is DEFAULT:
  1170. raise TypeError("Can't use 'autospec' with create=True")
  1171. spec_set = bool(spec_set)
  1172. if autospec is True:
  1173. autospec = original
  1174. new = create_autospec(autospec, spec_set=spec_set,
  1175. _name=self.attribute, **kwargs)
  1176. elif kwargs:
  1177. # can't set keyword args when we aren't creating the mock
  1178. # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
  1179. raise TypeError("Can't pass kwargs to a mock we aren't creating")
  1180. new_attr = new
  1181. self.temp_original = original
  1182. self.is_local = local
  1183. setattr(self.target, self.attribute, new_attr)
  1184. if self.attribute_name is not None:
  1185. extra_args = {}
  1186. if self.new is DEFAULT:
  1187. extra_args[self.attribute_name] = new
  1188. for patching in self.additional_patchers:
  1189. arg = patching.__enter__()
  1190. if patching.new is DEFAULT:
  1191. extra_args.update(arg)
  1192. return extra_args
  1193. return new
  1194. def __exit__(self, *exc_info):
  1195. """Undo the patch."""
  1196. if not _is_started(self):
  1197. raise RuntimeError('stop called on unstarted patcher')
  1198. if self.is_local and self.temp_original is not DEFAULT:
  1199. setattr(self.target, self.attribute, self.temp_original)
  1200. else:
  1201. delattr(self.target, self.attribute)
  1202. if not self.create and (not hasattr(self.target, self.attribute) or
  1203. self.attribute in ('__doc__', '__module__',
  1204. '__defaults__', '__annotations__',
  1205. '__kwdefaults__')):
  1206. # needed for proxy objects like django settings
  1207. setattr(self.target, self.attribute, self.temp_original)
  1208. del self.temp_original
  1209. del self.is_local
  1210. del self.target
  1211. for patcher in reversed(self.additional_patchers):
  1212. if _is_started(patcher):
  1213. patcher.__exit__(*exc_info)
  1214. def start(self):
  1215. """Activate a patch, returning any created mock."""
  1216. result = self.__enter__()
  1217. self._active_patches.append(self)
  1218. return result
  1219. def stop(self):
  1220. """Stop an active patch."""
  1221. try:
  1222. self._active_patches.remove(self)
  1223. except ValueError:
  1224. # If the patch hasn't been started this will fail
  1225. pass
  1226. return self.__exit__()
  1227. def _get_target(target):
  1228. try:
  1229. target, attribute = target.rsplit('.', 1)
  1230. except (TypeError, ValueError):
  1231. raise TypeError("Need a valid target to patch. You supplied: %r" %
  1232. (target,))
  1233. getter = lambda: _importer(target)
  1234. return getter, attribute
  1235. def _patch_object(
  1236. target, attribute, new=DEFAULT, spec=None,
  1237. create=False, spec_set=None, autospec=None,
  1238. new_callable=None, **kwargs
  1239. ):
  1240. """
  1241. patch the named member (`attribute`) on an object (`target`) with a mock
  1242. object.
  1243. `patch.object` can be used as a decorator, class decorator or a context
  1244. manager. Arguments `new`, `spec`, `create`, `spec_set`,
  1245. `autospec` and `new_callable` have the same meaning as for `patch`. Like
  1246. `patch`, `patch.object` takes arbitrary keyword arguments for configuring
  1247. the mock object it creates.
  1248. When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
  1249. for choosing which methods to wrap.
  1250. """
  1251. getter = lambda: target
  1252. return _patch(
  1253. getter, attribute, new, spec, create,
  1254. spec_set, autospec, new_callable, kwargs
  1255. )
  1256. def _patch_multiple(target, spec=None, create=False, spec_set=None,
  1257. autospec=None, new_callable=None, **kwargs):
  1258. """Perform multiple patches in a single call. It takes the object to be
  1259. patched (either as an object or a string to fetch the object by importing)
  1260. and keyword arguments for the patches::
  1261. with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
  1262. ...
  1263. Use `DEFAULT` as the value if you want `patch.multiple` to create
  1264. mocks for you. In this case the created mocks are passed into a decorated
  1265. function by keyword, and a dictionary is returned when `patch.multiple` is
  1266. used as a context manager.
  1267. `patch.multiple` can be used as a decorator, class decorator or a context
  1268. manager. The arguments `spec`, `spec_set`, `create`,
  1269. `autospec` and `new_callable` have the same meaning as for `patch`. These
  1270. arguments will be applied to *all* patches done by `patch.multiple`.
  1271. When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
  1272. for choosing which methods to wrap.
  1273. """
  1274. if type(target) in (unicode, str):
  1275. getter = lambda: _importer(target)
  1276. else:
  1277. getter = lambda: target
  1278. if not kwargs:
  1279. raise ValueError(
  1280. 'Must supply at least one keyword argument with patch.multiple'
  1281. )
  1282. # need to wrap in a list for python 3, where items is a view
  1283. items = list(kwargs.items())
  1284. attribute, new = items[0]
  1285. patcher = _patch(
  1286. getter, attribute, new, spec, create, spec_set,
  1287. autospec, new_callable, {}
  1288. )
  1289. patcher.attribute_name = attribute
  1290. for attribute, new in items[1:]:
  1291. this_patcher = _patch(
  1292. getter, attribute, new, spec, create, spec_set,
  1293. autospec, new_callable, {}
  1294. )
  1295. this_patcher.attribute_name = attribute
  1296. patcher.additional_patchers.append(this_patcher)
  1297. return patcher
  1298. def patch(
  1299. target, new=DEFAULT, spec=None, create=False,
  1300. spec_set=None, autospec=None, new_callable=None, **kwargs
  1301. ):
  1302. """
  1303. `patch` acts as a function decorator, class decorator or a context
  1304. manager. Inside the body of the function or with statement, the `target`
  1305. is patched with a `new` object. When the function/with statement exits
  1306. the patch is undone.
  1307. If `new` is omitted, then the target is replaced with a
  1308. `MagicMock`. If `patch` is used as a decorator and `new` is
  1309. omitted, the created mock is passed in as an extra argument to the
  1310. decorated function. If `patch` is used as a context manager the created
  1311. mock is returned by the context manager.
  1312. `target` should be a string in the form `'package.module.ClassName'`. The
  1313. `target` is imported and the specified object replaced with the `new`
  1314. object, so the `target` must be importable from the environment you are
  1315. calling `patch` from. The target is imported when the decorated function
  1316. is executed, not at decoration time.
  1317. The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
  1318. if patch is creating one for you.
  1319. In addition you can pass `spec=True` or `spec_set=True`, which causes
  1320. patch to pass in the object being mocked as the spec/spec_set object.
  1321. `new_callable` allows you to specify a different class, or callable object,
  1322. that will be called to create the `new` object. By default `MagicMock` is
  1323. used.
  1324. A more powerful form of `spec` is `autospec`. If you set `autospec=True`
  1325. then the mock will be created with a spec from the object being replaced.
  1326. All attributes of the mock will also have the spec of the corresponding
  1327. attribute of the object being replaced. Methods and functions being
  1328. mocked will have their arguments checked and will raise a `TypeError` if
  1329. they are called with the wrong signature. For mocks replacing a class,
  1330. their return value (the 'instance') will have the same spec as the class.
  1331. Instead of `autospec=True` you can pass `autospec=some_object` to use an
  1332. arbitrary object as the spec instead of the one being replaced.
  1333. By default `patch` will fail to replace attributes that don't exist. If
  1334. you pass in `create=True`, and the attribute doesn't exist, patch will
  1335. create the attribute for you when the patched function is called, and
  1336. delete it again afterwards. This is useful for writing tests against
  1337. attributes that your production code creates at runtime. It is off by
  1338. default because it can be dangerous. With it switched on you can write
  1339. passing tests against APIs that don't actually exist!
  1340. Patch can be used as a `TestCase` class decorator. It works by
  1341. decorating each test method in the class. This reduces the boilerplate
  1342. code when your test methods share a common patchings set. `patch` finds
  1343. tests by looking for method names that start with `patch.TEST_PREFIX`.
  1344. By default this is `test`, which matches the way `unittest` finds tests.
  1345. You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
  1346. Patch can be used as a context manager, with the with statement. Here the
  1347. patching applies to the indented block after the with statement. If you
  1348. use "as" then the patched object will be bound to the name after the
  1349. "as"; very useful if `patch` is creating a mock object for you.
  1350. `patch` takes arbitrary keyword arguments. These will be passed to
  1351. the `Mock` (or `new_callable`) on construction.
  1352. `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
  1353. available for alternate use-cases.
  1354. """
  1355. getter, attribute = _get_target(target)
  1356. return _patch(
  1357. getter, attribute, new, spec, create,
  1358. spec_set, autospec, new_callable, kwargs
  1359. )
  1360. class _patch_dict(object):
  1361. """
  1362. Patch a dictionary, or dictionary like object, and restore the dictionary
  1363. to its original state after the test.
  1364. `in_dict` can be a dictionary or a mapping like container. If it is a
  1365. mapping then it must at least support getting, setting and deleting items
  1366. plus iterating over keys.
  1367. `in_dict` can also be a string specifying the name of the dictionary, which
  1368. will then be fetched by importing it.
  1369. `values` can be a dictionary of values to set in the dictionary. `values`
  1370. can also be an iterable of `(key, value)` pairs.
  1371. If `clear` is True then the dictionary will be cleared before the new
  1372. values are set.
  1373. `patch.dict` can also be called with arbitrary keyword arguments to set
  1374. values in the dictionary::
  1375. with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
  1376. ...
  1377. `patch.dict` can be used as a context manager, decorator or class
  1378. decorator. When used as a class decorator `patch.dict` honours
  1379. `patch.TEST_PREFIX` for choosing which methods to wrap.
  1380. """
  1381. def __init__(self, in_dict, values=(), clear=False, **kwargs):
  1382. if isinstance(in_dict, basestring):
  1383. in_dict = _importer(in_dict)
  1384. self.in_dict = in_dict
  1385. # support any argument supported by dict(...) constructor
  1386. self.values = dict(values)
  1387. self.values.update(kwargs)
  1388. self.clear = clear
  1389. self._original = None
  1390. def __call__(self, f):
  1391. if isinstance(f, ClassTypes):
  1392. return self.decorate_class(f)
  1393. @wraps(f)
  1394. def _inner(*args, **kw):
  1395. self._patch_dict()
  1396. try:
  1397. return f(*args, **kw)
  1398. finally:
  1399. self._unpatch_dict()
  1400. return _inner
  1401. def decorate_class(self, klass):
  1402. for attr in dir(klass):
  1403. attr_value = getattr(klass, attr)
  1404. if (attr.startswith(patch.TEST_PREFIX) and
  1405. hasattr(attr_value, "__call__")):
  1406. decorator = _patch_dict(self.in_dict, self.values, self.clear)
  1407. decorated = decorator(attr_value)
  1408. setattr(klass, attr, decorated)
  1409. return klass
  1410. def __enter__(self):
  1411. """Patch the dict."""
  1412. self._patch_dict()
  1413. def _patch_dict(self):
  1414. values = self.values
  1415. in_dict = self.in_dict
  1416. clear = self.clear
  1417. try:
  1418. original = in_dict.copy()
  1419. except AttributeError:
  1420. # dict like object with no copy method
  1421. # must support iteration over keys
  1422. original = {}
  1423. for key in in_dict:
  1424. original[key] = in_dict[key]
  1425. self._original = original
  1426. if clear:
  1427. _clear_dict(in_dict)
  1428. try:
  1429. in_dict.update(values)
  1430. except AttributeError:
  1431. # dict like object with no update method
  1432. for key in values:
  1433. in_dict[key] = values[key]
  1434. def _unpatch_dict(self):
  1435. in_dict = self.in_dict
  1436. original = self._original
  1437. _clear_dict(in_dict)
  1438. try:
  1439. in_dict.update(original)
  1440. except AttributeError:
  1441. for key in original:
  1442. in_dict[key] = original[key]
  1443. def __exit__(self, *args):
  1444. """Unpatch the dict."""
  1445. self._unpatch_dict()
  1446. return False
  1447. start = __enter__
  1448. stop = __exit__
  1449. def _clear_dict(in_dict):
  1450. try:
  1451. in_dict.clear()
  1452. except AttributeError:
  1453. keys = list(in_dict)
  1454. for key in keys:
  1455. del in_dict[key]
  1456. def _patch_stopall():
  1457. """Stop all active patches. LIFO to unroll nested patches."""
  1458. for patch in reversed(_patch._active_patches):
  1459. patch.stop()
  1460. patch.object = _patch_object
  1461. patch.dict = _patch_dict
  1462. patch.multiple = _patch_multiple
  1463. patch.stopall = _patch_stopall
  1464. patch.TEST_PREFIX = 'test'
  1465. magic_methods = (
  1466. "lt le gt ge eq ne "
  1467. "getitem setitem delitem "
  1468. "len contains iter "
  1469. "hash str sizeof "
  1470. "enter exit "
  1471. # we added divmod and rdivmod here instead of numerics
  1472. # because there is no idivmod
  1473. "divmod rdivmod neg pos abs invert "
  1474. "complex int float index "
  1475. "trunc floor ceil "
  1476. )
  1477. numerics = (
  1478. "add sub mul matmul div floordiv mod lshift rshift and xor or pow"
  1479. )
  1480. if six.PY3:
  1481. numerics += ' truediv'
  1482. inplace = ' '.join('i%s' % n for n in numerics.split())
  1483. right = ' '.join('r%s' % n for n in numerics.split())
  1484. extra = ''
  1485. if six.PY3:
  1486. extra = 'bool next '
  1487. else:
  1488. extra = 'unicode long nonzero oct hex truediv rtruediv '
  1489. # not including __prepare__, __instancecheck__, __subclasscheck__
  1490. # (as they are metaclass methods)
  1491. # __del__ is not supported at all as it causes problems if it exists
  1492. _non_defaults = set((
  1493. '__cmp__', '__getslice__', '__setslice__', '__coerce__', # <3.x
  1494. '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
  1495. '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
  1496. '__getstate__', '__setstate__', '__getformat__', '__setformat__',
  1497. '__repr__', '__dir__', '__subclasses__', '__format__',
  1498. ))
  1499. def _get_method(name, func):
  1500. "Turns a callable object (like a mock) into a real function"
  1501. def method(self, *args, **kw):
  1502. return func(self, *args, **kw)
  1503. method.__name__ = name
  1504. return method
  1505. _magics = set(
  1506. '__%s__' % method for method in
  1507. ' '.join([magic_methods, numerics, inplace, right, extra]).split()
  1508. )
  1509. _all_magics = _magics | _non_defaults
  1510. _unsupported_magics = set((
  1511. '__getattr__', '__setattr__',
  1512. '__init__', '__new__', '__prepare__'
  1513. '__instancecheck__', '__subclasscheck__',
  1514. '__del__'
  1515. ))
  1516. _calculate_return_value = {
  1517. '__hash__': lambda self: object.__hash__(self),
  1518. '__str__': lambda self: object.__str__(self),
  1519. '__sizeof__': lambda self: object.__sizeof__(self),
  1520. '__unicode__': lambda self: unicode(object.__str__(self)),
  1521. }
  1522. _return_values = {
  1523. '__lt__': NotImplemented,
  1524. '__gt__': NotImplemented,
  1525. '__le__': NotImplemented,
  1526. '__ge__': NotImplemented,
  1527. '__int__': 1,
  1528. '__contains__': False,
  1529. '__len__': 0,
  1530. '__exit__': False,
  1531. '__complex__': 1j,
  1532. '__float__': 1.0,
  1533. '__bool__': True,
  1534. '__nonzero__': True,
  1535. '__oct__': '1',
  1536. '__hex__': '0x1',
  1537. '__long__': long(1),
  1538. '__index__': 1,
  1539. }
  1540. def _get_eq(self):
  1541. def __eq__(other):
  1542. ret_val = self.__eq__._mock_return_value
  1543. if ret_val is not DEFAULT:
  1544. return ret_val
  1545. return self is other
  1546. return __eq__
  1547. def _get_ne(self):
  1548. def __ne__(other):
  1549. if self.__ne__._mock_return_value is not DEFAULT:
  1550. return DEFAULT
  1551. return self is not other
  1552. return __ne__
  1553. def _get_iter(self):
  1554. def __iter__():
  1555. ret_val = self.__iter__._mock_return_value
  1556. if ret_val is DEFAULT:
  1557. return iter([])
  1558. # if ret_val was already an iterator, then calling iter on it should
  1559. # return the iterator unchanged
  1560. return iter(ret_val)
  1561. return __iter__
  1562. _side_effect_methods = {
  1563. '__eq__': _get_eq,
  1564. '__ne__': _get_ne,
  1565. '__iter__': _get_iter,
  1566. }
  1567. def _set_return_value(mock, method, name):
  1568. fixed = _return_values.get(name, DEFAULT)
  1569. if fixed is not DEFAULT:
  1570. method.return_value = fixed
  1571. return
  1572. return_calulator = _calculate_return_value.get(name)
  1573. if return_calulator is not None:
  1574. try:
  1575. return_value = return_calulator(mock)
  1576. except AttributeError:
  1577. # XXXX why do we return AttributeError here?
  1578. # set it as a side_effect instead?
  1579. return_value = AttributeError(name)
  1580. method.return_value = return_value
  1581. return
  1582. side_effector = _side_effect_methods.get(name)
  1583. if side_effector is not None:
  1584. method.side_effect = side_effector(mock)
  1585. class MagicMixin(object):
  1586. def __init__(self, *args, **kw):
  1587. self._mock_set_magics() # make magic work for kwargs in init
  1588. _safe_super(MagicMixin, self).__init__(*args, **kw)
  1589. self._mock_set_magics() # fix magic broken by upper level init
  1590. def _mock_set_magics(self):
  1591. these_magics = _magics
  1592. if getattr(self, "_mock_methods", None) is not None:
  1593. these_magics = _magics.intersection(self._mock_methods)
  1594. remove_magics = set()
  1595. remove_magics = _magics - these_magics
  1596. for entry in remove_magics:
  1597. if entry in type(self).__dict__:
  1598. # remove unneeded magic methods
  1599. delattr(self, entry)
  1600. # don't overwrite existing attributes if called a second time
  1601. these_magics = these_magics - set(type(self).__dict__)
  1602. _type = type(self)
  1603. for entry in these_magics:
  1604. setattr(_type, entry, MagicProxy(entry, self))
  1605. class NonCallableMagicMock(MagicMixin, NonCallableMock):
  1606. """A version of `MagicMock` that isn't callable."""
  1607. def mock_add_spec(self, spec, spec_set=False):
  1608. """Add a spec to a mock. `spec` can either be an object or a
  1609. list of strings. Only attributes on the `spec` can be fetched as
  1610. attributes from the mock.
  1611. If `spec_set` is True then only attributes on the spec can be set."""
  1612. self._mock_add_spec(spec, spec_set)
  1613. self._mock_set_magics()
  1614. class MagicMock(MagicMixin, Mock):
  1615. """
  1616. MagicMock is a subclass of Mock with default implementations
  1617. of most of the magic methods. You can use MagicMock without having to
  1618. configure the magic methods yourself.
  1619. If you use the `spec` or `spec_set` arguments then *only* magic
  1620. methods that exist in the spec will be created.
  1621. Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
  1622. """
  1623. def mock_add_spec(self, spec, spec_set=False):
  1624. """Add a spec to a mock. `spec` can either be an object or a
  1625. list of strings. Only attributes on the `spec` can be fetched as
  1626. attributes from the mock.
  1627. If `spec_set` is True then only attributes on the spec can be set."""
  1628. self._mock_add_spec(spec, spec_set)
  1629. self._mock_set_magics()
  1630. class MagicProxy(object):
  1631. def __init__(self, name, parent):
  1632. self.name = name
  1633. self.parent = parent
  1634. def __call__(self, *args, **kwargs):
  1635. m = self.create_mock()
  1636. return m(*args, **kwargs)
  1637. def create_mock(self):
  1638. entry = self.name
  1639. parent = self.parent
  1640. m = parent._get_child_mock(name=entry, _new_name=entry,
  1641. _new_parent=parent)
  1642. setattr(parent, entry, m)
  1643. _set_return_value(parent, m, entry)
  1644. return m
  1645. def __get__(self, obj, _type=None):
  1646. return self.create_mock()
  1647. class _ANY(object):
  1648. "A helper object that compares equal to everything."
  1649. def __eq__(self, other):
  1650. return True
  1651. def __ne__(self, other):
  1652. return False
  1653. def __repr__(self):
  1654. return '<ANY>'
  1655. __hash__ = None
  1656. ANY = _ANY()
  1657. def _format_call_signature(name, args, kwargs):
  1658. message = '%s(%%s)' % name
  1659. formatted_args = ''
  1660. args_string = ', '.join([repr(arg) for arg in args])
  1661. def encode_item(item):
  1662. if six.PY2 and isinstance(item, unicode):
  1663. return item.encode("utf-8")
  1664. else:
  1665. return item
  1666. kwargs_string = ', '.join([
  1667. '%s=%r' % (encode_item(key), value) for key, value in sorted(kwargs.items())
  1668. ])
  1669. if args_string:
  1670. formatted_args = args_string
  1671. if kwargs_string:
  1672. if formatted_args:
  1673. formatted_args += ', '
  1674. formatted_args += kwargs_string
  1675. return message % formatted_args
  1676. class _Call(tuple):
  1677. """
  1678. A tuple for holding the results of a call to a mock, either in the form
  1679. `(args, kwargs)` or `(name, args, kwargs)`.
  1680. If args or kwargs are empty then a call tuple will compare equal to
  1681. a tuple without those values. This makes comparisons less verbose::
  1682. _Call(('name', (), {})) == ('name',)
  1683. _Call(('name', (1,), {})) == ('name', (1,))
  1684. _Call(((), {'a': 'b'})) == ({'a': 'b'},)
  1685. The `_Call` object provides a useful shortcut for comparing with call::
  1686. _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
  1687. _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
  1688. If the _Call has no name then it will match any name.
  1689. """
  1690. def __new__(cls, value=(), name=None, parent=None, two=False,
  1691. from_kall=True):
  1692. name = ''
  1693. args = ()
  1694. kwargs = {}
  1695. _len = len(value)
  1696. if _len == 3:
  1697. name, args, kwargs = value
  1698. elif _len == 2:
  1699. first, second = value
  1700. if isinstance(first, basestring):
  1701. name = first
  1702. if isinstance(second, tuple):
  1703. args = second
  1704. else:
  1705. kwargs = second
  1706. else:
  1707. args, kwargs = first, second
  1708. elif _len == 1:
  1709. value, = value
  1710. if isinstance(value, basestring):
  1711. name = value
  1712. elif isinstance(value, tuple):
  1713. args = value
  1714. else:
  1715. kwargs = value
  1716. if two:
  1717. return tuple.__new__(cls, (args, kwargs))
  1718. return tuple.__new__(cls, (name, args, kwargs))
  1719. def __init__(self, value=(), name=None, parent=None, two=False,
  1720. from_kall=True):
  1721. self.name = name
  1722. self.parent = parent
  1723. self.from_kall = from_kall
  1724. def __eq__(self, other):
  1725. if other is ANY:
  1726. return True
  1727. try:
  1728. len_other = len(other)
  1729. except TypeError:
  1730. return False
  1731. self_name = ''
  1732. if len(self) == 2:
  1733. self_args, self_kwargs = self
  1734. else:
  1735. self_name, self_args, self_kwargs = self
  1736. other_name = ''
  1737. if len_other == 0:
  1738. other_args, other_kwargs = (), {}
  1739. elif len_other == 3:
  1740. other_name, other_args, other_kwargs = other
  1741. elif len_other == 1:
  1742. value, = other
  1743. if isinstance(value, tuple):
  1744. other_args = value
  1745. other_kwargs = {}
  1746. elif isinstance(value, basestring):
  1747. other_name = value
  1748. other_args, other_kwargs = (), {}
  1749. else:
  1750. other_args = ()
  1751. other_kwargs = value
  1752. elif len_other == 2:
  1753. # could be (name, args) or (name, kwargs) or (args, kwargs)
  1754. first, second = other
  1755. if isinstance(first, basestring):
  1756. other_name = first
  1757. if isinstance(second, tuple):
  1758. other_args, other_kwargs = second, {}
  1759. else:
  1760. other_args, other_kwargs = (), second
  1761. else:
  1762. other_args, other_kwargs = first, second
  1763. else:
  1764. return False
  1765. if self_name and other_name != self_name:
  1766. return False
  1767. # this order is important for ANY to work!
  1768. return (other_args, other_kwargs) == (self_args, self_kwargs)
  1769. def __ne__(self, other):
  1770. return not self.__eq__(other)
  1771. __hash__ = None
  1772. def __call__(self, *args, **kwargs):
  1773. if self.name is None:
  1774. return _Call(('', args, kwargs), name='()')
  1775. name = self.name + '()'
  1776. return _Call((self.name, args, kwargs), name=name, parent=self)
  1777. def __getattr__(self, attr):
  1778. if self.name is None:
  1779. return _Call(name=attr, from_kall=False)
  1780. name = '%s.%s' % (self.name, attr)
  1781. return _Call(name=name, parent=self, from_kall=False)
  1782. def count(self, *args, **kwargs):
  1783. return self.__getattr__('count')(*args, **kwargs)
  1784. def index(self, *args, **kwargs):
  1785. return self.__getattr__('index')(*args, **kwargs)
  1786. def __repr__(self):
  1787. if not self.from_kall:
  1788. name = self.name or 'call'
  1789. if name.startswith('()'):
  1790. name = 'call%s' % name
  1791. return name
  1792. if len(self) == 2:
  1793. name = 'call'
  1794. args, kwargs = self
  1795. else:
  1796. name, args, kwargs = self
  1797. if not name:
  1798. name = 'call'
  1799. elif not name.startswith('()'):
  1800. name = 'call.%s' % name
  1801. else:
  1802. name = 'call%s' % name
  1803. return _format_call_signature(name, args, kwargs)
  1804. def call_list(self):
  1805. """For a call object that represents multiple calls, `call_list`
  1806. returns a list of all the intermediate calls as well as the
  1807. final call."""
  1808. vals = []
  1809. thing = self
  1810. while thing is not None:
  1811. if thing.from_kall:
  1812. vals.append(thing)
  1813. thing = thing.parent
  1814. return _CallList(reversed(vals))
  1815. call = _Call(from_kall=False)
  1816. def create_autospec(spec, spec_set=False, instance=False, _parent=None,
  1817. _name=None, **kwargs):
  1818. """Create a mock object using another object as a spec. Attributes on the
  1819. mock will use the corresponding attribute on the `spec` object as their
  1820. spec.
  1821. Functions or methods being mocked will have their arguments checked
  1822. to check that they are called with the correct signature.
  1823. If `spec_set` is True then attempting to set attributes that don't exist
  1824. on the spec object will raise an `AttributeError`.
  1825. If a class is used as a spec then the return value of the mock (the
  1826. instance of the class) will have the same spec. You can use a class as the
  1827. spec for an instance object by passing `instance=True`. The returned mock
  1828. will only be callable if instances of the mock are callable.
  1829. `create_autospec` also takes arbitrary keyword arguments that are passed to
  1830. the constructor of the created mock."""
  1831. if _is_list(spec):
  1832. # can't pass a list instance to the mock constructor as it will be
  1833. # interpreted as a list of strings
  1834. spec = type(spec)
  1835. is_type = isinstance(spec, ClassTypes)
  1836. _kwargs = {'spec': spec}
  1837. if spec_set:
  1838. _kwargs = {'spec_set': spec}
  1839. elif spec is None:
  1840. # None we mock with a normal mock without a spec
  1841. _kwargs = {}
  1842. if _kwargs and instance:
  1843. _kwargs['_spec_as_instance'] = True
  1844. _kwargs.update(kwargs)
  1845. Klass = MagicMock
  1846. if type(spec) in DescriptorTypes:
  1847. # descriptors don't have a spec
  1848. # because we don't know what type they return
  1849. _kwargs = {}
  1850. elif not _callable(spec):
  1851. Klass = NonCallableMagicMock
  1852. elif is_type and instance and not _instance_callable(spec):
  1853. Klass = NonCallableMagicMock
  1854. _name = _kwargs.pop('name', _name)
  1855. _new_name = _name
  1856. if _parent is None:
  1857. # for a top level object no _new_name should be set
  1858. _new_name = ''
  1859. mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
  1860. name=_name, **_kwargs)
  1861. if isinstance(spec, FunctionTypes):
  1862. # should only happen at the top level because we don't
  1863. # recurse for functions
  1864. mock = _set_signature(mock, spec)
  1865. else:
  1866. _check_signature(spec, mock, is_type, instance)
  1867. if _parent is not None and not instance:
  1868. _parent._mock_children[_name] = mock
  1869. if is_type and not instance and 'return_value' not in kwargs:
  1870. mock.return_value = create_autospec(spec, spec_set, instance=True,
  1871. _name='()', _parent=mock)
  1872. for entry in dir(spec):
  1873. if _is_magic(entry):
  1874. # MagicMock already does the useful magic methods for us
  1875. continue
  1876. # XXXX do we need a better way of getting attributes without
  1877. # triggering code execution (?) Probably not - we need the actual
  1878. # object to mock it so we would rather trigger a property than mock
  1879. # the property descriptor. Likewise we want to mock out dynamically
  1880. # provided attributes.
  1881. # XXXX what about attributes that raise exceptions other than
  1882. # AttributeError on being fetched?
  1883. # we could be resilient against it, or catch and propagate the
  1884. # exception when the attribute is fetched from the mock
  1885. try:
  1886. original = getattr(spec, entry)
  1887. except AttributeError:
  1888. continue
  1889. kwargs = {'spec': original}
  1890. if spec_set:
  1891. kwargs = {'spec_set': original}
  1892. if not isinstance(original, FunctionTypes):
  1893. new = _SpecState(original, spec_set, mock, entry, instance)
  1894. mock._mock_children[entry] = new
  1895. else:
  1896. parent = mock
  1897. if isinstance(spec, FunctionTypes):
  1898. parent = mock.mock
  1899. skipfirst = _must_skip(spec, entry, is_type)
  1900. kwargs['_eat_self'] = skipfirst
  1901. new = MagicMock(parent=parent, name=entry, _new_name=entry,
  1902. _new_parent=parent,
  1903. **kwargs)
  1904. mock._mock_children[entry] = new
  1905. _check_signature(original, new, skipfirst=skipfirst)
  1906. # so functions created with _set_signature become instance attributes,
  1907. # *plus* their underlying mock exists in _mock_children of the parent
  1908. # mock. Adding to _mock_children may be unnecessary where we are also
  1909. # setting as an instance attribute?
  1910. if isinstance(new, FunctionTypes):
  1911. setattr(mock, entry, new)
  1912. return mock
  1913. def _must_skip(spec, entry, is_type):
  1914. """
  1915. Return whether we should skip the first argument on spec's `entry`
  1916. attribute.
  1917. """
  1918. if not isinstance(spec, ClassTypes):
  1919. if entry in getattr(spec, '__dict__', {}):
  1920. # instance attribute - shouldn't skip
  1921. return False
  1922. spec = spec.__class__
  1923. if not hasattr(spec, '__mro__'):
  1924. # old style class: can't have descriptors anyway
  1925. return is_type
  1926. for klass in spec.__mro__:
  1927. result = klass.__dict__.get(entry, DEFAULT)
  1928. if result is DEFAULT:
  1929. continue
  1930. if isinstance(result, (staticmethod, classmethod)):
  1931. return False
  1932. elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
  1933. # Normal method => skip if looked up on type
  1934. # (if looked up on instance, self is already skipped)
  1935. return is_type
  1936. else:
  1937. return False
  1938. # shouldn't get here unless function is a dynamically provided attribute
  1939. # XXXX untested behaviour
  1940. return is_type
  1941. def _get_class(obj):
  1942. try:
  1943. return obj.__class__
  1944. except AttributeError:
  1945. # it is possible for objects to have no __class__
  1946. return type(obj)
  1947. class _SpecState(object):
  1948. def __init__(self, spec, spec_set=False, parent=None,
  1949. name=None, ids=None, instance=False):
  1950. self.spec = spec
  1951. self.ids = ids
  1952. self.spec_set = spec_set
  1953. self.parent = parent
  1954. self.instance = instance
  1955. self.name = name
  1956. FunctionTypes = (
  1957. # python function
  1958. type(create_autospec),
  1959. # instance method
  1960. type(ANY.__eq__),
  1961. )
  1962. MethodWrapperTypes = (
  1963. type(ANY.__eq__.__get__),
  1964. )
  1965. file_spec = None
  1966. def _iterate_read_data(read_data):
  1967. # Helper for mock_open:
  1968. # Retrieve lines from read_data via a generator so that separate calls to
  1969. # readline, read, and readlines are properly interleaved
  1970. sep = b'\n' if isinstance(read_data, bytes) else '\n'
  1971. data_as_list = [l + sep for l in read_data.split(sep)]
  1972. if data_as_list[-1] == sep:
  1973. # If the last line ended in a newline, the list comprehension will have an
  1974. # extra entry that's just a newline. Remove this.
  1975. data_as_list = data_as_list[:-1]
  1976. else:
  1977. # If there wasn't an extra newline by itself, then the file being
  1978. # emulated doesn't have a newline to end the last line remove the
  1979. # newline that our naive format() added
  1980. data_as_list[-1] = data_as_list[-1][:-1]
  1981. for line in data_as_list:
  1982. yield line
  1983. def mock_open(mock=None, read_data=''):
  1984. """
  1985. A helper function to create a mock to replace the use of `open`. It works
  1986. for `open` called directly or used as a context manager.
  1987. The `mock` argument is the mock object to configure. If `None` (the
  1988. default) then a `MagicMock` will be created for you, with the API limited
  1989. to methods or attributes available on standard file handles.
  1990. `read_data` is a string for the `read` methoddline`, and `readlines` of the
  1991. file handle to return. This is an empty string by default.
  1992. """
  1993. def _readlines_side_effect(*args, **kwargs):
  1994. if handle.readlines.return_value is not None:
  1995. return handle.readlines.return_value
  1996. return list(_state[0])
  1997. def _read_side_effect(*args, **kwargs):
  1998. if handle.read.return_value is not None:
  1999. return handle.read.return_value
  2000. return type(read_data)().join(_state[0])
  2001. def _readline_side_effect():
  2002. if handle.readline.return_value is not None:
  2003. while True:
  2004. yield handle.readline.return_value
  2005. for line in _state[0]:
  2006. yield line
  2007. global file_spec
  2008. if file_spec is None:
  2009. # set on first use
  2010. if six.PY3:
  2011. import _io
  2012. file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
  2013. else:
  2014. file_spec = file
  2015. if mock is None:
  2016. mock = MagicMock(name='open', spec=open)
  2017. handle = MagicMock(spec=file_spec)
  2018. handle.__enter__.return_value = handle
  2019. _state = [_iterate_read_data(read_data), None]
  2020. handle.write.return_value = None
  2021. handle.read.return_value = None
  2022. handle.readline.return_value = None
  2023. handle.readlines.return_value = None
  2024. handle.read.side_effect = _read_side_effect
  2025. _state[1] = _readline_side_effect()
  2026. handle.readline.side_effect = _state[1]
  2027. handle.readlines.side_effect = _readlines_side_effect
  2028. def reset_data(*args, **kwargs):
  2029. _state[0] = _iterate_read_data(read_data)
  2030. if handle.readline.side_effect == _state[1]:
  2031. # Only reset the side effect if the user hasn't overridden it.
  2032. _state[1] = _readline_side_effect()
  2033. handle.readline.side_effect = _state[1]
  2034. return DEFAULT
  2035. mock.side_effect = reset_data
  2036. mock.return_value = handle
  2037. return mock
  2038. class PropertyMock(Mock):
  2039. """
  2040. A mock intended to be used as a property, or other descriptor, on a class.
  2041. `PropertyMock` provides `__get__` and `__set__` methods so you can specify
  2042. a return value when it is fetched.
  2043. Fetching a `PropertyMock` instance from an object calls the mock, with
  2044. no args. Setting it calls the mock with the value being set.
  2045. """
  2046. def _get_child_mock(self, **kwargs):
  2047. return MagicMock(**kwargs)
  2048. def __get__(self, obj, obj_type):
  2049. return self()
  2050. def __set__(self, obj, val):
  2051. self(val)