mock.py 73 KB

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