mock.py 75 KB

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