mock.py 73 KB

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