blob: 89fe232c2bf8b7aa33cdc963ef89814e924655c9 [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:
81 regargs, varargs, varkwargs, defaults = inspect.getargspec(func)
82 except TypeError:
83 # C function / method, possibly inherited object().__init__
84 return
85
86 # instance methods and classmethods need to lose the self argument
87 if getattr(func, '__self__', None) is not None:
88 regargs = regargs[1:]
89 if skipfirst:
90 # this condition and the above one are never both True - why?
91 regargs = regargs[1:]
92
93 signature = inspect.formatargspec(regargs, varargs, varkwargs, defaults,
94 formatvalue=lambda value: "")
95 return signature[1:-1], func
96
97
98def _check_signature(func, mock, skipfirst, instance=False):
99 if not _callable(func):
100 return
101
102 result = _getsignature(func, skipfirst, instance)
103 if result is None:
104 return
105 signature, func = result
106
107 # can't use self because "self" is common as an argument name
108 # unfortunately even not in the first place
109 src = "lambda _mock_self, %s: None" % signature
110 checksig = eval(src, {})
111 _copy_func_details(func, checksig)
112 type(mock)._mock_check_sig = checksig
113
114
115def _copy_func_details(func, funcopy):
116 funcopy.__name__ = func.__name__
117 funcopy.__doc__ = func.__doc__
118 # we explicitly don't copy func.__dict__ into this copy as it would
119 # expose original attributes that should be mocked
120 funcopy.__module__ = func.__module__
121 funcopy.__defaults__ = func.__defaults__
122 funcopy.__kwdefaults__ = func.__kwdefaults__
123
124
125def _callable(obj):
126 if isinstance(obj, type):
127 return True
128 if getattr(obj, '__call__', None) is not None:
129 return True
130 return False
131
132
133def _is_list(obj):
134 # checks for list or tuples
135 # XXXX badly named!
136 return type(obj) in (list, tuple)
137
138
139def _instance_callable(obj):
140 """Given an object, return True if the object is callable.
141 For classes, return True if instances would be callable."""
142 if not isinstance(obj, type):
143 # already an instance
144 return getattr(obj, '__call__', None) is not None
145
146 klass = obj
147 # uses __bases__ instead of __mro__ so that we work with old style classes
148 if klass.__dict__.get('__call__') is not None:
149 return True
150
151 for base in klass.__bases__:
152 if _instance_callable(base):
153 return True
154 return False
155
156
157def _set_signature(mock, original, instance=False):
158 # creates a function with signature (*args, **kwargs) that delegates to a
159 # mock. It still does signature checking by calling a lambda with the same
160 # signature as the original.
161 if not _callable(original):
162 return
163
164 skipfirst = isinstance(original, type)
165 result = _getsignature(original, skipfirst, instance)
166 if result is None:
167 # was a C function (e.g. object().__init__ ) that can't be mocked
168 return
169
170 signature, func = result
171
172 src = "lambda %s: None" % signature
173 context = {'_mock_': mock}
174 checksig = eval(src, context)
175 _copy_func_details(func, checksig)
176
177 name = original.__name__
178 if not name.isidentifier():
179 name = 'funcopy'
180 context = {'checksig': checksig, 'mock': mock}
181 src = """def %s(*args, **kwargs):
182 checksig(*args, **kwargs)
183 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):
625 """Filter the output of `dir(mock)` to only useful members.
626 XXXX
627 """
628 extras = self._mock_methods or []
629 from_type = dir(type(self))
630 from_dict = list(self.__dict__)
631
632 if FILTER_DIR:
633 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)]
636 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):
898 return next(effect)
899
900 ret_val = effect(*args, **kwargs)
901 if ret_val is DEFAULT:
902 ret_val = self.return_value
903
904 if (self._mock_wraps is not None and
905 self._mock_return_value is DEFAULT):
906 return self._mock_wraps(*args, **kwargs)
907 if ret_val is DEFAULT:
908 ret_val = self.return_value
909 return ret_val
910
911
912
913class Mock(CallableMixin, NonCallableMock):
914 """
915 Create a new `Mock` object. `Mock` takes several optional arguments
916 that specify the behaviour of the Mock object:
917
918 * `spec`: This can be either a list of strings or an existing object (a
919 class or instance) that acts as the specification for the mock object. If
920 you pass in an object then a list of strings is formed by calling dir on
921 the object (excluding unsupported magic attributes and methods). Accessing
922 any attribute not in this list will raise an `AttributeError`.
923
924 If `spec` is an object (rather than a list of strings) then
925 `mock.__class__` returns the class of the spec object. This allows mocks
926 to pass `isinstance` tests.
927
928 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
929 or get an attribute on the mock that isn't on the object passed as
930 `spec_set` will raise an `AttributeError`.
931
932 * `side_effect`: A function to be called whenever the Mock is called. See
933 the `side_effect` attribute. Useful for raising exceptions or
934 dynamically changing return values. The function is called with the same
935 arguments as the mock, and unless it returns `DEFAULT`, the return
936 value of this function is used as the return value.
937
938 Alternatively `side_effect` can be an exception class or instance. In
939 this case the exception will be raised when the mock is called.
940
941 If `side_effect` is an iterable then each call to the mock will return
942 the next value from the iterable.
943
944 * `return_value`: The value returned when the mock is called. By default
945 this is a new Mock (created on first access). See the
946 `return_value` attribute.
947
948 * `wraps`: Item for the mock object to wrap. If `wraps` is not None
949 then calling the Mock will pass the call through to the wrapped object
950 (returning the real result and ignoring `return_value`). Attribute
951 access on the mock will return a Mock object that wraps the corresponding
952 attribute of the wrapped object (so attempting to access an attribute that
953 doesn't exist will raise an `AttributeError`).
954
955 If the mock has an explicit `return_value` set then calls are not passed
956 to the wrapped object and the `return_value` is returned instead.
957
958 * `name`: If the mock has a name then it will be used in the repr of the
959 mock. This can be useful for debugging. The name is propagated to child
960 mocks.
961
962 Mocks can also be called with arbitrary keyword arguments. These will be
963 used to set attributes on the mock after it is created.
964 """
965
966
967
968def _dot_lookup(thing, comp, import_path):
969 try:
970 return getattr(thing, comp)
971 except AttributeError:
972 __import__(import_path)
973 return getattr(thing, comp)
974
975
976def _importer(target):
977 components = target.split('.')
978 import_path = components.pop(0)
979 thing = __import__(import_path)
980
981 for comp in components:
982 import_path += ".%s" % comp
983 thing = _dot_lookup(thing, comp, import_path)
984 return thing
985
986
987def _is_started(patcher):
988 # XXXX horrible
989 return hasattr(patcher, 'is_local')
990
991
992class _patch(object):
993
994 attribute_name = None
995
996 def __init__(
997 self, getter, attribute, new, spec, create,
998 spec_set, autospec, new_callable, kwargs
999 ):
1000 if new_callable is not None:
1001 if new is not DEFAULT:
1002 raise ValueError(
1003 "Cannot use 'new' and 'new_callable' together"
1004 )
1005 if autospec is not False:
1006 raise ValueError(
1007 "Cannot use 'autospec' and 'new_callable' together"
1008 )
1009
1010 self.getter = getter
1011 self.attribute = attribute
1012 self.new = new
1013 self.new_callable = new_callable
1014 self.spec = spec
1015 self.create = create
1016 self.has_local = False
1017 self.spec_set = spec_set
1018 self.autospec = autospec
1019 self.kwargs = kwargs
1020 self.additional_patchers = []
1021
1022
1023 def copy(self):
1024 patcher = _patch(
1025 self.getter, self.attribute, self.new, self.spec,
1026 self.create, self.spec_set,
1027 self.autospec, self.new_callable, self.kwargs
1028 )
1029 patcher.attribute_name = self.attribute_name
1030 patcher.additional_patchers = [
1031 p.copy() for p in self.additional_patchers
1032 ]
1033 return patcher
1034
1035
1036 def __call__(self, func):
1037 if isinstance(func, type):
1038 return self.decorate_class(func)
1039 return self.decorate_callable(func)
1040
1041
1042 def decorate_class(self, klass):
1043 for attr in dir(klass):
1044 if not attr.startswith(patch.TEST_PREFIX):
1045 continue
1046
1047 attr_value = getattr(klass, attr)
1048 if not hasattr(attr_value, "__call__"):
1049 continue
1050
1051 patcher = self.copy()
1052 setattr(klass, attr, patcher(attr_value))
1053 return klass
1054
1055
1056 def decorate_callable(self, func):
1057 if hasattr(func, 'patchings'):
1058 func.patchings.append(self)
1059 return func
1060
1061 @wraps(func)
1062 def patched(*args, **keywargs):
1063 # could use with statement here
1064 extra_args = []
1065 entered_patchers = []
1066
1067 # could use try..except...finally here
1068 try:
1069 try:
1070 for patching in patched.patchings:
1071 arg = patching.__enter__()
1072 entered_patchers.append(patching)
1073 if patching.attribute_name is not None:
1074 keywargs.update(arg)
1075 elif patching.new is DEFAULT:
1076 extra_args.append(arg)
1077
1078 args += tuple(extra_args)
1079 return func(*args, **keywargs)
1080 except:
1081 if (patching not in entered_patchers and
1082 _is_started(patching)):
1083 # the patcher may have been started, but an exception
1084 # raised whilst entering one of its additional_patchers
1085 entered_patchers.append(patching)
1086 # re-raise the exception
1087 raise
1088 finally:
1089 for patching in reversed(entered_patchers):
1090 patching.__exit__()
1091
1092 patched.patchings = [self]
1093 if hasattr(func, 'func_code'):
1094 # not in Python 3
1095 patched.compat_co_firstlineno = getattr(
1096 func, "compat_co_firstlineno",
1097 func.func_code.co_firstlineno
1098 )
1099 return patched
1100
1101
1102 def get_original(self):
1103 target = self.getter()
1104 name = self.attribute
1105
1106 original = DEFAULT
1107 local = False
1108
1109 try:
1110 original = target.__dict__[name]
1111 except (AttributeError, KeyError):
1112 original = getattr(target, name, DEFAULT)
1113 else:
1114 local = True
1115
1116 if not self.create and original is DEFAULT:
1117 raise AttributeError(
1118 "%s does not have the attribute %r" % (target, name)
1119 )
1120 return original, local
1121
1122
1123 def __enter__(self):
1124 """Perform the patch."""
1125 new, spec, spec_set = self.new, self.spec, self.spec_set
1126 autospec, kwargs = self.autospec, self.kwargs
1127 new_callable = self.new_callable
1128 self.target = self.getter()
1129
1130 original, local = self.get_original()
1131
1132 if new is DEFAULT and autospec is False:
1133 inherit = False
1134 if spec_set == True:
1135 spec_set = original
1136 elif spec == True:
1137 # set spec to the object we are replacing
1138 spec = original
1139
1140 if (spec or spec_set) is not None:
1141 if isinstance(original, type):
1142 # If we're patching out a class and there is a spec
1143 inherit = True
1144
1145 Klass = MagicMock
1146 _kwargs = {}
1147 if new_callable is not None:
1148 Klass = new_callable
1149 elif (spec or spec_set) is not None:
1150 if not _callable(spec or spec_set):
1151 Klass = NonCallableMagicMock
1152
1153 if spec is not None:
1154 _kwargs['spec'] = spec
1155 if spec_set is not None:
1156 _kwargs['spec_set'] = spec_set
1157
1158 # add a name to mocks
1159 if (isinstance(Klass, type) and
1160 issubclass(Klass, NonCallableMock) and self.attribute):
1161 _kwargs['name'] = self.attribute
1162
1163 _kwargs.update(kwargs)
1164 new = Klass(**_kwargs)
1165
1166 if inherit and _is_instance_mock(new):
1167 # we can only tell if the instance should be callable if the
1168 # spec is not a list
1169 if (not _is_list(spec or spec_set) and not
1170 _instance_callable(spec or spec_set)):
1171 Klass = NonCallableMagicMock
1172
1173 _kwargs.pop('name')
1174 new.return_value = Klass(_new_parent=new, _new_name='()',
1175 **_kwargs)
1176 elif autospec is not False:
1177 # spec is ignored, new *must* be default, spec_set is treated
1178 # as a boolean. Should we check spec is not None and that spec_set
1179 # is a bool?
1180 if new is not DEFAULT:
1181 raise TypeError(
1182 "autospec creates the mock for you. Can't specify "
1183 "autospec and new."
1184 )
1185 spec_set = bool(spec_set)
1186 if autospec is True:
1187 autospec = original
1188
1189 new = create_autospec(autospec, spec_set=spec_set,
1190 _name=self.attribute, **kwargs)
1191 elif kwargs:
1192 # can't set keyword args when we aren't creating the mock
1193 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1194 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1195
1196 new_attr = new
1197
1198 self.temp_original = original
1199 self.is_local = local
1200 setattr(self.target, self.attribute, new_attr)
1201 if self.attribute_name is not None:
1202 extra_args = {}
1203 if self.new is DEFAULT:
1204 extra_args[self.attribute_name] = new
1205 for patching in self.additional_patchers:
1206 arg = patching.__enter__()
1207 if patching.new is DEFAULT:
1208 extra_args.update(arg)
1209 return extra_args
1210
1211 return new
1212
1213
1214 def __exit__(self, *_):
1215 """Undo the patch."""
1216 if not _is_started(self):
1217 raise RuntimeError('stop called on unstarted patcher')
1218
1219 if self.is_local and self.temp_original is not DEFAULT:
1220 setattr(self.target, self.attribute, self.temp_original)
1221 else:
1222 delattr(self.target, self.attribute)
1223 if not self.create and not hasattr(self.target, self.attribute):
1224 # needed for proxy objects like django settings
1225 setattr(self.target, self.attribute, self.temp_original)
1226
1227 del self.temp_original
1228 del self.is_local
1229 del self.target
1230 for patcher in reversed(self.additional_patchers):
1231 if _is_started(patcher):
1232 patcher.__exit__()
1233
1234 start = __enter__
1235 stop = __exit__
1236
1237
1238
1239def _get_target(target):
1240 try:
1241 target, attribute = target.rsplit('.', 1)
1242 except (TypeError, ValueError):
1243 raise TypeError("Need a valid target to patch. You supplied: %r" %
1244 (target,))
1245 getter = lambda: _importer(target)
1246 return getter, attribute
1247
1248
1249def _patch_object(
1250 target, attribute, new=DEFAULT, spec=None,
1251 create=False, spec_set=None, autospec=False,
1252 new_callable=None, **kwargs
1253 ):
1254 """
1255 patch.object(target, attribute, new=DEFAULT, spec=None, create=False,
1256 spec_set=None, autospec=False,
1257 new_callable=None, **kwargs)
1258
1259 patch the named member (`attribute`) on an object (`target`) with a mock
1260 object.
1261
1262 `patch.object` can be used as a decorator, class decorator or a context
1263 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1264 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1265 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1266 the mock object it creates.
1267
1268 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1269 for choosing which methods to wrap.
1270 """
1271 getter = lambda: target
1272 return _patch(
1273 getter, attribute, new, spec, create,
1274 spec_set, autospec, new_callable, kwargs
1275 )
1276
1277
1278def _patch_multiple(target, spec=None, create=False,
1279 spec_set=None, autospec=False,
1280 new_callable=None, **kwargs
1281 ):
1282 """Perform multiple patches in a single call. It takes the object to be
1283 patched (either as an object or a string to fetch the object by importing)
1284 and keyword arguments for the patches::
1285
1286 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1287 ...
1288
1289 Use `DEFAULT` as the value if you want `patch.multiple` to create
1290 mocks for you. In this case the created mocks are passed into a decorated
1291 function by keyword, and a dictionary is returned when `patch.multiple` is
1292 used as a context manager.
1293
1294 `patch.multiple` can be used as a decorator, class decorator or a context
1295 manager. The arguments `spec`, `spec_set`, `create`,
1296 `autospec` and `new_callable` have the same meaning as for `patch`. These
1297 arguments will be applied to *all* patches done by `patch.multiple`.
1298
1299 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1300 for choosing which methods to wrap.
1301 """
1302 if type(target) is str:
1303 getter = lambda: _importer(target)
1304 else:
1305 getter = lambda: target
1306
1307 if not kwargs:
1308 raise ValueError(
1309 'Must supply at least one keyword argument with patch.multiple'
1310 )
1311 # need to wrap in a list for python 3, where items is a view
1312 items = list(kwargs.items())
1313 attribute, new = items[0]
1314 patcher = _patch(
1315 getter, attribute, new, spec, create, spec_set,
1316 autospec, new_callable, {}
1317 )
1318 patcher.attribute_name = attribute
1319 for attribute, new in items[1:]:
1320 this_patcher = _patch(
1321 getter, attribute, new, spec, create, spec_set,
1322 autospec, new_callable, {}
1323 )
1324 this_patcher.attribute_name = attribute
1325 patcher.additional_patchers.append(this_patcher)
1326 return patcher
1327
1328
1329def patch(
1330 target, new=DEFAULT, spec=None, create=False,
1331 spec_set=None, autospec=False,
1332 new_callable=None, **kwargs
1333 ):
1334 """
1335 `patch` acts as a function decorator, class decorator or a context
1336 manager. Inside the body of the function or with statement, the `target`
1337 (specified in the form `'package.module.ClassName'`) is patched
1338 with a `new` object. When the function/with statement exits the patch is
1339 undone.
1340
1341 The `target` is imported and the specified attribute patched with the new
1342 object, so it must be importable from the environment you are calling the
1343 decorator from. The target is imported when the decorated function is
1344 executed, not at decoration time.
1345
1346 If `new` is omitted, then a new `MagicMock` is created and passed in as an
1347 extra argument to the decorated function.
1348
1349 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1350 if patch is creating one for you.
1351
1352 In addition you can pass `spec=True` or `spec_set=True`, which causes
1353 patch to pass in the object being mocked as the spec/spec_set object.
1354
1355 `new_callable` allows you to specify a different class, or callable object,
1356 that will be called to create the `new` object. By default `MagicMock` is
1357 used.
1358
1359 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1360 then the mock with be created with a spec from the object being replaced.
1361 All attributes of the mock will also have the spec of the corresponding
1362 attribute of the object being replaced. Methods and functions being
1363 mocked will have their arguments checked and will raise a `TypeError` if
1364 they are called with the wrong signature. For mocks replacing a class,
1365 their return value (the 'instance') will have the same spec as the class.
1366
1367 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1368 arbitrary object as the spec instead of the one being replaced.
1369
1370 By default `patch` will fail to replace attributes that don't exist. If
1371 you pass in `create=True`, and the attribute doesn't exist, patch will
1372 create the attribute for you when the patched function is called, and
1373 delete it again afterwards. This is useful for writing tests against
1374 attributes that your production code creates at runtime. It is off by by
1375 default because it can be dangerous. With it switched on you can write
1376 passing tests against APIs that don't actually exist!
1377
1378 Patch can be used as a `TestCase` class decorator. It works by
1379 decorating each test method in the class. This reduces the boilerplate
1380 code when your test methods share a common patchings set. `patch` finds
1381 tests by looking for method names that start with `patch.TEST_PREFIX`.
1382 By default this is `test`, which matches the way `unittest` finds tests.
1383 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1384
1385 Patch can be used as a context manager, with the with statement. Here the
1386 patching applies to the indented block after the with statement. If you
1387 use "as" then the patched object will be bound to the name after the
1388 "as"; very useful if `patch` is creating a mock object for you.
1389
1390 `patch` takes arbitrary keyword arguments. These will be passed to
1391 the `Mock` (or `new_callable`) on construction.
1392
1393 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1394 available for alternate use-cases.
1395 """
1396 getter, attribute = _get_target(target)
1397 return _patch(
1398 getter, attribute, new, spec, create,
1399 spec_set, autospec, new_callable, kwargs
1400 )
1401
1402
1403class _patch_dict(object):
1404 """
1405 Patch a dictionary, or dictionary like object, and restore the dictionary
1406 to its original state after the test.
1407
1408 `in_dict` can be a dictionary or a mapping like container. If it is a
1409 mapping then it must at least support getting, setting and deleting items
1410 plus iterating over keys.
1411
1412 `in_dict` can also be a string specifying the name of the dictionary, which
1413 will then be fetched by importing it.
1414
1415 `values` can be a dictionary of values to set in the dictionary. `values`
1416 can also be an iterable of `(key, value)` pairs.
1417
1418 If `clear` is True then the dictionary will be cleared before the new
1419 values are set.
1420
1421 `patch.dict` can also be called with arbitrary keyword arguments to set
1422 values in the dictionary::
1423
1424 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1425 ...
1426
1427 `patch.dict` can be used as a context manager, decorator or class
1428 decorator. When used as a class decorator `patch.dict` honours
1429 `patch.TEST_PREFIX` for choosing which methods to wrap.
1430 """
1431
1432 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1433 if isinstance(in_dict, str):
1434 in_dict = _importer(in_dict)
1435 self.in_dict = in_dict
1436 # support any argument supported by dict(...) constructor
1437 self.values = dict(values)
1438 self.values.update(kwargs)
1439 self.clear = clear
1440 self._original = None
1441
1442
1443 def __call__(self, f):
1444 if isinstance(f, type):
1445 return self.decorate_class(f)
1446 @wraps(f)
1447 def _inner(*args, **kw):
1448 self._patch_dict()
1449 try:
1450 return f(*args, **kw)
1451 finally:
1452 self._unpatch_dict()
1453
1454 return _inner
1455
1456
1457 def decorate_class(self, klass):
1458 for attr in dir(klass):
1459 attr_value = getattr(klass, attr)
1460 if (attr.startswith(patch.TEST_PREFIX) and
1461 hasattr(attr_value, "__call__")):
1462 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1463 decorated = decorator(attr_value)
1464 setattr(klass, attr, decorated)
1465 return klass
1466
1467
1468 def __enter__(self):
1469 """Patch the dict."""
1470 self._patch_dict()
1471
1472
1473 def _patch_dict(self):
1474 values = self.values
1475 in_dict = self.in_dict
1476 clear = self.clear
1477
1478 try:
1479 original = in_dict.copy()
1480 except AttributeError:
1481 # dict like object with no copy method
1482 # must support iteration over keys
1483 original = {}
1484 for key in in_dict:
1485 original[key] = in_dict[key]
1486 self._original = original
1487
1488 if clear:
1489 _clear_dict(in_dict)
1490
1491 try:
1492 in_dict.update(values)
1493 except AttributeError:
1494 # dict like object with no update method
1495 for key in values:
1496 in_dict[key] = values[key]
1497
1498
1499 def _unpatch_dict(self):
1500 in_dict = self.in_dict
1501 original = self._original
1502
1503 _clear_dict(in_dict)
1504
1505 try:
1506 in_dict.update(original)
1507 except AttributeError:
1508 for key in original:
1509 in_dict[key] = original[key]
1510
1511
1512 def __exit__(self, *args):
1513 """Unpatch the dict."""
1514 self._unpatch_dict()
1515 return False
1516
1517 start = __enter__
1518 stop = __exit__
1519
1520
1521def _clear_dict(in_dict):
1522 try:
1523 in_dict.clear()
1524 except AttributeError:
1525 keys = list(in_dict)
1526 for key in keys:
1527 del in_dict[key]
1528
1529
1530patch.object = _patch_object
1531patch.dict = _patch_dict
1532patch.multiple = _patch_multiple
1533patch.TEST_PREFIX = 'test'
1534
1535magic_methods = (
1536 "lt le gt ge eq ne "
1537 "getitem setitem delitem "
1538 "len contains iter "
1539 "hash str sizeof "
1540 "enter exit "
1541 "divmod neg pos abs invert "
1542 "complex int float index "
1543 "trunc floor ceil "
1544 "bool next "
1545)
1546
1547numerics = "add sub mul div floordiv mod lshift rshift and xor or pow "
1548inplace = ' '.join('i%s' % n for n in numerics.split())
1549right = ' '.join('r%s' % n for n in numerics.split())
1550
1551# not including __prepare__, __instancecheck__, __subclasscheck__
1552# (as they are metaclass methods)
1553# __del__ is not supported at all as it causes problems if it exists
1554
1555_non_defaults = set('__%s__' % method for method in [
1556 'cmp', 'getslice', 'setslice', 'coerce', 'subclasses',
1557 'format', 'get', 'set', 'delete', 'reversed',
1558 'missing', 'reduce', 'reduce_ex', 'getinitargs',
1559 'getnewargs', 'getstate', 'setstate', 'getformat',
1560 'setformat', 'repr', 'dir'
1561])
1562
1563
1564def _get_method(name, func):
1565 "Turns a callable object (like a mock) into a real function"
1566 def method(self, *args, **kw):
1567 return func(self, *args, **kw)
1568 method.__name__ = name
1569 return method
1570
1571
1572_magics = set(
1573 '__%s__' % method for method in
1574 ' '.join([magic_methods, numerics, inplace, right]).split()
1575)
1576
1577_all_magics = _magics | _non_defaults
1578
1579_unsupported_magics = set([
1580 '__getattr__', '__setattr__',
1581 '__init__', '__new__', '__prepare__'
1582 '__instancecheck__', '__subclasscheck__',
1583 '__del__'
1584])
1585
1586_calculate_return_value = {
1587 '__hash__': lambda self: object.__hash__(self),
1588 '__str__': lambda self: object.__str__(self),
1589 '__sizeof__': lambda self: object.__sizeof__(self),
1590}
1591
1592_return_values = {
1593 '__int__': 1,
1594 '__contains__': False,
1595 '__len__': 0,
1596 '__exit__': False,
1597 '__complex__': 1j,
1598 '__float__': 1.0,
1599 '__bool__': True,
1600 '__index__': 1,
1601}
1602
1603
1604def _get_eq(self):
1605 def __eq__(other):
1606 ret_val = self.__eq__._mock_return_value
1607 if ret_val is not DEFAULT:
1608 return ret_val
1609 return self is other
1610 return __eq__
1611
1612def _get_ne(self):
1613 def __ne__(other):
1614 if self.__ne__._mock_return_value is not DEFAULT:
1615 return DEFAULT
1616 return self is not other
1617 return __ne__
1618
1619def _get_iter(self):
1620 def __iter__():
1621 ret_val = self.__iter__._mock_return_value
1622 if ret_val is DEFAULT:
1623 return iter([])
1624 # if ret_val was already an iterator, then calling iter on it should
1625 # return the iterator unchanged
1626 return iter(ret_val)
1627 return __iter__
1628
1629_side_effect_methods = {
1630 '__eq__': _get_eq,
1631 '__ne__': _get_ne,
1632 '__iter__': _get_iter,
1633}
1634
1635
1636
1637def _set_return_value(mock, method, name):
1638 fixed = _return_values.get(name, DEFAULT)
1639 if fixed is not DEFAULT:
1640 method.return_value = fixed
1641 return
1642
1643 return_calulator = _calculate_return_value.get(name)
1644 if return_calulator is not None:
1645 try:
1646 return_value = return_calulator(mock)
1647 except AttributeError:
1648 # XXXX why do we return AttributeError here?
1649 # set it as a side_effect instead?
1650 return_value = AttributeError(name)
1651 method.return_value = return_value
1652 return
1653
1654 side_effector = _side_effect_methods.get(name)
1655 if side_effector is not None:
1656 method.side_effect = side_effector(mock)
1657
1658
1659
1660class MagicMixin(object):
1661 def __init__(self, *args, **kw):
1662 super(MagicMixin, self).__init__(*args, **kw)
1663 self._mock_set_magics()
1664
1665
1666 def _mock_set_magics(self):
1667 these_magics = _magics
1668
1669 if self._mock_methods is not None:
1670 these_magics = _magics.intersection(self._mock_methods)
1671
1672 remove_magics = set()
1673 remove_magics = _magics - these_magics
1674
1675 for entry in remove_magics:
1676 if entry in type(self).__dict__:
1677 # remove unneeded magic methods
1678 delattr(self, entry)
1679
1680 # don't overwrite existing attributes if called a second time
1681 these_magics = these_magics - set(type(self).__dict__)
1682
1683 _type = type(self)
1684 for entry in these_magics:
1685 setattr(_type, entry, MagicProxy(entry, self))
1686
1687
1688
1689class NonCallableMagicMock(MagicMixin, NonCallableMock):
1690 """A version of `MagicMock` that isn't callable."""
1691 def mock_add_spec(self, spec, spec_set=False):
1692 """Add a spec to a mock. `spec` can either be an object or a
1693 list of strings. Only attributes on the `spec` can be fetched as
1694 attributes from the mock.
1695
1696 If `spec_set` is True then only attributes on the spec can be set."""
1697 self._mock_add_spec(spec, spec_set)
1698 self._mock_set_magics()
1699
1700
1701
1702class MagicMock(MagicMixin, Mock):
1703 """
1704 MagicMock is a subclass of Mock with default implementations
1705 of most of the magic methods. You can use MagicMock without having to
1706 configure the magic methods yourself.
1707
1708 If you use the `spec` or `spec_set` arguments then *only* magic
1709 methods that exist in the spec will be created.
1710
1711 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1712 """
1713 def mock_add_spec(self, spec, spec_set=False):
1714 """Add a spec to a mock. `spec` can either be an object or a
1715 list of strings. Only attributes on the `spec` can be fetched as
1716 attributes from the mock.
1717
1718 If `spec_set` is True then only attributes on the spec can be set."""
1719 self._mock_add_spec(spec, spec_set)
1720 self._mock_set_magics()
1721
1722
1723
1724class MagicProxy(object):
1725 def __init__(self, name, parent):
1726 self.name = name
1727 self.parent = parent
1728
1729 def __call__(self, *args, **kwargs):
1730 m = self.create_mock()
1731 return m(*args, **kwargs)
1732
1733 def create_mock(self):
1734 entry = self.name
1735 parent = self.parent
1736 m = parent._get_child_mock(name=entry, _new_name=entry,
1737 _new_parent=parent)
1738 setattr(parent, entry, m)
1739 _set_return_value(parent, m, entry)
1740 return m
1741
1742 def __get__(self, obj, _type=None):
1743 return self.create_mock()
1744
1745
1746
1747class _ANY(object):
1748 "A helper object that compares equal to everything."
1749
1750 def __eq__(self, other):
1751 return True
1752
1753 def __ne__(self, other):
1754 return False
1755
1756 def __repr__(self):
1757 return '<ANY>'
1758
1759ANY = _ANY()
1760
1761
1762
1763def _format_call_signature(name, args, kwargs):
1764 message = '%s(%%s)' % name
1765 formatted_args = ''
1766 args_string = ', '.join([repr(arg) for arg in args])
1767 kwargs_string = ', '.join([
1768 '%s=%r' % (key, value) for key, value in kwargs.items()
1769 ])
1770 if args_string:
1771 formatted_args = args_string
1772 if kwargs_string:
1773 if formatted_args:
1774 formatted_args += ', '
1775 formatted_args += kwargs_string
1776
1777 return message % formatted_args
1778
1779
1780
1781class _Call(tuple):
1782 """
1783 A tuple for holding the results of a call to a mock, either in the form
1784 `(args, kwargs)` or `(name, args, kwargs)`.
1785
1786 If args or kwargs are empty then a call tuple will compare equal to
1787 a tuple without those values. This makes comparisons less verbose::
1788
1789 _Call(('name', (), {})) == ('name',)
1790 _Call(('name', (1,), {})) == ('name', (1,))
1791 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1792
1793 The `_Call` object provides a useful shortcut for comparing with call::
1794
1795 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1796 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1797
1798 If the _Call has no name then it will match any name.
1799 """
1800 def __new__(cls, value=(), name=None, parent=None, two=False,
1801 from_kall=True):
1802 name = ''
1803 args = ()
1804 kwargs = {}
1805 _len = len(value)
1806 if _len == 3:
1807 name, args, kwargs = value
1808 elif _len == 2:
1809 first, second = value
1810 if isinstance(first, str):
1811 name = first
1812 if isinstance(second, tuple):
1813 args = second
1814 else:
1815 kwargs = second
1816 else:
1817 args, kwargs = first, second
1818 elif _len == 1:
1819 value, = value
1820 if isinstance(value, str):
1821 name = value
1822 elif isinstance(value, tuple):
1823 args = value
1824 else:
1825 kwargs = value
1826
1827 if two:
1828 return tuple.__new__(cls, (args, kwargs))
1829
1830 return tuple.__new__(cls, (name, args, kwargs))
1831
1832
1833 def __init__(self, value=(), name=None, parent=None, two=False,
1834 from_kall=True):
1835 self.name = name
1836 self.parent = parent
1837 self.from_kall = from_kall
1838
1839
1840 def __eq__(self, other):
1841 if other is ANY:
1842 return True
1843 try:
1844 len_other = len(other)
1845 except TypeError:
1846 return False
1847
1848 self_name = ''
1849 if len(self) == 2:
1850 self_args, self_kwargs = self
1851 else:
1852 self_name, self_args, self_kwargs = self
1853
1854 other_name = ''
1855 if len_other == 0:
1856 other_args, other_kwargs = (), {}
1857 elif len_other == 3:
1858 other_name, other_args, other_kwargs = other
1859 elif len_other == 1:
1860 value, = other
1861 if isinstance(value, tuple):
1862 other_args = value
1863 other_kwargs = {}
1864 elif isinstance(value, str):
1865 other_name = value
1866 other_args, other_kwargs = (), {}
1867 else:
1868 other_args = ()
1869 other_kwargs = value
1870 else:
1871 # len 2
1872 # could be (name, args) or (name, kwargs) or (args, kwargs)
1873 first, second = other
1874 if isinstance(first, str):
1875 other_name = first
1876 if isinstance(second, tuple):
1877 other_args, other_kwargs = second, {}
1878 else:
1879 other_args, other_kwargs = (), second
1880 else:
1881 other_args, other_kwargs = first, second
1882
1883 if self_name and other_name != self_name:
1884 return False
1885
1886 # this order is important for ANY to work!
1887 return (other_args, other_kwargs) == (self_args, self_kwargs)
1888
1889
1890 def __ne__(self, other):
1891 return not self.__eq__(other)
1892
1893
1894 def __call__(self, *args, **kwargs):
1895 if self.name is None:
1896 return _Call(('', args, kwargs), name='()')
1897
1898 name = self.name + '()'
1899 return _Call((self.name, args, kwargs), name=name, parent=self)
1900
1901
1902 def __getattr__(self, attr):
1903 if self.name is None:
1904 return _Call(name=attr, from_kall=False)
1905 name = '%s.%s' % (self.name, attr)
1906 return _Call(name=name, parent=self, from_kall=False)
1907
1908
1909 def __repr__(self):
1910 if not self.from_kall:
1911 name = self.name or 'call'
1912 if name.startswith('()'):
1913 name = 'call%s' % name
1914 return name
1915
1916 if len(self) == 2:
1917 name = 'call'
1918 args, kwargs = self
1919 else:
1920 name, args, kwargs = self
1921 if not name:
1922 name = 'call'
1923 elif not name.startswith('()'):
1924 name = 'call.%s' % name
1925 else:
1926 name = 'call%s' % name
1927 return _format_call_signature(name, args, kwargs)
1928
1929
1930 def call_list(self):
1931 """For a call object that represents multiple calls, `call_list`
1932 returns a list of all the intermediate calls as well as the
1933 final call."""
1934 vals = []
1935 thing = self
1936 while thing is not None:
1937 if thing.from_kall:
1938 vals.append(thing)
1939 thing = thing.parent
1940 return _CallList(reversed(vals))
1941
1942
1943call = _Call(from_kall=False)
1944
1945
1946
1947def create_autospec(spec, spec_set=False, instance=False, _parent=None,
1948 _name=None, **kwargs):
1949 """Create a mock object using another object as a spec. Attributes on the
1950 mock will use the corresponding attribute on the `spec` object as their
1951 spec.
1952
1953 Functions or methods being mocked will have their arguments checked
1954 to check that they are called with the correct signature.
1955
1956 If `spec_set` is True then attempting to set attributes that don't exist
1957 on the spec object will raise an `AttributeError`.
1958
1959 If a class is used as a spec then the return value of the mock (the
1960 instance of the class) will have the same spec. You can use a class as the
1961 spec for an instance object by passing `instance=True`. The returned mock
1962 will only be callable if instances of the mock are callable.
1963
1964 `create_autospec` also takes arbitrary keyword arguments that are passed to
1965 the constructor of the created mock."""
1966 if _is_list(spec):
1967 # can't pass a list instance to the mock constructor as it will be
1968 # interpreted as a list of strings
1969 spec = type(spec)
1970
1971 is_type = isinstance(spec, type)
1972
1973 _kwargs = {'spec': spec}
1974 if spec_set:
1975 _kwargs = {'spec_set': spec}
1976 elif spec is None:
1977 # None we mock with a normal mock without a spec
1978 _kwargs = {}
1979
1980 _kwargs.update(kwargs)
1981
1982 Klass = MagicMock
1983 if type(spec) in DescriptorTypes:
1984 # descriptors don't have a spec
1985 # because we don't know what type they return
1986 _kwargs = {}
1987 elif not _callable(spec):
1988 Klass = NonCallableMagicMock
1989 elif is_type and instance and not _instance_callable(spec):
1990 Klass = NonCallableMagicMock
1991
1992 _new_name = _name
1993 if _parent is None:
1994 # for a top level object no _new_name should be set
1995 _new_name = ''
1996
1997 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
1998 name=_name, **_kwargs)
1999
2000 if isinstance(spec, FunctionTypes):
2001 # should only happen at the top level because we don't
2002 # recurse for functions
2003 mock = _set_signature(mock, spec)
2004 else:
2005 _check_signature(spec, mock, is_type, instance)
2006
2007 if _parent is not None and not instance:
2008 _parent._mock_children[_name] = mock
2009
2010 if is_type and not instance and 'return_value' not in kwargs:
2011 # XXXX could give a name to the return_value mock?
2012 mock.return_value = create_autospec(spec, spec_set, instance=True,
2013 _name='()', _parent=mock)
2014
2015 for entry in dir(spec):
2016 if _is_magic(entry):
2017 # MagicMock already does the useful magic methods for us
2018 continue
2019
2020 if isinstance(spec, FunctionTypes) and entry in FunctionAttributes:
2021 # allow a mock to actually be a function
2022 continue
2023
2024 # XXXX do we need a better way of getting attributes without
2025 # triggering code execution (?) Probably not - we need the actual
2026 # object to mock it so we would rather trigger a property than mock
2027 # the property descriptor. Likewise we want to mock out dynamically
2028 # provided attributes.
2029 # XXXX what about attributes that raise exceptions on being fetched
2030 # we could be resilient against it, or catch and propagate the
2031 # exception when the attribute is fetched from the mock
2032 original = getattr(spec, entry)
2033
2034 kwargs = {'spec': original}
2035 if spec_set:
2036 kwargs = {'spec_set': original}
2037
2038 if not isinstance(original, FunctionTypes):
2039 new = _SpecState(original, spec_set, mock, entry, instance)
2040 mock._mock_children[entry] = new
2041 else:
2042 parent = mock
2043 if isinstance(spec, FunctionTypes):
2044 parent = mock.mock
2045
2046 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2047 _new_parent=parent, **kwargs)
2048 mock._mock_children[entry] = new
2049 skipfirst = _must_skip(spec, entry, is_type)
2050 _check_signature(original, new, skipfirst=skipfirst)
2051
2052 # so functions created with _set_signature become instance attributes,
2053 # *plus* their underlying mock exists in _mock_children of the parent
2054 # mock. Adding to _mock_children may be unnecessary where we are also
2055 # setting as an instance attribute?
2056 if isinstance(new, FunctionTypes):
2057 setattr(mock, entry, new)
2058
2059 return mock
2060
2061
2062def _must_skip(spec, entry, is_type):
2063 if not isinstance(spec, type):
2064 if entry in getattr(spec, '__dict__', {}):
2065 # instance attribute - shouldn't skip
2066 return False
2067 # can't use type because of old style classes
2068 spec = spec.__class__
2069 if not hasattr(spec, '__mro__'):
2070 # old style class: can't have descriptors anyway
2071 return is_type
2072
2073 for klass in spec.__mro__:
2074 result = klass.__dict__.get(entry, DEFAULT)
2075 if result is DEFAULT:
2076 continue
2077 if isinstance(result, (staticmethod, classmethod)):
2078 return False
2079 return is_type
2080
2081 # shouldn't get here unless function is a dynamically provided attribute
2082 # XXXX untested behaviour
2083 return is_type
2084
2085
2086def _get_class(obj):
2087 try:
2088 return obj.__class__
2089 except AttributeError:
2090 # in Python 2, _sre.SRE_Pattern objects have no __class__
2091 return type(obj)
2092
2093
2094class _SpecState(object):
2095
2096 def __init__(self, spec, spec_set=False, parent=None,
2097 name=None, ids=None, instance=False):
2098 self.spec = spec
2099 self.ids = ids
2100 self.spec_set = spec_set
2101 self.parent = parent
2102 self.instance = instance
2103 self.name = name
2104
2105
2106FunctionTypes = (
2107 # python function
2108 type(create_autospec),
2109 # instance method
2110 type(ANY.__eq__),
2111 # unbound method
2112 type(_ANY.__eq__),
2113)
2114
2115FunctionAttributes = set([
2116 'func_closure',
2117 'func_code',
2118 'func_defaults',
2119 'func_dict',
2120 'func_doc',
2121 'func_globals',
2122 'func_name',
2123])
2124
2125import _io
2126file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2127
2128
2129def mock_open(mock=None, read_data=None):
2130 if mock is None:
2131 mock = MagicMock(spec=file_spec)
2132
2133 handle = MagicMock(spec=file_spec)
2134 handle.write.return_value = None
2135 handle.__enter__.return_value = handle
2136
2137 if read_data is not None:
2138 handle.read.return_value = read_data
2139
2140 mock.return_value = handle
2141 return mock
2142
2143
2144class PropertyMock(Mock):
2145 """A Mock variant with __get__ and __set__ methods to act as a property"""
2146 def __get__(self, obj, obj_type):
2147 return self()
2148 def __set__(self, obj, val):
2149 self(val)