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