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