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