Debian Codegraph @

tests/mock.py

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