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