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