blob: e6b103d5d6f5c0cc4fbc2cb33d96f5f78911e4fb [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):
Michael Foordd7c65e22012-03-14 14:56:54 -0700622 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord345266a2012-03-14 12:24:34 -0700623 extras = self._mock_methods or []
624 from_type = dir(type(self))
625 from_dict = list(self.__dict__)
626
627 if FILTER_DIR:
628 from_type = [e for e in from_type if not e.startswith('_')]
629 from_dict = [e for e in from_dict if not e.startswith('_') or
630 _is_magic(e)]
631 return sorted(set(extras + from_type + from_dict +
632 list(self._mock_children)))
633
634
635 def __setattr__(self, name, value):
636 if name in _allowed_names:
637 # property setters go through here
638 return object.__setattr__(self, name, value)
639 elif (self._spec_set and self._mock_methods is not None and
640 name not in self._mock_methods and
641 name not in self.__dict__):
642 raise AttributeError("Mock object has no attribute '%s'" % name)
643 elif name in _unsupported_magics:
644 msg = 'Attempting to set unsupported magic method %r.' % name
645 raise AttributeError(msg)
646 elif name in _all_magics:
647 if self._mock_methods is not None and name not in self._mock_methods:
648 raise AttributeError("Mock object has no attribute '%s'" % name)
649
650 if not _is_instance_mock(value):
651 setattr(type(self), name, _get_method(name, value))
652 original = value
653 value = lambda *args, **kw: original(self, *args, **kw)
654 else:
655 # only set _new_name and not name so that mock_calls is tracked
656 # but not method calls
657 _check_and_set_parent(self, value, None, name)
658 setattr(type(self), name, value)
659 elif name == '__class__':
660 self._spec_class = value
661 return
662 else:
663 if _check_and_set_parent(self, value, name, name):
664 self._mock_children[name] = value
665 return object.__setattr__(self, name, value)
666
667
668 def __delattr__(self, name):
669 if name in _all_magics and name in type(self).__dict__:
670 delattr(type(self), name)
671 if name not in self.__dict__:
672 # for magic methods that are still MagicProxy objects and
673 # not set on the instance itself
674 return
675
676 if name in self.__dict__:
677 object.__delattr__(self, name)
678
679 obj = self._mock_children.get(name, _missing)
680 if obj is _deleted:
681 raise AttributeError(name)
682 if obj is not _missing:
683 del self._mock_children[name]
684 self._mock_children[name] = _deleted
685
686
687
688 def _format_mock_call_signature(self, args, kwargs):
689 name = self._mock_name or 'mock'
690 return _format_call_signature(name, args, kwargs)
691
692
693 def _format_mock_failure_message(self, args, kwargs):
694 message = 'Expected call: %s\nActual call: %s'
695 expected_string = self._format_mock_call_signature(args, kwargs)
696 call_args = self.call_args
697 if len(call_args) == 3:
698 call_args = call_args[1:]
699 actual_string = self._format_mock_call_signature(*call_args)
700 return message % (expected_string, actual_string)
701
702
703 def assert_called_with(_mock_self, *args, **kwargs):
704 """assert that the mock was called with the specified arguments.
705
706 Raises an AssertionError if the args and keyword args passed in are
707 different to the last call to the mock."""
708 self = _mock_self
709 if self.call_args is None:
710 expected = self._format_mock_call_signature(args, kwargs)
711 raise AssertionError('Expected call: %s\nNot called' % (expected,))
712
713 if self.call_args != (args, kwargs):
714 msg = self._format_mock_failure_message(args, kwargs)
715 raise AssertionError(msg)
716
717
718 def assert_called_once_with(_mock_self, *args, **kwargs):
719 """assert that the mock was called exactly once and with the specified
720 arguments."""
721 self = _mock_self
722 if not self.call_count == 1:
723 msg = ("Expected to be called once. Called %s times." %
724 self.call_count)
725 raise AssertionError(msg)
726 return self.assert_called_with(*args, **kwargs)
727
728
729 def assert_has_calls(self, calls, any_order=False):
730 """assert the mock has been called with the specified calls.
731 The `mock_calls` list is checked for the calls.
732
733 If `any_order` is False (the default) then the calls must be
734 sequential. There can be extra calls before or after the
735 specified calls.
736
737 If `any_order` is True then the calls can be in any order, but
738 they must all appear in `mock_calls`."""
739 if not any_order:
740 if calls not in self.mock_calls:
741 raise AssertionError(
742 'Calls not found.\nExpected: %r\n'
743 'Actual: %r' % (calls, self.mock_calls)
744 )
745 return
746
747 all_calls = list(self.mock_calls)
748
749 not_found = []
750 for kall in calls:
751 try:
752 all_calls.remove(kall)
753 except ValueError:
754 not_found.append(kall)
755 if not_found:
756 raise AssertionError(
757 '%r not all found in call list' % (tuple(not_found),)
758 )
759
760
761 def assert_any_call(self, *args, **kwargs):
762 """assert the mock has been called with the specified arguments.
763
764 The assert passes if the mock has *ever* been called, unlike
765 `assert_called_with` and `assert_called_once_with` that only pass if
766 the call is the most recent one."""
767 kall = call(*args, **kwargs)
768 if kall not in self.call_args_list:
769 expected_string = self._format_mock_call_signature(args, kwargs)
770 raise AssertionError(
771 '%s call not found' % expected_string
772 )
773
774
775 def _get_child_mock(self, **kw):
776 """Create the child mocks for attributes and return value.
777 By default child mocks will be the same type as the parent.
778 Subclasses of Mock may want to override this to customize the way
779 child mocks are made.
780
781 For non-callable mocks the callable variant will be used (rather than
782 any custom subclass)."""
783 _type = type(self)
784 if not issubclass(_type, CallableMixin):
785 if issubclass(_type, NonCallableMagicMock):
786 klass = MagicMock
787 elif issubclass(_type, NonCallableMock) :
788 klass = Mock
789 else:
790 klass = _type.__mro__[1]
791 return klass(**kw)
792
793
794
795def _try_iter(obj):
796 if obj is None:
797 return obj
798 if _is_exception(obj):
799 return obj
800 if _callable(obj):
801 return obj
802 try:
803 return iter(obj)
804 except TypeError:
805 # XXXX backwards compatibility
806 # but this will blow up on first call - so maybe we should fail early?
807 return obj
808
809
810
811class CallableMixin(Base):
812
813 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
814 wraps=None, name=None, spec_set=None, parent=None,
815 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
816 self.__dict__['_mock_return_value'] = return_value
817
818 super(CallableMixin, self).__init__(
819 spec, wraps, name, spec_set, parent,
820 _spec_state, _new_name, _new_parent, **kwargs
821 )
822
823 self.side_effect = side_effect
824
825
826 def _mock_check_sig(self, *args, **kwargs):
827 # stub method that can be replaced with one with a specific signature
828 pass
829
830
831 def __call__(_mock_self, *args, **kwargs):
832 # can't use self in-case a function / method we are mocking uses self
833 # in the signature
834 _mock_self._mock_check_sig(*args, **kwargs)
835 return _mock_self._mock_call(*args, **kwargs)
836
837
838 def _mock_call(_mock_self, *args, **kwargs):
839 self = _mock_self
840 self.called = True
841 self.call_count += 1
842 self.call_args = _Call((args, kwargs), two=True)
843 self.call_args_list.append(_Call((args, kwargs), two=True))
844
845 _new_name = self._mock_new_name
846 _new_parent = self._mock_new_parent
847 self.mock_calls.append(_Call(('', args, kwargs)))
848
849 seen = set()
850 skip_next_dot = _new_name == '()'
851 do_method_calls = self._mock_parent is not None
852 name = self._mock_name
853 while _new_parent is not None:
854 this_mock_call = _Call((_new_name, args, kwargs))
855 if _new_parent._mock_new_name:
856 dot = '.'
857 if skip_next_dot:
858 dot = ''
859
860 skip_next_dot = False
861 if _new_parent._mock_new_name == '()':
862 skip_next_dot = True
863
864 _new_name = _new_parent._mock_new_name + dot + _new_name
865
866 if do_method_calls:
867 if _new_name == name:
868 this_method_call = this_mock_call
869 else:
870 this_method_call = _Call((name, args, kwargs))
871 _new_parent.method_calls.append(this_method_call)
872
873 do_method_calls = _new_parent._mock_parent is not None
874 if do_method_calls:
875 name = _new_parent._mock_name + '.' + name
876
877 _new_parent.mock_calls.append(this_mock_call)
878 _new_parent = _new_parent._mock_new_parent
879
880 # use ids here so as not to call __hash__ on the mocks
881 _new_parent_id = id(_new_parent)
882 if _new_parent_id in seen:
883 break
884 seen.add(_new_parent_id)
885
886 ret_val = DEFAULT
887 effect = self.side_effect
888 if effect is not None:
889 if _is_exception(effect):
890 raise effect
891
892 if not _callable(effect):
893 return next(effect)
894
895 ret_val = effect(*args, **kwargs)
896 if ret_val is DEFAULT:
897 ret_val = self.return_value
898
899 if (self._mock_wraps is not None and
900 self._mock_return_value is DEFAULT):
901 return self._mock_wraps(*args, **kwargs)
902 if ret_val is DEFAULT:
903 ret_val = self.return_value
904 return ret_val
905
906
907
908class Mock(CallableMixin, NonCallableMock):
909 """
910 Create a new `Mock` object. `Mock` takes several optional arguments
911 that specify the behaviour of the Mock object:
912
913 * `spec`: This can be either a list of strings or an existing object (a
914 class or instance) that acts as the specification for the mock object. If
915 you pass in an object then a list of strings is formed by calling dir on
916 the object (excluding unsupported magic attributes and methods). Accessing
917 any attribute not in this list will raise an `AttributeError`.
918
919 If `spec` is an object (rather than a list of strings) then
920 `mock.__class__` returns the class of the spec object. This allows mocks
921 to pass `isinstance` tests.
922
923 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
924 or get an attribute on the mock that isn't on the object passed as
925 `spec_set` will raise an `AttributeError`.
926
927 * `side_effect`: A function to be called whenever the Mock is called. See
928 the `side_effect` attribute. Useful for raising exceptions or
929 dynamically changing return values. The function is called with the same
930 arguments as the mock, and unless it returns `DEFAULT`, the return
931 value of this function is used as the return value.
932
933 Alternatively `side_effect` can be an exception class or instance. In
934 this case the exception will be raised when the mock is called.
935
936 If `side_effect` is an iterable then each call to the mock will return
937 the next value from the iterable.
938
939 * `return_value`: The value returned when the mock is called. By default
940 this is a new Mock (created on first access). See the
941 `return_value` attribute.
942
943 * `wraps`: Item for the mock object to wrap. If `wraps` is not None
944 then calling the Mock will pass the call through to the wrapped object
945 (returning the real result and ignoring `return_value`). Attribute
946 access on the mock will return a Mock object that wraps the corresponding
947 attribute of the wrapped object (so attempting to access an attribute that
948 doesn't exist will raise an `AttributeError`).
949
950 If the mock has an explicit `return_value` set then calls are not passed
951 to the wrapped object and the `return_value` is returned instead.
952
953 * `name`: If the mock has a name then it will be used in the repr of the
954 mock. This can be useful for debugging. The name is propagated to child
955 mocks.
956
957 Mocks can also be called with arbitrary keyword arguments. These will be
958 used to set attributes on the mock after it is created.
959 """
960
961
962
963def _dot_lookup(thing, comp, import_path):
964 try:
965 return getattr(thing, comp)
966 except AttributeError:
967 __import__(import_path)
968 return getattr(thing, comp)
969
970
971def _importer(target):
972 components = target.split('.')
973 import_path = components.pop(0)
974 thing = __import__(import_path)
975
976 for comp in components:
977 import_path += ".%s" % comp
978 thing = _dot_lookup(thing, comp, import_path)
979 return thing
980
981
982def _is_started(patcher):
983 # XXXX horrible
984 return hasattr(patcher, 'is_local')
985
986
987class _patch(object):
988
989 attribute_name = None
990
991 def __init__(
992 self, getter, attribute, new, spec, create,
993 spec_set, autospec, new_callable, kwargs
994 ):
995 if new_callable is not None:
996 if new is not DEFAULT:
997 raise ValueError(
998 "Cannot use 'new' and 'new_callable' together"
999 )
1000 if autospec is not False:
1001 raise ValueError(
1002 "Cannot use 'autospec' and 'new_callable' together"
1003 )
1004
1005 self.getter = getter
1006 self.attribute = attribute
1007 self.new = new
1008 self.new_callable = new_callable
1009 self.spec = spec
1010 self.create = create
1011 self.has_local = False
1012 self.spec_set = spec_set
1013 self.autospec = autospec
1014 self.kwargs = kwargs
1015 self.additional_patchers = []
1016
1017
1018 def copy(self):
1019 patcher = _patch(
1020 self.getter, self.attribute, self.new, self.spec,
1021 self.create, self.spec_set,
1022 self.autospec, self.new_callable, self.kwargs
1023 )
1024 patcher.attribute_name = self.attribute_name
1025 patcher.additional_patchers = [
1026 p.copy() for p in self.additional_patchers
1027 ]
1028 return patcher
1029
1030
1031 def __call__(self, func):
1032 if isinstance(func, type):
1033 return self.decorate_class(func)
1034 return self.decorate_callable(func)
1035
1036
1037 def decorate_class(self, klass):
1038 for attr in dir(klass):
1039 if not attr.startswith(patch.TEST_PREFIX):
1040 continue
1041
1042 attr_value = getattr(klass, attr)
1043 if not hasattr(attr_value, "__call__"):
1044 continue
1045
1046 patcher = self.copy()
1047 setattr(klass, attr, patcher(attr_value))
1048 return klass
1049
1050
1051 def decorate_callable(self, func):
1052 if hasattr(func, 'patchings'):
1053 func.patchings.append(self)
1054 return func
1055
1056 @wraps(func)
1057 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001058 extra_args = []
1059 entered_patchers = []
1060
Michael Foord345266a2012-03-14 12:24:34 -07001061 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001062 for patching in patched.patchings:
1063 arg = patching.__enter__()
1064 entered_patchers.append(patching)
1065 if patching.attribute_name is not None:
1066 keywargs.update(arg)
1067 elif patching.new is DEFAULT:
1068 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001069
Michael Foordd7c65e22012-03-14 14:56:54 -07001070 args += tuple(extra_args)
1071 return func(*args, **keywargs)
1072 except:
1073 if (patching not in entered_patchers and
1074 _is_started(patching)):
1075 # the patcher may have been started, but an exception
1076 # raised whilst entering one of its additional_patchers
1077 entered_patchers.append(patching)
1078 # re-raise the exception
1079 raise
Michael Foord345266a2012-03-14 12:24:34 -07001080 finally:
1081 for patching in reversed(entered_patchers):
1082 patching.__exit__()
1083
1084 patched.patchings = [self]
1085 if hasattr(func, 'func_code'):
1086 # not in Python 3
1087 patched.compat_co_firstlineno = getattr(
1088 func, "compat_co_firstlineno",
1089 func.func_code.co_firstlineno
1090 )
1091 return patched
1092
1093
1094 def get_original(self):
1095 target = self.getter()
1096 name = self.attribute
1097
1098 original = DEFAULT
1099 local = False
1100
1101 try:
1102 original = target.__dict__[name]
1103 except (AttributeError, KeyError):
1104 original = getattr(target, name, DEFAULT)
1105 else:
1106 local = True
1107
1108 if not self.create and original is DEFAULT:
1109 raise AttributeError(
1110 "%s does not have the attribute %r" % (target, name)
1111 )
1112 return original, local
1113
1114
1115 def __enter__(self):
1116 """Perform the patch."""
1117 new, spec, spec_set = self.new, self.spec, self.spec_set
1118 autospec, kwargs = self.autospec, self.kwargs
1119 new_callable = self.new_callable
1120 self.target = self.getter()
1121
1122 original, local = self.get_original()
1123
1124 if new is DEFAULT and autospec is False:
1125 inherit = False
1126 if spec_set == True:
1127 spec_set = original
1128 elif spec == True:
1129 # set spec to the object we are replacing
1130 spec = original
1131
1132 if (spec or spec_set) is not None:
1133 if isinstance(original, type):
1134 # If we're patching out a class and there is a spec
1135 inherit = True
1136
1137 Klass = MagicMock
1138 _kwargs = {}
1139 if new_callable is not None:
1140 Klass = new_callable
1141 elif (spec or spec_set) is not None:
1142 if not _callable(spec or spec_set):
1143 Klass = NonCallableMagicMock
1144
1145 if spec is not None:
1146 _kwargs['spec'] = spec
1147 if spec_set is not None:
1148 _kwargs['spec_set'] = spec_set
1149
1150 # add a name to mocks
1151 if (isinstance(Klass, type) and
1152 issubclass(Klass, NonCallableMock) and self.attribute):
1153 _kwargs['name'] = self.attribute
1154
1155 _kwargs.update(kwargs)
1156 new = Klass(**_kwargs)
1157
1158 if inherit and _is_instance_mock(new):
1159 # we can only tell if the instance should be callable if the
1160 # spec is not a list
1161 if (not _is_list(spec or spec_set) and not
1162 _instance_callable(spec or spec_set)):
1163 Klass = NonCallableMagicMock
1164
1165 _kwargs.pop('name')
1166 new.return_value = Klass(_new_parent=new, _new_name='()',
1167 **_kwargs)
1168 elif autospec is not False:
1169 # spec is ignored, new *must* be default, spec_set is treated
1170 # as a boolean. Should we check spec is not None and that spec_set
1171 # is a bool?
1172 if new is not DEFAULT:
1173 raise TypeError(
1174 "autospec creates the mock for you. Can't specify "
1175 "autospec and new."
1176 )
1177 spec_set = bool(spec_set)
1178 if autospec is True:
1179 autospec = original
1180
1181 new = create_autospec(autospec, spec_set=spec_set,
1182 _name=self.attribute, **kwargs)
1183 elif kwargs:
1184 # can't set keyword args when we aren't creating the mock
1185 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1186 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1187
1188 new_attr = new
1189
1190 self.temp_original = original
1191 self.is_local = local
1192 setattr(self.target, self.attribute, new_attr)
1193 if self.attribute_name is not None:
1194 extra_args = {}
1195 if self.new is DEFAULT:
1196 extra_args[self.attribute_name] = new
1197 for patching in self.additional_patchers:
1198 arg = patching.__enter__()
1199 if patching.new is DEFAULT:
1200 extra_args.update(arg)
1201 return extra_args
1202
1203 return new
1204
1205
1206 def __exit__(self, *_):
1207 """Undo the patch."""
1208 if not _is_started(self):
1209 raise RuntimeError('stop called on unstarted patcher')
1210
1211 if self.is_local and self.temp_original is not DEFAULT:
1212 setattr(self.target, self.attribute, self.temp_original)
1213 else:
1214 delattr(self.target, self.attribute)
1215 if not self.create and not hasattr(self.target, self.attribute):
1216 # needed for proxy objects like django settings
1217 setattr(self.target, self.attribute, self.temp_original)
1218
1219 del self.temp_original
1220 del self.is_local
1221 del self.target
1222 for patcher in reversed(self.additional_patchers):
1223 if _is_started(patcher):
1224 patcher.__exit__()
1225
1226 start = __enter__
1227 stop = __exit__
1228
1229
1230
1231def _get_target(target):
1232 try:
1233 target, attribute = target.rsplit('.', 1)
1234 except (TypeError, ValueError):
1235 raise TypeError("Need a valid target to patch. You supplied: %r" %
1236 (target,))
1237 getter = lambda: _importer(target)
1238 return getter, attribute
1239
1240
1241def _patch_object(
1242 target, attribute, new=DEFAULT, spec=None,
1243 create=False, spec_set=None, autospec=False,
1244 new_callable=None, **kwargs
1245 ):
1246 """
1247 patch.object(target, attribute, new=DEFAULT, spec=None, create=False,
1248 spec_set=None, autospec=False,
1249 new_callable=None, **kwargs)
1250
1251 patch the named member (`attribute`) on an object (`target`) with a mock
1252 object.
1253
1254 `patch.object` can be used as a decorator, class decorator or a context
1255 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1256 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1257 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1258 the mock object it creates.
1259
1260 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1261 for choosing which methods to wrap.
1262 """
1263 getter = lambda: target
1264 return _patch(
1265 getter, attribute, new, spec, create,
1266 spec_set, autospec, new_callable, kwargs
1267 )
1268
1269
1270def _patch_multiple(target, spec=None, create=False,
1271 spec_set=None, autospec=False,
1272 new_callable=None, **kwargs
1273 ):
1274 """Perform multiple patches in a single call. It takes the object to be
1275 patched (either as an object or a string to fetch the object by importing)
1276 and keyword arguments for the patches::
1277
1278 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1279 ...
1280
1281 Use `DEFAULT` as the value if you want `patch.multiple` to create
1282 mocks for you. In this case the created mocks are passed into a decorated
1283 function by keyword, and a dictionary is returned when `patch.multiple` is
1284 used as a context manager.
1285
1286 `patch.multiple` can be used as a decorator, class decorator or a context
1287 manager. The arguments `spec`, `spec_set`, `create`,
1288 `autospec` and `new_callable` have the same meaning as for `patch`. These
1289 arguments will be applied to *all* patches done by `patch.multiple`.
1290
1291 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1292 for choosing which methods to wrap.
1293 """
1294 if type(target) is str:
1295 getter = lambda: _importer(target)
1296 else:
1297 getter = lambda: target
1298
1299 if not kwargs:
1300 raise ValueError(
1301 'Must supply at least one keyword argument with patch.multiple'
1302 )
1303 # need to wrap in a list for python 3, where items is a view
1304 items = list(kwargs.items())
1305 attribute, new = items[0]
1306 patcher = _patch(
1307 getter, attribute, new, spec, create, spec_set,
1308 autospec, new_callable, {}
1309 )
1310 patcher.attribute_name = attribute
1311 for attribute, new in items[1:]:
1312 this_patcher = _patch(
1313 getter, attribute, new, spec, create, spec_set,
1314 autospec, new_callable, {}
1315 )
1316 this_patcher.attribute_name = attribute
1317 patcher.additional_patchers.append(this_patcher)
1318 return patcher
1319
1320
1321def patch(
1322 target, new=DEFAULT, spec=None, create=False,
1323 spec_set=None, autospec=False,
1324 new_callable=None, **kwargs
1325 ):
1326 """
1327 `patch` acts as a function decorator, class decorator or a context
1328 manager. Inside the body of the function or with statement, the `target`
1329 (specified in the form `'package.module.ClassName'`) is patched
1330 with a `new` object. When the function/with statement exits the patch is
1331 undone.
1332
1333 The `target` is imported and the specified attribute patched with the new
1334 object, so it must be importable from the environment you are calling the
1335 decorator from. The target is imported when the decorated function is
1336 executed, not at decoration time.
1337
1338 If `new` is omitted, then a new `MagicMock` is created and passed in as an
1339 extra argument to the decorated function.
1340
1341 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1342 if patch is creating one for you.
1343
1344 In addition you can pass `spec=True` or `spec_set=True`, which causes
1345 patch to pass in the object being mocked as the spec/spec_set object.
1346
1347 `new_callable` allows you to specify a different class, or callable object,
1348 that will be called to create the `new` object. By default `MagicMock` is
1349 used.
1350
1351 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1352 then the mock with be created with a spec from the object being replaced.
1353 All attributes of the mock will also have the spec of the corresponding
1354 attribute of the object being replaced. Methods and functions being
1355 mocked will have their arguments checked and will raise a `TypeError` if
1356 they are called with the wrong signature. For mocks replacing a class,
1357 their return value (the 'instance') will have the same spec as the class.
1358
1359 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1360 arbitrary object as the spec instead of the one being replaced.
1361
1362 By default `patch` will fail to replace attributes that don't exist. If
1363 you pass in `create=True`, and the attribute doesn't exist, patch will
1364 create the attribute for you when the patched function is called, and
1365 delete it again afterwards. This is useful for writing tests against
1366 attributes that your production code creates at runtime. It is off by by
1367 default because it can be dangerous. With it switched on you can write
1368 passing tests against APIs that don't actually exist!
1369
1370 Patch can be used as a `TestCase` class decorator. It works by
1371 decorating each test method in the class. This reduces the boilerplate
1372 code when your test methods share a common patchings set. `patch` finds
1373 tests by looking for method names that start with `patch.TEST_PREFIX`.
1374 By default this is `test`, which matches the way `unittest` finds tests.
1375 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1376
1377 Patch can be used as a context manager, with the with statement. Here the
1378 patching applies to the indented block after the with statement. If you
1379 use "as" then the patched object will be bound to the name after the
1380 "as"; very useful if `patch` is creating a mock object for you.
1381
1382 `patch` takes arbitrary keyword arguments. These will be passed to
1383 the `Mock` (or `new_callable`) on construction.
1384
1385 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1386 available for alternate use-cases.
1387 """
1388 getter, attribute = _get_target(target)
1389 return _patch(
1390 getter, attribute, new, spec, create,
1391 spec_set, autospec, new_callable, kwargs
1392 )
1393
1394
1395class _patch_dict(object):
1396 """
1397 Patch a dictionary, or dictionary like object, and restore the dictionary
1398 to its original state after the test.
1399
1400 `in_dict` can be a dictionary or a mapping like container. If it is a
1401 mapping then it must at least support getting, setting and deleting items
1402 plus iterating over keys.
1403
1404 `in_dict` can also be a string specifying the name of the dictionary, which
1405 will then be fetched by importing it.
1406
1407 `values` can be a dictionary of values to set in the dictionary. `values`
1408 can also be an iterable of `(key, value)` pairs.
1409
1410 If `clear` is True then the dictionary will be cleared before the new
1411 values are set.
1412
1413 `patch.dict` can also be called with arbitrary keyword arguments to set
1414 values in the dictionary::
1415
1416 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1417 ...
1418
1419 `patch.dict` can be used as a context manager, decorator or class
1420 decorator. When used as a class decorator `patch.dict` honours
1421 `patch.TEST_PREFIX` for choosing which methods to wrap.
1422 """
1423
1424 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1425 if isinstance(in_dict, str):
1426 in_dict = _importer(in_dict)
1427 self.in_dict = in_dict
1428 # support any argument supported by dict(...) constructor
1429 self.values = dict(values)
1430 self.values.update(kwargs)
1431 self.clear = clear
1432 self._original = None
1433
1434
1435 def __call__(self, f):
1436 if isinstance(f, type):
1437 return self.decorate_class(f)
1438 @wraps(f)
1439 def _inner(*args, **kw):
1440 self._patch_dict()
1441 try:
1442 return f(*args, **kw)
1443 finally:
1444 self._unpatch_dict()
1445
1446 return _inner
1447
1448
1449 def decorate_class(self, klass):
1450 for attr in dir(klass):
1451 attr_value = getattr(klass, attr)
1452 if (attr.startswith(patch.TEST_PREFIX) and
1453 hasattr(attr_value, "__call__")):
1454 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1455 decorated = decorator(attr_value)
1456 setattr(klass, attr, decorated)
1457 return klass
1458
1459
1460 def __enter__(self):
1461 """Patch the dict."""
1462 self._patch_dict()
1463
1464
1465 def _patch_dict(self):
1466 values = self.values
1467 in_dict = self.in_dict
1468 clear = self.clear
1469
1470 try:
1471 original = in_dict.copy()
1472 except AttributeError:
1473 # dict like object with no copy method
1474 # must support iteration over keys
1475 original = {}
1476 for key in in_dict:
1477 original[key] = in_dict[key]
1478 self._original = original
1479
1480 if clear:
1481 _clear_dict(in_dict)
1482
1483 try:
1484 in_dict.update(values)
1485 except AttributeError:
1486 # dict like object with no update method
1487 for key in values:
1488 in_dict[key] = values[key]
1489
1490
1491 def _unpatch_dict(self):
1492 in_dict = self.in_dict
1493 original = self._original
1494
1495 _clear_dict(in_dict)
1496
1497 try:
1498 in_dict.update(original)
1499 except AttributeError:
1500 for key in original:
1501 in_dict[key] = original[key]
1502
1503
1504 def __exit__(self, *args):
1505 """Unpatch the dict."""
1506 self._unpatch_dict()
1507 return False
1508
1509 start = __enter__
1510 stop = __exit__
1511
1512
1513def _clear_dict(in_dict):
1514 try:
1515 in_dict.clear()
1516 except AttributeError:
1517 keys = list(in_dict)
1518 for key in keys:
1519 del in_dict[key]
1520
1521
1522patch.object = _patch_object
1523patch.dict = _patch_dict
1524patch.multiple = _patch_multiple
1525patch.TEST_PREFIX = 'test'
1526
1527magic_methods = (
1528 "lt le gt ge eq ne "
1529 "getitem setitem delitem "
1530 "len contains iter "
1531 "hash str sizeof "
1532 "enter exit "
1533 "divmod neg pos abs invert "
1534 "complex int float index "
1535 "trunc floor ceil "
1536 "bool next "
1537)
1538
1539numerics = "add sub mul div floordiv mod lshift rshift and xor or pow "
1540inplace = ' '.join('i%s' % n for n in numerics.split())
1541right = ' '.join('r%s' % n for n in numerics.split())
1542
1543# not including __prepare__, __instancecheck__, __subclasscheck__
1544# (as they are metaclass methods)
1545# __del__ is not supported at all as it causes problems if it exists
1546
1547_non_defaults = set('__%s__' % method for method in [
1548 'cmp', 'getslice', 'setslice', 'coerce', 'subclasses',
1549 'format', 'get', 'set', 'delete', 'reversed',
1550 'missing', 'reduce', 'reduce_ex', 'getinitargs',
1551 'getnewargs', 'getstate', 'setstate', 'getformat',
1552 'setformat', 'repr', 'dir'
1553])
1554
1555
1556def _get_method(name, func):
1557 "Turns a callable object (like a mock) into a real function"
1558 def method(self, *args, **kw):
1559 return func(self, *args, **kw)
1560 method.__name__ = name
1561 return method
1562
1563
1564_magics = set(
1565 '__%s__' % method for method in
1566 ' '.join([magic_methods, numerics, inplace, right]).split()
1567)
1568
1569_all_magics = _magics | _non_defaults
1570
1571_unsupported_magics = set([
1572 '__getattr__', '__setattr__',
1573 '__init__', '__new__', '__prepare__'
1574 '__instancecheck__', '__subclasscheck__',
1575 '__del__'
1576])
1577
1578_calculate_return_value = {
1579 '__hash__': lambda self: object.__hash__(self),
1580 '__str__': lambda self: object.__str__(self),
1581 '__sizeof__': lambda self: object.__sizeof__(self),
1582}
1583
1584_return_values = {
1585 '__int__': 1,
1586 '__contains__': False,
1587 '__len__': 0,
1588 '__exit__': False,
1589 '__complex__': 1j,
1590 '__float__': 1.0,
1591 '__bool__': True,
1592 '__index__': 1,
1593}
1594
1595
1596def _get_eq(self):
1597 def __eq__(other):
1598 ret_val = self.__eq__._mock_return_value
1599 if ret_val is not DEFAULT:
1600 return ret_val
1601 return self is other
1602 return __eq__
1603
1604def _get_ne(self):
1605 def __ne__(other):
1606 if self.__ne__._mock_return_value is not DEFAULT:
1607 return DEFAULT
1608 return self is not other
1609 return __ne__
1610
1611def _get_iter(self):
1612 def __iter__():
1613 ret_val = self.__iter__._mock_return_value
1614 if ret_val is DEFAULT:
1615 return iter([])
1616 # if ret_val was already an iterator, then calling iter on it should
1617 # return the iterator unchanged
1618 return iter(ret_val)
1619 return __iter__
1620
1621_side_effect_methods = {
1622 '__eq__': _get_eq,
1623 '__ne__': _get_ne,
1624 '__iter__': _get_iter,
1625}
1626
1627
1628
1629def _set_return_value(mock, method, name):
1630 fixed = _return_values.get(name, DEFAULT)
1631 if fixed is not DEFAULT:
1632 method.return_value = fixed
1633 return
1634
1635 return_calulator = _calculate_return_value.get(name)
1636 if return_calulator is not None:
1637 try:
1638 return_value = return_calulator(mock)
1639 except AttributeError:
1640 # XXXX why do we return AttributeError here?
1641 # set it as a side_effect instead?
1642 return_value = AttributeError(name)
1643 method.return_value = return_value
1644 return
1645
1646 side_effector = _side_effect_methods.get(name)
1647 if side_effector is not None:
1648 method.side_effect = side_effector(mock)
1649
1650
1651
1652class MagicMixin(object):
1653 def __init__(self, *args, **kw):
1654 super(MagicMixin, self).__init__(*args, **kw)
1655 self._mock_set_magics()
1656
1657
1658 def _mock_set_magics(self):
1659 these_magics = _magics
1660
1661 if self._mock_methods is not None:
1662 these_magics = _magics.intersection(self._mock_methods)
1663
1664 remove_magics = set()
1665 remove_magics = _magics - these_magics
1666
1667 for entry in remove_magics:
1668 if entry in type(self).__dict__:
1669 # remove unneeded magic methods
1670 delattr(self, entry)
1671
1672 # don't overwrite existing attributes if called a second time
1673 these_magics = these_magics - set(type(self).__dict__)
1674
1675 _type = type(self)
1676 for entry in these_magics:
1677 setattr(_type, entry, MagicProxy(entry, self))
1678
1679
1680
1681class NonCallableMagicMock(MagicMixin, NonCallableMock):
1682 """A version of `MagicMock` that isn't callable."""
1683 def mock_add_spec(self, spec, spec_set=False):
1684 """Add a spec to a mock. `spec` can either be an object or a
1685 list of strings. Only attributes on the `spec` can be fetched as
1686 attributes from the mock.
1687
1688 If `spec_set` is True then only attributes on the spec can be set."""
1689 self._mock_add_spec(spec, spec_set)
1690 self._mock_set_magics()
1691
1692
1693
1694class MagicMock(MagicMixin, Mock):
1695 """
1696 MagicMock is a subclass of Mock with default implementations
1697 of most of the magic methods. You can use MagicMock without having to
1698 configure the magic methods yourself.
1699
1700 If you use the `spec` or `spec_set` arguments then *only* magic
1701 methods that exist in the spec will be created.
1702
1703 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1704 """
1705 def mock_add_spec(self, spec, spec_set=False):
1706 """Add a spec to a mock. `spec` can either be an object or a
1707 list of strings. Only attributes on the `spec` can be fetched as
1708 attributes from the mock.
1709
1710 If `spec_set` is True then only attributes on the spec can be set."""
1711 self._mock_add_spec(spec, spec_set)
1712 self._mock_set_magics()
1713
1714
1715
1716class MagicProxy(object):
1717 def __init__(self, name, parent):
1718 self.name = name
1719 self.parent = parent
1720
1721 def __call__(self, *args, **kwargs):
1722 m = self.create_mock()
1723 return m(*args, **kwargs)
1724
1725 def create_mock(self):
1726 entry = self.name
1727 parent = self.parent
1728 m = parent._get_child_mock(name=entry, _new_name=entry,
1729 _new_parent=parent)
1730 setattr(parent, entry, m)
1731 _set_return_value(parent, m, entry)
1732 return m
1733
1734 def __get__(self, obj, _type=None):
1735 return self.create_mock()
1736
1737
1738
1739class _ANY(object):
1740 "A helper object that compares equal to everything."
1741
1742 def __eq__(self, other):
1743 return True
1744
1745 def __ne__(self, other):
1746 return False
1747
1748 def __repr__(self):
1749 return '<ANY>'
1750
1751ANY = _ANY()
1752
1753
1754
1755def _format_call_signature(name, args, kwargs):
1756 message = '%s(%%s)' % name
1757 formatted_args = ''
1758 args_string = ', '.join([repr(arg) for arg in args])
1759 kwargs_string = ', '.join([
1760 '%s=%r' % (key, value) for key, value in kwargs.items()
1761 ])
1762 if args_string:
1763 formatted_args = args_string
1764 if kwargs_string:
1765 if formatted_args:
1766 formatted_args += ', '
1767 formatted_args += kwargs_string
1768
1769 return message % formatted_args
1770
1771
1772
1773class _Call(tuple):
1774 """
1775 A tuple for holding the results of a call to a mock, either in the form
1776 `(args, kwargs)` or `(name, args, kwargs)`.
1777
1778 If args or kwargs are empty then a call tuple will compare equal to
1779 a tuple without those values. This makes comparisons less verbose::
1780
1781 _Call(('name', (), {})) == ('name',)
1782 _Call(('name', (1,), {})) == ('name', (1,))
1783 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1784
1785 The `_Call` object provides a useful shortcut for comparing with call::
1786
1787 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1788 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1789
1790 If the _Call has no name then it will match any name.
1791 """
1792 def __new__(cls, value=(), name=None, parent=None, two=False,
1793 from_kall=True):
1794 name = ''
1795 args = ()
1796 kwargs = {}
1797 _len = len(value)
1798 if _len == 3:
1799 name, args, kwargs = value
1800 elif _len == 2:
1801 first, second = value
1802 if isinstance(first, str):
1803 name = first
1804 if isinstance(second, tuple):
1805 args = second
1806 else:
1807 kwargs = second
1808 else:
1809 args, kwargs = first, second
1810 elif _len == 1:
1811 value, = value
1812 if isinstance(value, str):
1813 name = value
1814 elif isinstance(value, tuple):
1815 args = value
1816 else:
1817 kwargs = value
1818
1819 if two:
1820 return tuple.__new__(cls, (args, kwargs))
1821
1822 return tuple.__new__(cls, (name, args, kwargs))
1823
1824
1825 def __init__(self, value=(), name=None, parent=None, two=False,
1826 from_kall=True):
1827 self.name = name
1828 self.parent = parent
1829 self.from_kall = from_kall
1830
1831
1832 def __eq__(self, other):
1833 if other is ANY:
1834 return True
1835 try:
1836 len_other = len(other)
1837 except TypeError:
1838 return False
1839
1840 self_name = ''
1841 if len(self) == 2:
1842 self_args, self_kwargs = self
1843 else:
1844 self_name, self_args, self_kwargs = self
1845
1846 other_name = ''
1847 if len_other == 0:
1848 other_args, other_kwargs = (), {}
1849 elif len_other == 3:
1850 other_name, other_args, other_kwargs = other
1851 elif len_other == 1:
1852 value, = other
1853 if isinstance(value, tuple):
1854 other_args = value
1855 other_kwargs = {}
1856 elif isinstance(value, str):
1857 other_name = value
1858 other_args, other_kwargs = (), {}
1859 else:
1860 other_args = ()
1861 other_kwargs = value
1862 else:
1863 # len 2
1864 # could be (name, args) or (name, kwargs) or (args, kwargs)
1865 first, second = other
1866 if isinstance(first, str):
1867 other_name = first
1868 if isinstance(second, tuple):
1869 other_args, other_kwargs = second, {}
1870 else:
1871 other_args, other_kwargs = (), second
1872 else:
1873 other_args, other_kwargs = first, second
1874
1875 if self_name and other_name != self_name:
1876 return False
1877
1878 # this order is important for ANY to work!
1879 return (other_args, other_kwargs) == (self_args, self_kwargs)
1880
1881
1882 def __ne__(self, other):
1883 return not self.__eq__(other)
1884
1885
1886 def __call__(self, *args, **kwargs):
1887 if self.name is None:
1888 return _Call(('', args, kwargs), name='()')
1889
1890 name = self.name + '()'
1891 return _Call((self.name, args, kwargs), name=name, parent=self)
1892
1893
1894 def __getattr__(self, attr):
1895 if self.name is None:
1896 return _Call(name=attr, from_kall=False)
1897 name = '%s.%s' % (self.name, attr)
1898 return _Call(name=name, parent=self, from_kall=False)
1899
1900
1901 def __repr__(self):
1902 if not self.from_kall:
1903 name = self.name or 'call'
1904 if name.startswith('()'):
1905 name = 'call%s' % name
1906 return name
1907
1908 if len(self) == 2:
1909 name = 'call'
1910 args, kwargs = self
1911 else:
1912 name, args, kwargs = self
1913 if not name:
1914 name = 'call'
1915 elif not name.startswith('()'):
1916 name = 'call.%s' % name
1917 else:
1918 name = 'call%s' % name
1919 return _format_call_signature(name, args, kwargs)
1920
1921
1922 def call_list(self):
1923 """For a call object that represents multiple calls, `call_list`
1924 returns a list of all the intermediate calls as well as the
1925 final call."""
1926 vals = []
1927 thing = self
1928 while thing is not None:
1929 if thing.from_kall:
1930 vals.append(thing)
1931 thing = thing.parent
1932 return _CallList(reversed(vals))
1933
1934
1935call = _Call(from_kall=False)
1936
1937
1938
1939def create_autospec(spec, spec_set=False, instance=False, _parent=None,
1940 _name=None, **kwargs):
1941 """Create a mock object using another object as a spec. Attributes on the
1942 mock will use the corresponding attribute on the `spec` object as their
1943 spec.
1944
1945 Functions or methods being mocked will have their arguments checked
1946 to check that they are called with the correct signature.
1947
1948 If `spec_set` is True then attempting to set attributes that don't exist
1949 on the spec object will raise an `AttributeError`.
1950
1951 If a class is used as a spec then the return value of the mock (the
1952 instance of the class) will have the same spec. You can use a class as the
1953 spec for an instance object by passing `instance=True`. The returned mock
1954 will only be callable if instances of the mock are callable.
1955
1956 `create_autospec` also takes arbitrary keyword arguments that are passed to
1957 the constructor of the created mock."""
1958 if _is_list(spec):
1959 # can't pass a list instance to the mock constructor as it will be
1960 # interpreted as a list of strings
1961 spec = type(spec)
1962
1963 is_type = isinstance(spec, type)
1964
1965 _kwargs = {'spec': spec}
1966 if spec_set:
1967 _kwargs = {'spec_set': spec}
1968 elif spec is None:
1969 # None we mock with a normal mock without a spec
1970 _kwargs = {}
1971
1972 _kwargs.update(kwargs)
1973
1974 Klass = MagicMock
1975 if type(spec) in DescriptorTypes:
1976 # descriptors don't have a spec
1977 # because we don't know what type they return
1978 _kwargs = {}
1979 elif not _callable(spec):
1980 Klass = NonCallableMagicMock
1981 elif is_type and instance and not _instance_callable(spec):
1982 Klass = NonCallableMagicMock
1983
1984 _new_name = _name
1985 if _parent is None:
1986 # for a top level object no _new_name should be set
1987 _new_name = ''
1988
1989 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
1990 name=_name, **_kwargs)
1991
1992 if isinstance(spec, FunctionTypes):
1993 # should only happen at the top level because we don't
1994 # recurse for functions
1995 mock = _set_signature(mock, spec)
1996 else:
1997 _check_signature(spec, mock, is_type, instance)
1998
1999 if _parent is not None and not instance:
2000 _parent._mock_children[_name] = mock
2001
2002 if is_type and not instance and 'return_value' not in kwargs:
2003 # XXXX could give a name to the return_value mock?
2004 mock.return_value = create_autospec(spec, spec_set, instance=True,
2005 _name='()', _parent=mock)
2006
2007 for entry in dir(spec):
2008 if _is_magic(entry):
2009 # MagicMock already does the useful magic methods for us
2010 continue
2011
2012 if isinstance(spec, FunctionTypes) and entry in FunctionAttributes:
2013 # allow a mock to actually be a function
2014 continue
2015
2016 # XXXX do we need a better way of getting attributes without
2017 # triggering code execution (?) Probably not - we need the actual
2018 # object to mock it so we would rather trigger a property than mock
2019 # the property descriptor. Likewise we want to mock out dynamically
2020 # provided attributes.
2021 # XXXX what about attributes that raise exceptions on being fetched
2022 # we could be resilient against it, or catch and propagate the
2023 # exception when the attribute is fetched from the mock
2024 original = getattr(spec, entry)
2025
2026 kwargs = {'spec': original}
2027 if spec_set:
2028 kwargs = {'spec_set': original}
2029
2030 if not isinstance(original, FunctionTypes):
2031 new = _SpecState(original, spec_set, mock, entry, instance)
2032 mock._mock_children[entry] = new
2033 else:
2034 parent = mock
2035 if isinstance(spec, FunctionTypes):
2036 parent = mock.mock
2037
2038 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2039 _new_parent=parent, **kwargs)
2040 mock._mock_children[entry] = new
2041 skipfirst = _must_skip(spec, entry, is_type)
2042 _check_signature(original, new, skipfirst=skipfirst)
2043
2044 # so functions created with _set_signature become instance attributes,
2045 # *plus* their underlying mock exists in _mock_children of the parent
2046 # mock. Adding to _mock_children may be unnecessary where we are also
2047 # setting as an instance attribute?
2048 if isinstance(new, FunctionTypes):
2049 setattr(mock, entry, new)
2050
2051 return mock
2052
2053
2054def _must_skip(spec, entry, is_type):
2055 if not isinstance(spec, type):
2056 if entry in getattr(spec, '__dict__', {}):
2057 # instance attribute - shouldn't skip
2058 return False
Michael Foord345266a2012-03-14 12:24:34 -07002059 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002060
2061 for klass in spec.__mro__:
2062 result = klass.__dict__.get(entry, DEFAULT)
2063 if result is DEFAULT:
2064 continue
2065 if isinstance(result, (staticmethod, classmethod)):
2066 return False
2067 return is_type
2068
2069 # shouldn't get here unless function is a dynamically provided attribute
2070 # XXXX untested behaviour
2071 return is_type
2072
2073
2074def _get_class(obj):
2075 try:
2076 return obj.__class__
2077 except AttributeError:
2078 # in Python 2, _sre.SRE_Pattern objects have no __class__
2079 return type(obj)
2080
2081
2082class _SpecState(object):
2083
2084 def __init__(self, spec, spec_set=False, parent=None,
2085 name=None, ids=None, instance=False):
2086 self.spec = spec
2087 self.ids = ids
2088 self.spec_set = spec_set
2089 self.parent = parent
2090 self.instance = instance
2091 self.name = name
2092
2093
2094FunctionTypes = (
2095 # python function
2096 type(create_autospec),
2097 # instance method
2098 type(ANY.__eq__),
2099 # unbound method
2100 type(_ANY.__eq__),
2101)
2102
2103FunctionAttributes = set([
2104 'func_closure',
2105 'func_code',
2106 'func_defaults',
2107 'func_dict',
2108 'func_doc',
2109 'func_globals',
2110 'func_name',
2111])
2112
2113import _io
2114file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2115
2116
2117def mock_open(mock=None, read_data=None):
2118 if mock is None:
2119 mock = MagicMock(spec=file_spec)
2120
2121 handle = MagicMock(spec=file_spec)
2122 handle.write.return_value = None
2123 handle.__enter__.return_value = handle
2124
2125 if read_data is not None:
2126 handle.read.return_value = read_data
2127
2128 mock.return_value = handle
2129 return mock
2130
2131
2132class PropertyMock(Mock):
2133 """A Mock variant with __get__ and __set__ methods to act as a property"""
2134 def __get__(self, obj, obj_type):
2135 return self()
2136 def __set__(self, obj, val):
2137 self(val)