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