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