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