Merge lp:~jjo/juju-deployer/decorate-tests-failing-on-LP-builders_and_support-precise-python-mock into lp:juju-deployer

Proposed by JuanJo Ciarlante
Status: Merged
Merged at revision: 86
Proposed branch: lp:~jjo/juju-deployer/decorate-tests-failing-on-LP-builders_and_support-precise-python-mock
Merge into: lp:juju-deployer
Diff against target: 2469 lines (+2380/-2)
6 files modified
deployer/tests/mock.py (+2367/-0)
deployer/tests/test_charm.py (+5/-0)
deployer/tests/test_deployment.py (+3/-0)
deployer/tests/test_guiserver.py (+4/-0)
deployer/tests/test_utils.py (+1/-1)
setup.py (+0/-1)
To merge this branch: bzr merge lp:~jjo/juju-deployer/decorate-tests-failing-on-LP-builders_and_support-precise-python-mock
Reviewer Review Type Date Requested Status
Kapil Thangavelu Approve
Review via email: mp+196372@code.launchpad.net

Commit message

decorate tests failing on LP builders, cp mock.py from python-mock==1.0.1 (to fix building on precise)

To post a comment you must log in.
86. By JuanJo Ciarlante

as per hazmat, directly cp mock.py into distrib and keep previous mock usage

Revision history for this message
Kapil Thangavelu (hazmat) wrote :

looks good, thanks. modified to use a constant based on env var instead of repeating DEB_BUILD_ARCH.

review: Approve

Preview Diff

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

Subscribers

People subscribed via source and target branches