mock.py 74 KB

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