blob: 42cf23abb733260dcfa2775c5bead29a147e6cdf [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
Michael Foordfddcfa22014-04-14 16:25:20 -040030import builtins
31from types import ModuleType
Antoine Pitrou5c64df72013-02-03 00:23:58 +010032from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070033
34
Michael Foordfddcfa22014-04-14 16:25:20 -040035_builtins = {name for name in dir(builtins) if not name.startswith('_')}
36
Michael Foord345266a2012-03-14 12:24:34 -070037BaseExceptions = (BaseException,)
38if 'java' in sys.platform:
39 # jython
40 import java
41 BaseExceptions = (BaseException, java.lang.Throwable)
42
43
44FILTER_DIR = True
45
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100046# Workaround for issue #12370
47# Without this, the __class__ properties wouldn't be set correctly
48_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070049
50def _is_instance_mock(obj):
51 # can't use isinstance on Mock objects because they override __class__
52 # The base class for all mocks is NonCallableMock
53 return issubclass(type(obj), NonCallableMock)
54
55
56def _is_exception(obj):
57 return (
58 isinstance(obj, BaseExceptions) or
59 isinstance(obj, type) and issubclass(obj, BaseExceptions)
60 )
61
62
63class _slotted(object):
64 __slots__ = ['a']
65
66
67DescriptorTypes = (
68 type(_slotted.a),
69 property,
70)
71
72
Antoine Pitrou5c64df72013-02-03 00:23:58 +010073def _get_signature_object(func, as_instance, eat_self):
74 """
75 Given an arbitrary, possibly callable object, try to create a suitable
76 signature object.
77 Return a (reduced func, signature) tuple, or None.
78 """
79 if isinstance(func, type) and not as_instance:
80 # If it's a type and should be modelled as a type, use __init__.
Michael Foord345266a2012-03-14 12:24:34 -070081 try:
82 func = func.__init__
83 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010084 return None
85 # Skip the `self` argument in __init__
86 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070087 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010088 # If we really want to model an instance of the passed type,
89 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070090 try:
91 func = func.__call__
92 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010093 return None
94 if eat_self:
95 sig_func = partial(func, None)
96 else:
97 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -070098 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010099 return func, inspect.signature(sig_func)
100 except ValueError:
101 # Certain callable types are not supported by inspect.signature()
102 return None
Michael Foord345266a2012-03-14 12:24:34 -0700103
104
105def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100106 sig = _get_signature_object(func, instance, skipfirst)
107 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700108 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100109 func, sig = sig
110 def checksig(_mock_self, *args, **kwargs):
111 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700112 _copy_func_details(func, checksig)
113 type(mock)._mock_check_sig = checksig
114
115
116def _copy_func_details(func, funcopy):
117 funcopy.__name__ = func.__name__
118 funcopy.__doc__ = func.__doc__
Larry Hastings5c661892014-01-24 06:17:25 -0800119 try:
120 funcopy.__text_signature__ = func.__text_signature__
121 except AttributeError:
122 pass
Michael Foord345266a2012-03-14 12:24:34 -0700123 # we explicitly don't copy func.__dict__ into this copy as it would
124 # expose original attributes that should be mocked
Larry Hastings5c661892014-01-24 06:17:25 -0800125 try:
126 funcopy.__module__ = func.__module__
127 except AttributeError:
128 pass
129 try:
130 funcopy.__defaults__ = func.__defaults__
131 except AttributeError:
132 pass
133 try:
134 funcopy.__kwdefaults__ = func.__kwdefaults__
135 except AttributeError:
136 pass
Michael Foord345266a2012-03-14 12:24:34 -0700137
138
139def _callable(obj):
140 if isinstance(obj, type):
141 return True
142 if getattr(obj, '__call__', None) is not None:
143 return True
144 return False
145
146
147def _is_list(obj):
148 # checks for list or tuples
149 # XXXX badly named!
150 return type(obj) in (list, tuple)
151
152
153def _instance_callable(obj):
154 """Given an object, return True if the object is callable.
155 For classes, return True if instances would be callable."""
156 if not isinstance(obj, type):
157 # already an instance
158 return getattr(obj, '__call__', None) is not None
159
Michael Foorda74b3aa2012-03-14 14:40:22 -0700160 # *could* be broken by a class overriding __mro__ or __dict__ via
161 # a metaclass
162 for base in (obj,) + obj.__mro__:
163 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700164 return True
165 return False
166
167
168def _set_signature(mock, original, instance=False):
169 # creates a function with signature (*args, **kwargs) that delegates to a
170 # mock. It still does signature checking by calling a lambda with the same
171 # signature as the original.
172 if not _callable(original):
173 return
174
175 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100176 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700177 if result is None:
Michael Foord345266a2012-03-14 12:24:34 -0700178 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100179 func, sig = result
180 def checksig(*args, **kwargs):
181 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700182 _copy_func_details(func, checksig)
183
184 name = original.__name__
185 if not name.isidentifier():
186 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100187 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700188 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100189 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700190 return mock(*args, **kwargs)""" % name
191 exec (src, context)
192 funcopy = context[name]
193 _setup_func(funcopy, mock)
194 return funcopy
195
196
197def _setup_func(funcopy, mock):
198 funcopy.mock = mock
199
200 # can't use isinstance with mocks
201 if not _is_instance_mock(mock):
202 return
203
204 def assert_called_with(*args, **kwargs):
205 return mock.assert_called_with(*args, **kwargs)
206 def assert_called_once_with(*args, **kwargs):
207 return mock.assert_called_once_with(*args, **kwargs)
208 def assert_has_calls(*args, **kwargs):
209 return mock.assert_has_calls(*args, **kwargs)
210 def assert_any_call(*args, **kwargs):
211 return mock.assert_any_call(*args, **kwargs)
212 def reset_mock():
213 funcopy.method_calls = _CallList()
214 funcopy.mock_calls = _CallList()
215 mock.reset_mock()
216 ret = funcopy.return_value
217 if _is_instance_mock(ret) and not ret is mock:
218 ret.reset_mock()
219
220 funcopy.called = False
221 funcopy.call_count = 0
222 funcopy.call_args = None
223 funcopy.call_args_list = _CallList()
224 funcopy.method_calls = _CallList()
225 funcopy.mock_calls = _CallList()
226
227 funcopy.return_value = mock.return_value
228 funcopy.side_effect = mock.side_effect
229 funcopy._mock_children = mock._mock_children
230
231 funcopy.assert_called_with = assert_called_with
232 funcopy.assert_called_once_with = assert_called_once_with
233 funcopy.assert_has_calls = assert_has_calls
234 funcopy.assert_any_call = assert_any_call
235 funcopy.reset_mock = reset_mock
236
237 mock._mock_delegate = funcopy
238
239
240def _is_magic(name):
241 return '__%s__' % name[2:-2] == name
242
243
244class _SentinelObject(object):
245 "A unique, named, sentinel object."
246 def __init__(self, name):
247 self.name = name
248
249 def __repr__(self):
250 return 'sentinel.%s' % self.name
251
252
253class _Sentinel(object):
254 """Access attributes to return a named object, usable as a sentinel."""
255 def __init__(self):
256 self._sentinels = {}
257
258 def __getattr__(self, name):
259 if name == '__bases__':
260 # Without this help(unittest.mock) raises an exception
261 raise AttributeError
262 return self._sentinels.setdefault(name, _SentinelObject(name))
263
264
265sentinel = _Sentinel()
266
267DEFAULT = sentinel.DEFAULT
268_missing = sentinel.MISSING
269_deleted = sentinel.DELETED
270
271
Michael Foord345266a2012-03-14 12:24:34 -0700272def _copy(value):
273 if type(value) in (dict, list, tuple, set):
274 return type(value)(value)
275 return value
276
277
278_allowed_names = set(
279 [
280 'return_value', '_mock_return_value', 'side_effect',
281 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
282 '_mock_name', '_mock_new_name'
283 ]
284)
285
286
287def _delegating_property(name):
288 _allowed_names.add(name)
289 _the_name = '_mock_' + name
290 def _get(self, name=name, _the_name=_the_name):
291 sig = self._mock_delegate
292 if sig is None:
293 return getattr(self, _the_name)
294 return getattr(sig, name)
295 def _set(self, value, name=name, _the_name=_the_name):
296 sig = self._mock_delegate
297 if sig is None:
298 self.__dict__[_the_name] = value
299 else:
300 setattr(sig, name, value)
301
302 return property(_get, _set)
303
304
305
306class _CallList(list):
307
308 def __contains__(self, value):
309 if not isinstance(value, list):
310 return list.__contains__(self, value)
311 len_value = len(value)
312 len_self = len(self)
313 if len_value > len_self:
314 return False
315
316 for i in range(0, len_self - len_value + 1):
317 sub_list = self[i:i+len_value]
318 if sub_list == value:
319 return True
320 return False
321
322 def __repr__(self):
323 return pprint.pformat(list(self))
324
325
326def _check_and_set_parent(parent, value, name, new_name):
327 if not _is_instance_mock(value):
328 return False
329 if ((value._mock_name or value._mock_new_name) or
330 (value._mock_parent is not None) or
331 (value._mock_new_parent is not None)):
332 return False
333
334 _parent = parent
335 while _parent is not None:
336 # setting a mock (value) as a child or return value of itself
337 # should not modify the mock
338 if _parent is value:
339 return False
340 _parent = _parent._mock_new_parent
341
342 if new_name:
343 value._mock_new_parent = parent
344 value._mock_new_name = new_name
345 if name:
346 value._mock_parent = parent
347 value._mock_name = name
348 return True
349
Michael Foord01bafdc2014-04-14 16:09:42 -0400350# Internal class to identify if we wrapped an iterator object or not.
351class _MockIter(object):
352 def __init__(self, obj):
353 self.obj = iter(obj)
354 def __iter__(self):
355 return self
356 def __next__(self):
357 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700358
359class Base(object):
360 _mock_return_value = DEFAULT
361 _mock_side_effect = None
362 def __init__(self, *args, **kwargs):
363 pass
364
365
366
367class NonCallableMock(Base):
368 """A non-callable version of `Mock`"""
369
370 def __new__(cls, *args, **kw):
371 # every instance has its own class
372 # so we can create magic methods on the
373 # class without stomping on other mocks
374 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
375 instance = object.__new__(new)
376 return instance
377
378
379 def __init__(
380 self, spec=None, wraps=None, name=None, spec_set=None,
381 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100382 _spec_as_instance=False, _eat_self=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700383 ):
384 if _new_parent is None:
385 _new_parent = parent
386
387 __dict__ = self.__dict__
388 __dict__['_mock_parent'] = parent
389 __dict__['_mock_name'] = name
390 __dict__['_mock_new_name'] = _new_name
391 __dict__['_mock_new_parent'] = _new_parent
392
393 if spec_set is not None:
394 spec = spec_set
395 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100396 if _eat_self is None:
397 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700398
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100399 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700400
401 __dict__['_mock_children'] = {}
402 __dict__['_mock_wraps'] = wraps
403 __dict__['_mock_delegate'] = None
404
405 __dict__['_mock_called'] = False
406 __dict__['_mock_call_args'] = None
407 __dict__['_mock_call_count'] = 0
408 __dict__['_mock_call_args_list'] = _CallList()
409 __dict__['_mock_mock_calls'] = _CallList()
410
411 __dict__['method_calls'] = _CallList()
412
413 if kwargs:
414 self.configure_mock(**kwargs)
415
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000416 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700417 spec, wraps, name, spec_set, parent,
418 _spec_state
419 )
420
421
422 def attach_mock(self, mock, attribute):
423 """
424 Attach a mock as an attribute of this one, replacing its name and
425 parent. Calls to the attached mock will be recorded in the
426 `method_calls` and `mock_calls` attributes of this one."""
427 mock._mock_parent = None
428 mock._mock_new_parent = None
429 mock._mock_name = ''
430 mock._mock_new_name = None
431
432 setattr(self, attribute, mock)
433
434
435 def mock_add_spec(self, spec, spec_set=False):
436 """Add a spec to a mock. `spec` can either be an object or a
437 list of strings. Only attributes on the `spec` can be fetched as
438 attributes from the mock.
439
440 If `spec_set` is True then only attributes on the spec can be set."""
441 self._mock_add_spec(spec, spec_set)
442
443
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100444 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
445 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700446 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100447 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700448
449 if spec is not None and not _is_list(spec):
450 if isinstance(spec, type):
451 _spec_class = spec
452 else:
453 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100454 res = _get_signature_object(spec,
455 _spec_as_instance, _eat_self)
456 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700457
458 spec = dir(spec)
459
460 __dict__ = self.__dict__
461 __dict__['_spec_class'] = _spec_class
462 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100463 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700464 __dict__['_mock_methods'] = spec
465
466
467 def __get_return_value(self):
468 ret = self._mock_return_value
469 if self._mock_delegate is not None:
470 ret = self._mock_delegate.return_value
471
472 if ret is DEFAULT:
473 ret = self._get_child_mock(
474 _new_parent=self, _new_name='()'
475 )
476 self.return_value = ret
477 return ret
478
479
480 def __set_return_value(self, value):
481 if self._mock_delegate is not None:
482 self._mock_delegate.return_value = value
483 else:
484 self._mock_return_value = value
485 _check_and_set_parent(self, value, None, '()')
486
487 __return_value_doc = "The value to be returned when the mock is called."
488 return_value = property(__get_return_value, __set_return_value,
489 __return_value_doc)
490
491
492 @property
493 def __class__(self):
494 if self._spec_class is None:
495 return type(self)
496 return self._spec_class
497
498 called = _delegating_property('called')
499 call_count = _delegating_property('call_count')
500 call_args = _delegating_property('call_args')
501 call_args_list = _delegating_property('call_args_list')
502 mock_calls = _delegating_property('mock_calls')
503
504
505 def __get_side_effect(self):
506 delegated = self._mock_delegate
507 if delegated is None:
508 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400509 sf = delegated.side_effect
510 if sf is not None and not callable(sf) and not isinstance(sf, _MockIter):
511 sf = _MockIter(sf)
512 delegated.side_effect = sf
513 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700514
515 def __set_side_effect(self, value):
516 value = _try_iter(value)
517 delegated = self._mock_delegate
518 if delegated is None:
519 self._mock_side_effect = value
520 else:
521 delegated.side_effect = value
522
523 side_effect = property(__get_side_effect, __set_side_effect)
524
525
526 def reset_mock(self):
527 "Restore the mock object to its initial state."
528 self.called = False
529 self.call_args = None
530 self.call_count = 0
531 self.mock_calls = _CallList()
532 self.call_args_list = _CallList()
533 self.method_calls = _CallList()
534
535 for child in self._mock_children.values():
Michael Foord75963642012-06-09 17:31:59 +0100536 if isinstance(child, _SpecState):
537 continue
Michael Foord345266a2012-03-14 12:24:34 -0700538 child.reset_mock()
539
540 ret = self._mock_return_value
541 if _is_instance_mock(ret) and ret is not self:
542 ret.reset_mock()
543
544
545 def configure_mock(self, **kwargs):
546 """Set attributes on the mock through keyword arguments.
547
548 Attributes plus return values and side effects can be set on child
549 mocks using standard dot notation and unpacking a dictionary in the
550 method call:
551
552 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
553 >>> mock.configure_mock(**attrs)"""
554 for arg, val in sorted(kwargs.items(),
555 # we sort on the number of dots so that
556 # attributes are set before we set attributes on
557 # attributes
558 key=lambda entry: entry[0].count('.')):
559 args = arg.split('.')
560 final = args.pop()
561 obj = self
562 for entry in args:
563 obj = getattr(obj, entry)
564 setattr(obj, final, val)
565
566
567 def __getattr__(self, name):
568 if name == '_mock_methods':
569 raise AttributeError(name)
570 elif self._mock_methods is not None:
571 if name not in self._mock_methods or name in _all_magics:
572 raise AttributeError("Mock object has no attribute %r" % name)
573 elif _is_magic(name):
574 raise AttributeError(name)
575
576 result = self._mock_children.get(name)
577 if result is _deleted:
578 raise AttributeError(name)
579 elif result is None:
580 wraps = None
581 if self._mock_wraps is not None:
582 # XXXX should we get the attribute without triggering code
583 # execution?
584 wraps = getattr(self._mock_wraps, name)
585
586 result = self._get_child_mock(
587 parent=self, name=name, wraps=wraps, _new_name=name,
588 _new_parent=self
589 )
590 self._mock_children[name] = result
591
592 elif isinstance(result, _SpecState):
593 result = create_autospec(
594 result.spec, result.spec_set, result.instance,
595 result.parent, result.name
596 )
597 self._mock_children[name] = result
598
599 return result
600
601
602 def __repr__(self):
603 _name_list = [self._mock_new_name]
604 _parent = self._mock_new_parent
605 last = self
606
607 dot = '.'
608 if _name_list == ['()']:
609 dot = ''
610 seen = set()
611 while _parent is not None:
612 last = _parent
613
614 _name_list.append(_parent._mock_new_name + dot)
615 dot = '.'
616 if _parent._mock_new_name == '()':
617 dot = ''
618
619 _parent = _parent._mock_new_parent
620
621 # use ids here so as not to call __hash__ on the mocks
622 if id(_parent) in seen:
623 break
624 seen.add(id(_parent))
625
626 _name_list = list(reversed(_name_list))
627 _first = last._mock_name or 'mock'
628 if len(_name_list) > 1:
629 if _name_list[1] not in ('()', '().'):
630 _first += '.'
631 _name_list[0] = _first
632 name = ''.join(_name_list)
633
634 name_string = ''
635 if name not in ('mock', 'mock.'):
636 name_string = ' name=%r' % name
637
638 spec_string = ''
639 if self._spec_class is not None:
640 spec_string = ' spec=%r'
641 if self._spec_set:
642 spec_string = ' spec_set=%r'
643 spec_string = spec_string % self._spec_class.__name__
644 return "<%s%s%s id='%s'>" % (
645 type(self).__name__,
646 name_string,
647 spec_string,
648 id(self)
649 )
650
651
652 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700653 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100654 if not FILTER_DIR:
655 return object.__dir__(self)
656
Michael Foord345266a2012-03-14 12:24:34 -0700657 extras = self._mock_methods or []
658 from_type = dir(type(self))
659 from_dict = list(self.__dict__)
660
Michael Foord313f85f2012-03-25 18:16:07 +0100661 from_type = [e for e in from_type if not e.startswith('_')]
662 from_dict = [e for e in from_dict if not e.startswith('_') or
663 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700664 return sorted(set(extras + from_type + from_dict +
665 list(self._mock_children)))
666
667
668 def __setattr__(self, name, value):
669 if name in _allowed_names:
670 # property setters go through here
671 return object.__setattr__(self, name, value)
672 elif (self._spec_set and self._mock_methods is not None and
673 name not in self._mock_methods and
674 name not in self.__dict__):
675 raise AttributeError("Mock object has no attribute '%s'" % name)
676 elif name in _unsupported_magics:
677 msg = 'Attempting to set unsupported magic method %r.' % name
678 raise AttributeError(msg)
679 elif name in _all_magics:
680 if self._mock_methods is not None and name not in self._mock_methods:
681 raise AttributeError("Mock object has no attribute '%s'" % name)
682
683 if not _is_instance_mock(value):
684 setattr(type(self), name, _get_method(name, value))
685 original = value
686 value = lambda *args, **kw: original(self, *args, **kw)
687 else:
688 # only set _new_name and not name so that mock_calls is tracked
689 # but not method calls
690 _check_and_set_parent(self, value, None, name)
691 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100692 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700693 elif name == '__class__':
694 self._spec_class = value
695 return
696 else:
697 if _check_and_set_parent(self, value, name, name):
698 self._mock_children[name] = value
699 return object.__setattr__(self, name, value)
700
701
702 def __delattr__(self, name):
703 if name in _all_magics and name in type(self).__dict__:
704 delattr(type(self), name)
705 if name not in self.__dict__:
706 # for magic methods that are still MagicProxy objects and
707 # not set on the instance itself
708 return
709
710 if name in self.__dict__:
711 object.__delattr__(self, name)
712
713 obj = self._mock_children.get(name, _missing)
714 if obj is _deleted:
715 raise AttributeError(name)
716 if obj is not _missing:
717 del self._mock_children[name]
718 self._mock_children[name] = _deleted
719
720
Michael Foord345266a2012-03-14 12:24:34 -0700721 def _format_mock_call_signature(self, args, kwargs):
722 name = self._mock_name or 'mock'
723 return _format_call_signature(name, args, kwargs)
724
725
726 def _format_mock_failure_message(self, args, kwargs):
727 message = 'Expected call: %s\nActual call: %s'
728 expected_string = self._format_mock_call_signature(args, kwargs)
729 call_args = self.call_args
730 if len(call_args) == 3:
731 call_args = call_args[1:]
732 actual_string = self._format_mock_call_signature(*call_args)
733 return message % (expected_string, actual_string)
734
735
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100736 def _call_matcher(self, _call):
737 """
738 Given a call (or simply a (args, kwargs) tuple), return a
739 comparison key suitable for matching with other calls.
740 This is a best effort method which relies on the spec's signature,
741 if available, or falls back on the arguments themselves.
742 """
743 sig = self._spec_signature
744 if sig is not None:
745 if len(_call) == 2:
746 name = ''
747 args, kwargs = _call
748 else:
749 name, args, kwargs = _call
750 try:
751 return name, sig.bind(*args, **kwargs)
752 except TypeError as e:
753 return e.with_traceback(None)
754 else:
755 return _call
756
757
Michael Foord345266a2012-03-14 12:24:34 -0700758 def assert_called_with(_mock_self, *args, **kwargs):
759 """assert that the mock was called with the specified arguments.
760
761 Raises an AssertionError if the args and keyword args passed in are
762 different to the last call to the mock."""
763 self = _mock_self
764 if self.call_args is None:
765 expected = self._format_mock_call_signature(args, kwargs)
766 raise AssertionError('Expected call: %s\nNot called' % (expected,))
767
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100768 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700769 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100770 return msg
771 expected = self._call_matcher((args, kwargs))
772 actual = self._call_matcher(self.call_args)
773 if expected != actual:
774 cause = expected if isinstance(expected, Exception) else None
775 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700776
777
778 def assert_called_once_with(_mock_self, *args, **kwargs):
779 """assert that the mock was called exactly once and with the specified
780 arguments."""
781 self = _mock_self
782 if not self.call_count == 1:
Michael Foord28d591c2012-09-28 16:15:22 +0100783 msg = ("Expected '%s' to be called once. Called %s times." %
784 (self._mock_name or 'mock', self.call_count))
Michael Foord345266a2012-03-14 12:24:34 -0700785 raise AssertionError(msg)
786 return self.assert_called_with(*args, **kwargs)
787
788
789 def assert_has_calls(self, calls, any_order=False):
790 """assert the mock has been called with the specified calls.
791 The `mock_calls` list is checked for the calls.
792
793 If `any_order` is False (the default) then the calls must be
794 sequential. There can be extra calls before or after the
795 specified calls.
796
797 If `any_order` is True then the calls can be in any order, but
798 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100799 expected = [self._call_matcher(c) for c in calls]
800 cause = expected if isinstance(expected, Exception) else None
801 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700802 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100803 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700804 raise AssertionError(
805 'Calls not found.\nExpected: %r\n'
806 'Actual: %r' % (calls, self.mock_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100807 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700808 return
809
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100810 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700811
812 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100813 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700814 try:
815 all_calls.remove(kall)
816 except ValueError:
817 not_found.append(kall)
818 if not_found:
819 raise AssertionError(
820 '%r not all found in call list' % (tuple(not_found),)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100821 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700822
823
824 def assert_any_call(self, *args, **kwargs):
825 """assert the mock has been called with the specified arguments.
826
827 The assert passes if the mock has *ever* been called, unlike
828 `assert_called_with` and `assert_called_once_with` that only pass if
829 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100830 expected = self._call_matcher((args, kwargs))
831 actual = [self._call_matcher(c) for c in self.call_args_list]
832 if expected not in actual:
833 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700834 expected_string = self._format_mock_call_signature(args, kwargs)
835 raise AssertionError(
836 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100837 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700838
839
840 def _get_child_mock(self, **kw):
841 """Create the child mocks for attributes and return value.
842 By default child mocks will be the same type as the parent.
843 Subclasses of Mock may want to override this to customize the way
844 child mocks are made.
845
846 For non-callable mocks the callable variant will be used (rather than
847 any custom subclass)."""
848 _type = type(self)
849 if not issubclass(_type, CallableMixin):
850 if issubclass(_type, NonCallableMagicMock):
851 klass = MagicMock
852 elif issubclass(_type, NonCallableMock) :
853 klass = Mock
854 else:
855 klass = _type.__mro__[1]
856 return klass(**kw)
857
858
859
860def _try_iter(obj):
861 if obj is None:
862 return obj
863 if _is_exception(obj):
864 return obj
865 if _callable(obj):
866 return obj
867 try:
868 return iter(obj)
869 except TypeError:
870 # XXXX backwards compatibility
871 # but this will blow up on first call - so maybe we should fail early?
872 return obj
873
874
875
876class CallableMixin(Base):
877
878 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
879 wraps=None, name=None, spec_set=None, parent=None,
880 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
881 self.__dict__['_mock_return_value'] = return_value
882
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000883 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700884 spec, wraps, name, spec_set, parent,
885 _spec_state, _new_name, _new_parent, **kwargs
886 )
887
888 self.side_effect = side_effect
889
890
891 def _mock_check_sig(self, *args, **kwargs):
892 # stub method that can be replaced with one with a specific signature
893 pass
894
895
896 def __call__(_mock_self, *args, **kwargs):
897 # can't use self in-case a function / method we are mocking uses self
898 # in the signature
899 _mock_self._mock_check_sig(*args, **kwargs)
900 return _mock_self._mock_call(*args, **kwargs)
901
902
903 def _mock_call(_mock_self, *args, **kwargs):
904 self = _mock_self
905 self.called = True
906 self.call_count += 1
Michael Foord345266a2012-03-14 12:24:34 -0700907 _new_name = self._mock_new_name
908 _new_parent = self._mock_new_parent
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100909
910 _call = _Call((args, kwargs), two=True)
911 self.call_args = _call
912 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700913 self.mock_calls.append(_Call(('', args, kwargs)))
914
915 seen = set()
916 skip_next_dot = _new_name == '()'
917 do_method_calls = self._mock_parent is not None
918 name = self._mock_name
919 while _new_parent is not None:
920 this_mock_call = _Call((_new_name, args, kwargs))
921 if _new_parent._mock_new_name:
922 dot = '.'
923 if skip_next_dot:
924 dot = ''
925
926 skip_next_dot = False
927 if _new_parent._mock_new_name == '()':
928 skip_next_dot = True
929
930 _new_name = _new_parent._mock_new_name + dot + _new_name
931
932 if do_method_calls:
933 if _new_name == name:
934 this_method_call = this_mock_call
935 else:
936 this_method_call = _Call((name, args, kwargs))
937 _new_parent.method_calls.append(this_method_call)
938
939 do_method_calls = _new_parent._mock_parent is not None
940 if do_method_calls:
941 name = _new_parent._mock_name + '.' + name
942
943 _new_parent.mock_calls.append(this_mock_call)
944 _new_parent = _new_parent._mock_new_parent
945
946 # use ids here so as not to call __hash__ on the mocks
947 _new_parent_id = id(_new_parent)
948 if _new_parent_id in seen:
949 break
950 seen.add(_new_parent_id)
951
952 ret_val = DEFAULT
953 effect = self.side_effect
954 if effect is not None:
955 if _is_exception(effect):
956 raise effect
957
958 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +0100959 result = next(effect)
960 if _is_exception(result):
961 raise result
Andrew Svetlov8b2cd752013-04-07 16:42:24 +0300962 if result is DEFAULT:
963 result = self.return_value
Michael Foord2cd48732012-04-21 15:52:11 +0100964 return result
Michael Foord345266a2012-03-14 12:24:34 -0700965
966 ret_val = effect(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700967
968 if (self._mock_wraps is not None and
969 self._mock_return_value is DEFAULT):
970 return self._mock_wraps(*args, **kwargs)
971 if ret_val is DEFAULT:
972 ret_val = self.return_value
973 return ret_val
974
975
976
977class Mock(CallableMixin, NonCallableMock):
978 """
979 Create a new `Mock` object. `Mock` takes several optional arguments
980 that specify the behaviour of the Mock object:
981
982 * `spec`: This can be either a list of strings or an existing object (a
983 class or instance) that acts as the specification for the mock object. If
984 you pass in an object then a list of strings is formed by calling dir on
985 the object (excluding unsupported magic attributes and methods). Accessing
986 any attribute not in this list will raise an `AttributeError`.
987
988 If `spec` is an object (rather than a list of strings) then
989 `mock.__class__` returns the class of the spec object. This allows mocks
990 to pass `isinstance` tests.
991
992 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
993 or get an attribute on the mock that isn't on the object passed as
994 `spec_set` will raise an `AttributeError`.
995
996 * `side_effect`: A function to be called whenever the Mock is called. See
997 the `side_effect` attribute. Useful for raising exceptions or
998 dynamically changing return values. The function is called with the same
999 arguments as the mock, and unless it returns `DEFAULT`, the return
1000 value of this function is used as the return value.
1001
Michael Foord2cd48732012-04-21 15:52:11 +01001002 If `side_effect` is an iterable then each call to the mock will return
1003 the next value from the iterable. If any of the members of the iterable
1004 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001005
Michael Foord345266a2012-03-14 12:24:34 -07001006 * `return_value`: The value returned when the mock is called. By default
1007 this is a new Mock (created on first access). See the
1008 `return_value` attribute.
1009
Michael Foord0682a0c2012-04-13 20:51:20 +01001010 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1011 calling the Mock will pass the call through to the wrapped object
1012 (returning the real result). Attribute access on the mock will return a
1013 Mock object that wraps the corresponding attribute of the wrapped object
1014 (so attempting to access an attribute that doesn't exist will raise an
1015 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001016
1017 If the mock has an explicit `return_value` set then calls are not passed
1018 to the wrapped object and the `return_value` is returned instead.
1019
1020 * `name`: If the mock has a name then it will be used in the repr of the
1021 mock. This can be useful for debugging. The name is propagated to child
1022 mocks.
1023
1024 Mocks can also be called with arbitrary keyword arguments. These will be
1025 used to set attributes on the mock after it is created.
1026 """
1027
1028
1029
1030def _dot_lookup(thing, comp, import_path):
1031 try:
1032 return getattr(thing, comp)
1033 except AttributeError:
1034 __import__(import_path)
1035 return getattr(thing, comp)
1036
1037
1038def _importer(target):
1039 components = target.split('.')
1040 import_path = components.pop(0)
1041 thing = __import__(import_path)
1042
1043 for comp in components:
1044 import_path += ".%s" % comp
1045 thing = _dot_lookup(thing, comp, import_path)
1046 return thing
1047
1048
1049def _is_started(patcher):
1050 # XXXX horrible
1051 return hasattr(patcher, 'is_local')
1052
1053
1054class _patch(object):
1055
1056 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001057 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001058
1059 def __init__(
1060 self, getter, attribute, new, spec, create,
1061 spec_set, autospec, new_callable, kwargs
1062 ):
1063 if new_callable is not None:
1064 if new is not DEFAULT:
1065 raise ValueError(
1066 "Cannot use 'new' and 'new_callable' together"
1067 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001068 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001069 raise ValueError(
1070 "Cannot use 'autospec' and 'new_callable' together"
1071 )
1072
1073 self.getter = getter
1074 self.attribute = attribute
1075 self.new = new
1076 self.new_callable = new_callable
1077 self.spec = spec
1078 self.create = create
1079 self.has_local = False
1080 self.spec_set = spec_set
1081 self.autospec = autospec
1082 self.kwargs = kwargs
1083 self.additional_patchers = []
1084
1085
1086 def copy(self):
1087 patcher = _patch(
1088 self.getter, self.attribute, self.new, self.spec,
1089 self.create, self.spec_set,
1090 self.autospec, self.new_callable, self.kwargs
1091 )
1092 patcher.attribute_name = self.attribute_name
1093 patcher.additional_patchers = [
1094 p.copy() for p in self.additional_patchers
1095 ]
1096 return patcher
1097
1098
1099 def __call__(self, func):
1100 if isinstance(func, type):
1101 return self.decorate_class(func)
1102 return self.decorate_callable(func)
1103
1104
1105 def decorate_class(self, klass):
1106 for attr in dir(klass):
1107 if not attr.startswith(patch.TEST_PREFIX):
1108 continue
1109
1110 attr_value = getattr(klass, attr)
1111 if not hasattr(attr_value, "__call__"):
1112 continue
1113
1114 patcher = self.copy()
1115 setattr(klass, attr, patcher(attr_value))
1116 return klass
1117
1118
1119 def decorate_callable(self, func):
1120 if hasattr(func, 'patchings'):
1121 func.patchings.append(self)
1122 return func
1123
1124 @wraps(func)
1125 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001126 extra_args = []
1127 entered_patchers = []
1128
Michael Foord50a8c0e2012-03-25 18:57:58 +01001129 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001130 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001131 for patching in patched.patchings:
1132 arg = patching.__enter__()
1133 entered_patchers.append(patching)
1134 if patching.attribute_name is not None:
1135 keywargs.update(arg)
1136 elif patching.new is DEFAULT:
1137 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001138
Michael Foordd7c65e22012-03-14 14:56:54 -07001139 args += tuple(extra_args)
1140 return func(*args, **keywargs)
1141 except:
1142 if (patching not in entered_patchers and
1143 _is_started(patching)):
1144 # the patcher may have been started, but an exception
1145 # raised whilst entering one of its additional_patchers
1146 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001147 # Pass the exception to __exit__
1148 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001149 # re-raise the exception
1150 raise
Michael Foord345266a2012-03-14 12:24:34 -07001151 finally:
1152 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001153 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001154
1155 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001156 return patched
1157
1158
1159 def get_original(self):
1160 target = self.getter()
1161 name = self.attribute
1162
1163 original = DEFAULT
1164 local = False
1165
1166 try:
1167 original = target.__dict__[name]
1168 except (AttributeError, KeyError):
1169 original = getattr(target, name, DEFAULT)
1170 else:
1171 local = True
1172
Michael Foordfddcfa22014-04-14 16:25:20 -04001173 if name in _builtins and isinstance(target, ModuleType):
1174 self.create = True
1175
Michael Foord345266a2012-03-14 12:24:34 -07001176 if not self.create and original is DEFAULT:
1177 raise AttributeError(
1178 "%s does not have the attribute %r" % (target, name)
1179 )
1180 return original, local
1181
1182
1183 def __enter__(self):
1184 """Perform the patch."""
1185 new, spec, spec_set = self.new, self.spec, self.spec_set
1186 autospec, kwargs = self.autospec, self.kwargs
1187 new_callable = self.new_callable
1188 self.target = self.getter()
1189
Michael Foord50a8c0e2012-03-25 18:57:58 +01001190 # normalise False to None
1191 if spec is False:
1192 spec = None
1193 if spec_set is False:
1194 spec_set = None
1195 if autospec is False:
1196 autospec = None
1197
1198 if spec is not None and autospec is not None:
1199 raise TypeError("Can't specify spec and autospec")
1200 if ((spec is not None or autospec is not None) and
1201 spec_set not in (True, None)):
1202 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1203
Michael Foord345266a2012-03-14 12:24:34 -07001204 original, local = self.get_original()
1205
Michael Foord50a8c0e2012-03-25 18:57:58 +01001206 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001207 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001208 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001209 # set spec to the object we are replacing
1210 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001211 if spec_set is True:
1212 spec_set = original
1213 spec = None
1214 elif spec is not None:
1215 if spec_set is True:
1216 spec_set = spec
1217 spec = None
1218 elif spec_set is True:
1219 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001220
Michael Foord50a8c0e2012-03-25 18:57:58 +01001221 if spec is not None or spec_set is not None:
1222 if original is DEFAULT:
1223 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001224 if isinstance(original, type):
1225 # If we're patching out a class and there is a spec
1226 inherit = True
1227
1228 Klass = MagicMock
1229 _kwargs = {}
1230 if new_callable is not None:
1231 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001232 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001233 this_spec = spec
1234 if spec_set is not None:
1235 this_spec = spec_set
1236 if _is_list(this_spec):
1237 not_callable = '__call__' not in this_spec
1238 else:
1239 not_callable = not callable(this_spec)
1240 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001241 Klass = NonCallableMagicMock
1242
1243 if spec is not None:
1244 _kwargs['spec'] = spec
1245 if spec_set is not None:
1246 _kwargs['spec_set'] = spec_set
1247
1248 # add a name to mocks
1249 if (isinstance(Klass, type) and
1250 issubclass(Klass, NonCallableMock) and self.attribute):
1251 _kwargs['name'] = self.attribute
1252
1253 _kwargs.update(kwargs)
1254 new = Klass(**_kwargs)
1255
1256 if inherit and _is_instance_mock(new):
1257 # we can only tell if the instance should be callable if the
1258 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001259 this_spec = spec
1260 if spec_set is not None:
1261 this_spec = spec_set
1262 if (not _is_list(this_spec) and not
1263 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001264 Klass = NonCallableMagicMock
1265
1266 _kwargs.pop('name')
1267 new.return_value = Klass(_new_parent=new, _new_name='()',
1268 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001269 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001270 # spec is ignored, new *must* be default, spec_set is treated
1271 # as a boolean. Should we check spec is not None and that spec_set
1272 # is a bool?
1273 if new is not DEFAULT:
1274 raise TypeError(
1275 "autospec creates the mock for you. Can't specify "
1276 "autospec and new."
1277 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001278 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001279 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001280 spec_set = bool(spec_set)
1281 if autospec is True:
1282 autospec = original
1283
1284 new = create_autospec(autospec, spec_set=spec_set,
1285 _name=self.attribute, **kwargs)
1286 elif kwargs:
1287 # can't set keyword args when we aren't creating the mock
1288 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1289 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1290
1291 new_attr = new
1292
1293 self.temp_original = original
1294 self.is_local = local
1295 setattr(self.target, self.attribute, new_attr)
1296 if self.attribute_name is not None:
1297 extra_args = {}
1298 if self.new is DEFAULT:
1299 extra_args[self.attribute_name] = new
1300 for patching in self.additional_patchers:
1301 arg = patching.__enter__()
1302 if patching.new is DEFAULT:
1303 extra_args.update(arg)
1304 return extra_args
1305
1306 return new
1307
1308
Michael Foord50a8c0e2012-03-25 18:57:58 +01001309 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001310 """Undo the patch."""
1311 if not _is_started(self):
1312 raise RuntimeError('stop called on unstarted patcher')
1313
1314 if self.is_local and self.temp_original is not DEFAULT:
1315 setattr(self.target, self.attribute, self.temp_original)
1316 else:
1317 delattr(self.target, self.attribute)
1318 if not self.create and not hasattr(self.target, self.attribute):
1319 # needed for proxy objects like django settings
1320 setattr(self.target, self.attribute, self.temp_original)
1321
1322 del self.temp_original
1323 del self.is_local
1324 del self.target
1325 for patcher in reversed(self.additional_patchers):
1326 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001327 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001328
Michael Foordf7c41582012-06-10 20:36:32 +01001329
1330 def start(self):
1331 """Activate a patch, returning any created mock."""
1332 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001333 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001334 return result
1335
1336
1337 def stop(self):
1338 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001339 try:
1340 self._active_patches.remove(self)
1341 except ValueError:
1342 # If the patch hasn't been started this will fail
1343 pass
1344
Michael Foordf7c41582012-06-10 20:36:32 +01001345 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001346
1347
1348
1349def _get_target(target):
1350 try:
1351 target, attribute = target.rsplit('.', 1)
1352 except (TypeError, ValueError):
1353 raise TypeError("Need a valid target to patch. You supplied: %r" %
1354 (target,))
1355 getter = lambda: _importer(target)
1356 return getter, attribute
1357
1358
1359def _patch_object(
1360 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001361 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001362 new_callable=None, **kwargs
1363 ):
1364 """
Michael Foord345266a2012-03-14 12:24:34 -07001365 patch the named member (`attribute`) on an object (`target`) with a mock
1366 object.
1367
1368 `patch.object` can be used as a decorator, class decorator or a context
1369 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1370 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1371 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1372 the mock object it creates.
1373
1374 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1375 for choosing which methods to wrap.
1376 """
1377 getter = lambda: target
1378 return _patch(
1379 getter, attribute, new, spec, create,
1380 spec_set, autospec, new_callable, kwargs
1381 )
1382
1383
Michael Foord50a8c0e2012-03-25 18:57:58 +01001384def _patch_multiple(target, spec=None, create=False, spec_set=None,
1385 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001386 """Perform multiple patches in a single call. It takes the object to be
1387 patched (either as an object or a string to fetch the object by importing)
1388 and keyword arguments for the patches::
1389
1390 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1391 ...
1392
1393 Use `DEFAULT` as the value if you want `patch.multiple` to create
1394 mocks for you. In this case the created mocks are passed into a decorated
1395 function by keyword, and a dictionary is returned when `patch.multiple` is
1396 used as a context manager.
1397
1398 `patch.multiple` can be used as a decorator, class decorator or a context
1399 manager. The arguments `spec`, `spec_set`, `create`,
1400 `autospec` and `new_callable` have the same meaning as for `patch`. These
1401 arguments will be applied to *all* patches done by `patch.multiple`.
1402
1403 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1404 for choosing which methods to wrap.
1405 """
1406 if type(target) is str:
1407 getter = lambda: _importer(target)
1408 else:
1409 getter = lambda: target
1410
1411 if not kwargs:
1412 raise ValueError(
1413 'Must supply at least one keyword argument with patch.multiple'
1414 )
1415 # need to wrap in a list for python 3, where items is a view
1416 items = list(kwargs.items())
1417 attribute, new = items[0]
1418 patcher = _patch(
1419 getter, attribute, new, spec, create, spec_set,
1420 autospec, new_callable, {}
1421 )
1422 patcher.attribute_name = attribute
1423 for attribute, new in items[1:]:
1424 this_patcher = _patch(
1425 getter, attribute, new, spec, create, spec_set,
1426 autospec, new_callable, {}
1427 )
1428 this_patcher.attribute_name = attribute
1429 patcher.additional_patchers.append(this_patcher)
1430 return patcher
1431
1432
1433def patch(
1434 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001435 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001436 ):
1437 """
1438 `patch` acts as a function decorator, class decorator or a context
1439 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001440 is patched with a `new` object. When the function/with statement exits
1441 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001442
Michael Foord54b3db82012-03-28 15:08:08 +01001443 If `new` is omitted, then the target is replaced with a
1444 `MagicMock`. If `patch` is used as a decorator and `new` is
1445 omitted, the created mock is passed in as an extra argument to the
1446 decorated function. If `patch` is used as a context manager the created
1447 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001448
Michael Foord54b3db82012-03-28 15:08:08 +01001449 `target` should be a string in the form `'package.module.ClassName'`. The
1450 `target` is imported and the specified object replaced with the `new`
1451 object, so the `target` must be importable from the environment you are
1452 calling `patch` from. The target is imported when the decorated function
1453 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001454
1455 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1456 if patch is creating one for you.
1457
1458 In addition you can pass `spec=True` or `spec_set=True`, which causes
1459 patch to pass in the object being mocked as the spec/spec_set object.
1460
1461 `new_callable` allows you to specify a different class, or callable object,
1462 that will be called to create the `new` object. By default `MagicMock` is
1463 used.
1464
1465 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1466 then the mock with be created with a spec from the object being replaced.
1467 All attributes of the mock will also have the spec of the corresponding
1468 attribute of the object being replaced. Methods and functions being
1469 mocked will have their arguments checked and will raise a `TypeError` if
1470 they are called with the wrong signature. For mocks replacing a class,
1471 their return value (the 'instance') will have the same spec as the class.
1472
1473 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1474 arbitrary object as the spec instead of the one being replaced.
1475
1476 By default `patch` will fail to replace attributes that don't exist. If
1477 you pass in `create=True`, and the attribute doesn't exist, patch will
1478 create the attribute for you when the patched function is called, and
1479 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001480 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001481 default because it can be dangerous. With it switched on you can write
1482 passing tests against APIs that don't actually exist!
1483
1484 Patch can be used as a `TestCase` class decorator. It works by
1485 decorating each test method in the class. This reduces the boilerplate
1486 code when your test methods share a common patchings set. `patch` finds
1487 tests by looking for method names that start with `patch.TEST_PREFIX`.
1488 By default this is `test`, which matches the way `unittest` finds tests.
1489 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1490
1491 Patch can be used as a context manager, with the with statement. Here the
1492 patching applies to the indented block after the with statement. If you
1493 use "as" then the patched object will be bound to the name after the
1494 "as"; very useful if `patch` is creating a mock object for you.
1495
1496 `patch` takes arbitrary keyword arguments. These will be passed to
1497 the `Mock` (or `new_callable`) on construction.
1498
1499 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1500 available for alternate use-cases.
1501 """
1502 getter, attribute = _get_target(target)
1503 return _patch(
1504 getter, attribute, new, spec, create,
1505 spec_set, autospec, new_callable, kwargs
1506 )
1507
1508
1509class _patch_dict(object):
1510 """
1511 Patch a dictionary, or dictionary like object, and restore the dictionary
1512 to its original state after the test.
1513
1514 `in_dict` can be a dictionary or a mapping like container. If it is a
1515 mapping then it must at least support getting, setting and deleting items
1516 plus iterating over keys.
1517
1518 `in_dict` can also be a string specifying the name of the dictionary, which
1519 will then be fetched by importing it.
1520
1521 `values` can be a dictionary of values to set in the dictionary. `values`
1522 can also be an iterable of `(key, value)` pairs.
1523
1524 If `clear` is True then the dictionary will be cleared before the new
1525 values are set.
1526
1527 `patch.dict` can also be called with arbitrary keyword arguments to set
1528 values in the dictionary::
1529
1530 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1531 ...
1532
1533 `patch.dict` can be used as a context manager, decorator or class
1534 decorator. When used as a class decorator `patch.dict` honours
1535 `patch.TEST_PREFIX` for choosing which methods to wrap.
1536 """
1537
1538 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1539 if isinstance(in_dict, str):
1540 in_dict = _importer(in_dict)
1541 self.in_dict = in_dict
1542 # support any argument supported by dict(...) constructor
1543 self.values = dict(values)
1544 self.values.update(kwargs)
1545 self.clear = clear
1546 self._original = None
1547
1548
1549 def __call__(self, f):
1550 if isinstance(f, type):
1551 return self.decorate_class(f)
1552 @wraps(f)
1553 def _inner(*args, **kw):
1554 self._patch_dict()
1555 try:
1556 return f(*args, **kw)
1557 finally:
1558 self._unpatch_dict()
1559
1560 return _inner
1561
1562
1563 def decorate_class(self, klass):
1564 for attr in dir(klass):
1565 attr_value = getattr(klass, attr)
1566 if (attr.startswith(patch.TEST_PREFIX) and
1567 hasattr(attr_value, "__call__")):
1568 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1569 decorated = decorator(attr_value)
1570 setattr(klass, attr, decorated)
1571 return klass
1572
1573
1574 def __enter__(self):
1575 """Patch the dict."""
1576 self._patch_dict()
1577
1578
1579 def _patch_dict(self):
1580 values = self.values
1581 in_dict = self.in_dict
1582 clear = self.clear
1583
1584 try:
1585 original = in_dict.copy()
1586 except AttributeError:
1587 # dict like object with no copy method
1588 # must support iteration over keys
1589 original = {}
1590 for key in in_dict:
1591 original[key] = in_dict[key]
1592 self._original = original
1593
1594 if clear:
1595 _clear_dict(in_dict)
1596
1597 try:
1598 in_dict.update(values)
1599 except AttributeError:
1600 # dict like object with no update method
1601 for key in values:
1602 in_dict[key] = values[key]
1603
1604
1605 def _unpatch_dict(self):
1606 in_dict = self.in_dict
1607 original = self._original
1608
1609 _clear_dict(in_dict)
1610
1611 try:
1612 in_dict.update(original)
1613 except AttributeError:
1614 for key in original:
1615 in_dict[key] = original[key]
1616
1617
1618 def __exit__(self, *args):
1619 """Unpatch the dict."""
1620 self._unpatch_dict()
1621 return False
1622
1623 start = __enter__
1624 stop = __exit__
1625
1626
1627def _clear_dict(in_dict):
1628 try:
1629 in_dict.clear()
1630 except AttributeError:
1631 keys = list(in_dict)
1632 for key in keys:
1633 del in_dict[key]
1634
1635
Michael Foordf7c41582012-06-10 20:36:32 +01001636def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001637 """Stop all active patches. LIFO to unroll nested patches."""
1638 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001639 patch.stop()
1640
1641
Michael Foord345266a2012-03-14 12:24:34 -07001642patch.object = _patch_object
1643patch.dict = _patch_dict
1644patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001645patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001646patch.TEST_PREFIX = 'test'
1647
1648magic_methods = (
1649 "lt le gt ge eq ne "
1650 "getitem setitem delitem "
1651 "len contains iter "
1652 "hash str sizeof "
1653 "enter exit "
1654 "divmod neg pos abs invert "
1655 "complex int float index "
1656 "trunc floor ceil "
1657 "bool next "
1658)
1659
Michael Foordd2623d72014-04-14 11:23:48 -04001660numerics = (
1661 "add sub mul div floordiv mod lshift rshift and xor or pow truediv"
1662)
Michael Foord345266a2012-03-14 12:24:34 -07001663inplace = ' '.join('i%s' % n for n in numerics.split())
1664right = ' '.join('r%s' % n for n in numerics.split())
1665
1666# not including __prepare__, __instancecheck__, __subclasscheck__
1667# (as they are metaclass methods)
1668# __del__ is not supported at all as it causes problems if it exists
1669
1670_non_defaults = set('__%s__' % method for method in [
Michael Foord944e02d2012-03-25 23:12:55 +01001671 'get', 'set', 'delete', 'reversed', 'missing', 'reduce', 'reduce_ex',
1672 'getinitargs', 'getnewargs', 'getstate', 'setstate', 'getformat',
1673 'setformat', 'repr', 'dir', 'subclasses', 'format',
Michael Foord345266a2012-03-14 12:24:34 -07001674])
1675
1676
1677def _get_method(name, func):
1678 "Turns a callable object (like a mock) into a real function"
1679 def method(self, *args, **kw):
1680 return func(self, *args, **kw)
1681 method.__name__ = name
1682 return method
1683
1684
1685_magics = set(
1686 '__%s__' % method for method in
1687 ' '.join([magic_methods, numerics, inplace, right]).split()
1688)
1689
1690_all_magics = _magics | _non_defaults
1691
1692_unsupported_magics = set([
1693 '__getattr__', '__setattr__',
1694 '__init__', '__new__', '__prepare__'
1695 '__instancecheck__', '__subclasscheck__',
1696 '__del__'
1697])
1698
1699_calculate_return_value = {
1700 '__hash__': lambda self: object.__hash__(self),
1701 '__str__': lambda self: object.__str__(self),
1702 '__sizeof__': lambda self: object.__sizeof__(self),
1703}
1704
1705_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001706 '__lt__': NotImplemented,
1707 '__gt__': NotImplemented,
1708 '__le__': NotImplemented,
1709 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001710 '__int__': 1,
1711 '__contains__': False,
1712 '__len__': 0,
1713 '__exit__': False,
1714 '__complex__': 1j,
1715 '__float__': 1.0,
1716 '__bool__': True,
1717 '__index__': 1,
1718}
1719
1720
1721def _get_eq(self):
1722 def __eq__(other):
1723 ret_val = self.__eq__._mock_return_value
1724 if ret_val is not DEFAULT:
1725 return ret_val
1726 return self is other
1727 return __eq__
1728
1729def _get_ne(self):
1730 def __ne__(other):
1731 if self.__ne__._mock_return_value is not DEFAULT:
1732 return DEFAULT
1733 return self is not other
1734 return __ne__
1735
1736def _get_iter(self):
1737 def __iter__():
1738 ret_val = self.__iter__._mock_return_value
1739 if ret_val is DEFAULT:
1740 return iter([])
1741 # if ret_val was already an iterator, then calling iter on it should
1742 # return the iterator unchanged
1743 return iter(ret_val)
1744 return __iter__
1745
1746_side_effect_methods = {
1747 '__eq__': _get_eq,
1748 '__ne__': _get_ne,
1749 '__iter__': _get_iter,
1750}
1751
1752
1753
1754def _set_return_value(mock, method, name):
1755 fixed = _return_values.get(name, DEFAULT)
1756 if fixed is not DEFAULT:
1757 method.return_value = fixed
1758 return
1759
1760 return_calulator = _calculate_return_value.get(name)
1761 if return_calulator is not None:
1762 try:
1763 return_value = return_calulator(mock)
1764 except AttributeError:
1765 # XXXX why do we return AttributeError here?
1766 # set it as a side_effect instead?
1767 return_value = AttributeError(name)
1768 method.return_value = return_value
1769 return
1770
1771 side_effector = _side_effect_methods.get(name)
1772 if side_effector is not None:
1773 method.side_effect = side_effector(mock)
1774
1775
1776
1777class MagicMixin(object):
1778 def __init__(self, *args, **kw):
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001779 _safe_super(MagicMixin, self).__init__(*args, **kw)
Michael Foord345266a2012-03-14 12:24:34 -07001780 self._mock_set_magics()
1781
1782
1783 def _mock_set_magics(self):
1784 these_magics = _magics
1785
1786 if self._mock_methods is not None:
1787 these_magics = _magics.intersection(self._mock_methods)
1788
1789 remove_magics = set()
1790 remove_magics = _magics - these_magics
1791
1792 for entry in remove_magics:
1793 if entry in type(self).__dict__:
1794 # remove unneeded magic methods
1795 delattr(self, entry)
1796
1797 # don't overwrite existing attributes if called a second time
1798 these_magics = these_magics - set(type(self).__dict__)
1799
1800 _type = type(self)
1801 for entry in these_magics:
1802 setattr(_type, entry, MagicProxy(entry, self))
1803
1804
1805
1806class NonCallableMagicMock(MagicMixin, NonCallableMock):
1807 """A version of `MagicMock` that isn't callable."""
1808 def mock_add_spec(self, spec, spec_set=False):
1809 """Add a spec to a mock. `spec` can either be an object or a
1810 list of strings. Only attributes on the `spec` can be fetched as
1811 attributes from the mock.
1812
1813 If `spec_set` is True then only attributes on the spec can be set."""
1814 self._mock_add_spec(spec, spec_set)
1815 self._mock_set_magics()
1816
1817
1818
1819class MagicMock(MagicMixin, Mock):
1820 """
1821 MagicMock is a subclass of Mock with default implementations
1822 of most of the magic methods. You can use MagicMock without having to
1823 configure the magic methods yourself.
1824
1825 If you use the `spec` or `spec_set` arguments then *only* magic
1826 methods that exist in the spec will be created.
1827
1828 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1829 """
1830 def mock_add_spec(self, spec, spec_set=False):
1831 """Add a spec to a mock. `spec` can either be an object or a
1832 list of strings. Only attributes on the `spec` can be fetched as
1833 attributes from the mock.
1834
1835 If `spec_set` is True then only attributes on the spec can be set."""
1836 self._mock_add_spec(spec, spec_set)
1837 self._mock_set_magics()
1838
1839
1840
1841class MagicProxy(object):
1842 def __init__(self, name, parent):
1843 self.name = name
1844 self.parent = parent
1845
1846 def __call__(self, *args, **kwargs):
1847 m = self.create_mock()
1848 return m(*args, **kwargs)
1849
1850 def create_mock(self):
1851 entry = self.name
1852 parent = self.parent
1853 m = parent._get_child_mock(name=entry, _new_name=entry,
1854 _new_parent=parent)
1855 setattr(parent, entry, m)
1856 _set_return_value(parent, m, entry)
1857 return m
1858
1859 def __get__(self, obj, _type=None):
1860 return self.create_mock()
1861
1862
1863
1864class _ANY(object):
1865 "A helper object that compares equal to everything."
1866
1867 def __eq__(self, other):
1868 return True
1869
1870 def __ne__(self, other):
1871 return False
1872
1873 def __repr__(self):
1874 return '<ANY>'
1875
1876ANY = _ANY()
1877
1878
1879
1880def _format_call_signature(name, args, kwargs):
1881 message = '%s(%%s)' % name
1882 formatted_args = ''
1883 args_string = ', '.join([repr(arg) for arg in args])
1884 kwargs_string = ', '.join([
1885 '%s=%r' % (key, value) for key, value in kwargs.items()
1886 ])
1887 if args_string:
1888 formatted_args = args_string
1889 if kwargs_string:
1890 if formatted_args:
1891 formatted_args += ', '
1892 formatted_args += kwargs_string
1893
1894 return message % formatted_args
1895
1896
1897
1898class _Call(tuple):
1899 """
1900 A tuple for holding the results of a call to a mock, either in the form
1901 `(args, kwargs)` or `(name, args, kwargs)`.
1902
1903 If args or kwargs are empty then a call tuple will compare equal to
1904 a tuple without those values. This makes comparisons less verbose::
1905
1906 _Call(('name', (), {})) == ('name',)
1907 _Call(('name', (1,), {})) == ('name', (1,))
1908 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1909
1910 The `_Call` object provides a useful shortcut for comparing with call::
1911
1912 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1913 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1914
1915 If the _Call has no name then it will match any name.
1916 """
1917 def __new__(cls, value=(), name=None, parent=None, two=False,
1918 from_kall=True):
1919 name = ''
1920 args = ()
1921 kwargs = {}
1922 _len = len(value)
1923 if _len == 3:
1924 name, args, kwargs = value
1925 elif _len == 2:
1926 first, second = value
1927 if isinstance(first, str):
1928 name = first
1929 if isinstance(second, tuple):
1930 args = second
1931 else:
1932 kwargs = second
1933 else:
1934 args, kwargs = first, second
1935 elif _len == 1:
1936 value, = value
1937 if isinstance(value, str):
1938 name = value
1939 elif isinstance(value, tuple):
1940 args = value
1941 else:
1942 kwargs = value
1943
1944 if two:
1945 return tuple.__new__(cls, (args, kwargs))
1946
1947 return tuple.__new__(cls, (name, args, kwargs))
1948
1949
1950 def __init__(self, value=(), name=None, parent=None, two=False,
1951 from_kall=True):
1952 self.name = name
1953 self.parent = parent
1954 self.from_kall = from_kall
1955
1956
1957 def __eq__(self, other):
1958 if other is ANY:
1959 return True
1960 try:
1961 len_other = len(other)
1962 except TypeError:
1963 return False
1964
1965 self_name = ''
1966 if len(self) == 2:
1967 self_args, self_kwargs = self
1968 else:
1969 self_name, self_args, self_kwargs = self
1970
1971 other_name = ''
1972 if len_other == 0:
1973 other_args, other_kwargs = (), {}
1974 elif len_other == 3:
1975 other_name, other_args, other_kwargs = other
1976 elif len_other == 1:
1977 value, = other
1978 if isinstance(value, tuple):
1979 other_args = value
1980 other_kwargs = {}
1981 elif isinstance(value, str):
1982 other_name = value
1983 other_args, other_kwargs = (), {}
1984 else:
1985 other_args = ()
1986 other_kwargs = value
1987 else:
1988 # len 2
1989 # could be (name, args) or (name, kwargs) or (args, kwargs)
1990 first, second = other
1991 if isinstance(first, str):
1992 other_name = first
1993 if isinstance(second, tuple):
1994 other_args, other_kwargs = second, {}
1995 else:
1996 other_args, other_kwargs = (), second
1997 else:
1998 other_args, other_kwargs = first, second
1999
2000 if self_name and other_name != self_name:
2001 return False
2002
2003 # this order is important for ANY to work!
2004 return (other_args, other_kwargs) == (self_args, self_kwargs)
2005
2006
2007 def __ne__(self, other):
2008 return not self.__eq__(other)
2009
2010
2011 def __call__(self, *args, **kwargs):
2012 if self.name is None:
2013 return _Call(('', args, kwargs), name='()')
2014
2015 name = self.name + '()'
2016 return _Call((self.name, args, kwargs), name=name, parent=self)
2017
2018
2019 def __getattr__(self, attr):
2020 if self.name is None:
2021 return _Call(name=attr, from_kall=False)
2022 name = '%s.%s' % (self.name, attr)
2023 return _Call(name=name, parent=self, from_kall=False)
2024
2025
2026 def __repr__(self):
2027 if not self.from_kall:
2028 name = self.name or 'call'
2029 if name.startswith('()'):
2030 name = 'call%s' % name
2031 return name
2032
2033 if len(self) == 2:
2034 name = 'call'
2035 args, kwargs = self
2036 else:
2037 name, args, kwargs = self
2038 if not name:
2039 name = 'call'
2040 elif not name.startswith('()'):
2041 name = 'call.%s' % name
2042 else:
2043 name = 'call%s' % name
2044 return _format_call_signature(name, args, kwargs)
2045
2046
2047 def call_list(self):
2048 """For a call object that represents multiple calls, `call_list`
2049 returns a list of all the intermediate calls as well as the
2050 final call."""
2051 vals = []
2052 thing = self
2053 while thing is not None:
2054 if thing.from_kall:
2055 vals.append(thing)
2056 thing = thing.parent
2057 return _CallList(reversed(vals))
2058
2059
2060call = _Call(from_kall=False)
2061
2062
2063
2064def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2065 _name=None, **kwargs):
2066 """Create a mock object using another object as a spec. Attributes on the
2067 mock will use the corresponding attribute on the `spec` object as their
2068 spec.
2069
2070 Functions or methods being mocked will have their arguments checked
2071 to check that they are called with the correct signature.
2072
2073 If `spec_set` is True then attempting to set attributes that don't exist
2074 on the spec object will raise an `AttributeError`.
2075
2076 If a class is used as a spec then the return value of the mock (the
2077 instance of the class) will have the same spec. You can use a class as the
2078 spec for an instance object by passing `instance=True`. The returned mock
2079 will only be callable if instances of the mock are callable.
2080
2081 `create_autospec` also takes arbitrary keyword arguments that are passed to
2082 the constructor of the created mock."""
2083 if _is_list(spec):
2084 # can't pass a list instance to the mock constructor as it will be
2085 # interpreted as a list of strings
2086 spec = type(spec)
2087
2088 is_type = isinstance(spec, type)
2089
2090 _kwargs = {'spec': spec}
2091 if spec_set:
2092 _kwargs = {'spec_set': spec}
2093 elif spec is None:
2094 # None we mock with a normal mock without a spec
2095 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002096 if _kwargs and instance:
2097 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002098
2099 _kwargs.update(kwargs)
2100
2101 Klass = MagicMock
2102 if type(spec) in DescriptorTypes:
2103 # descriptors don't have a spec
2104 # because we don't know what type they return
2105 _kwargs = {}
2106 elif not _callable(spec):
2107 Klass = NonCallableMagicMock
2108 elif is_type and instance and not _instance_callable(spec):
2109 Klass = NonCallableMagicMock
2110
Kushal Das484f8a82014-04-16 01:05:50 +05302111 _name = _kwargs.pop('name', _name)
2112
Michael Foord345266a2012-03-14 12:24:34 -07002113 _new_name = _name
2114 if _parent is None:
2115 # for a top level object no _new_name should be set
2116 _new_name = ''
2117
2118 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2119 name=_name, **_kwargs)
2120
2121 if isinstance(spec, FunctionTypes):
2122 # should only happen at the top level because we don't
2123 # recurse for functions
2124 mock = _set_signature(mock, spec)
2125 else:
2126 _check_signature(spec, mock, is_type, instance)
2127
2128 if _parent is not None and not instance:
2129 _parent._mock_children[_name] = mock
2130
2131 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002132 mock.return_value = create_autospec(spec, spec_set, instance=True,
2133 _name='()', _parent=mock)
2134
2135 for entry in dir(spec):
2136 if _is_magic(entry):
2137 # MagicMock already does the useful magic methods for us
2138 continue
2139
Michael Foord345266a2012-03-14 12:24:34 -07002140 # XXXX do we need a better way of getting attributes without
2141 # triggering code execution (?) Probably not - we need the actual
2142 # object to mock it so we would rather trigger a property than mock
2143 # the property descriptor. Likewise we want to mock out dynamically
2144 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002145 # XXXX what about attributes that raise exceptions other than
2146 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002147 # we could be resilient against it, or catch and propagate the
2148 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002149 try:
2150 original = getattr(spec, entry)
2151 except AttributeError:
2152 continue
Michael Foord345266a2012-03-14 12:24:34 -07002153
2154 kwargs = {'spec': original}
2155 if spec_set:
2156 kwargs = {'spec_set': original}
2157
2158 if not isinstance(original, FunctionTypes):
2159 new = _SpecState(original, spec_set, mock, entry, instance)
2160 mock._mock_children[entry] = new
2161 else:
2162 parent = mock
2163 if isinstance(spec, FunctionTypes):
2164 parent = mock.mock
2165
Michael Foord345266a2012-03-14 12:24:34 -07002166 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002167 kwargs['_eat_self'] = skipfirst
2168 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2169 _new_parent=parent,
2170 **kwargs)
2171 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002172 _check_signature(original, new, skipfirst=skipfirst)
2173
2174 # so functions created with _set_signature become instance attributes,
2175 # *plus* their underlying mock exists in _mock_children of the parent
2176 # mock. Adding to _mock_children may be unnecessary where we are also
2177 # setting as an instance attribute?
2178 if isinstance(new, FunctionTypes):
2179 setattr(mock, entry, new)
2180
2181 return mock
2182
2183
2184def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002185 """
2186 Return whether we should skip the first argument on spec's `entry`
2187 attribute.
2188 """
Michael Foord345266a2012-03-14 12:24:34 -07002189 if not isinstance(spec, type):
2190 if entry in getattr(spec, '__dict__', {}):
2191 # instance attribute - shouldn't skip
2192 return False
Michael Foord345266a2012-03-14 12:24:34 -07002193 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002194
2195 for klass in spec.__mro__:
2196 result = klass.__dict__.get(entry, DEFAULT)
2197 if result is DEFAULT:
2198 continue
2199 if isinstance(result, (staticmethod, classmethod)):
2200 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002201 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2202 # Normal method => skip if looked up on type
2203 # (if looked up on instance, self is already skipped)
2204 return is_type
2205 else:
2206 return False
Michael Foord345266a2012-03-14 12:24:34 -07002207
2208 # shouldn't get here unless function is a dynamically provided attribute
2209 # XXXX untested behaviour
2210 return is_type
2211
2212
2213def _get_class(obj):
2214 try:
2215 return obj.__class__
2216 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002217 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002218 return type(obj)
2219
2220
2221class _SpecState(object):
2222
2223 def __init__(self, spec, spec_set=False, parent=None,
2224 name=None, ids=None, instance=False):
2225 self.spec = spec
2226 self.ids = ids
2227 self.spec_set = spec_set
2228 self.parent = parent
2229 self.instance = instance
2230 self.name = name
2231
2232
2233FunctionTypes = (
2234 # python function
2235 type(create_autospec),
2236 # instance method
2237 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002238)
2239
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002240MethodWrapperTypes = (
2241 type(ANY.__eq__.__get__),
2242)
2243
Michael Foord345266a2012-03-14 12:24:34 -07002244
Michael Foorda74561a2012-03-25 19:03:13 +01002245file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002246
Michael Foord04cbe0c2013-03-19 17:22:51 -07002247def _iterate_read_data(read_data):
2248 # Helper for mock_open:
2249 # Retrieve lines from read_data via a generator so that separate calls to
2250 # readline, read, and readlines are properly interleaved
2251 data_as_list = ['{}\n'.format(l) for l in read_data.split('\n')]
2252
2253 if data_as_list[-1] == '\n':
2254 # If the last line ended in a newline, the list comprehension will have an
2255 # extra entry that's just a newline. Remove this.
2256 data_as_list = data_as_list[:-1]
2257 else:
2258 # If there wasn't an extra newline by itself, then the file being
2259 # emulated doesn't have a newline to end the last line remove the
2260 # newline that our naive format() added
2261 data_as_list[-1] = data_as_list[-1][:-1]
2262
2263 for line in data_as_list:
2264 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002265
2266def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002267 """
2268 A helper function to create a mock to replace the use of `open`. It works
2269 for `open` called directly or used as a context manager.
2270
2271 The `mock` argument is the mock object to configure. If `None` (the
2272 default) then a `MagicMock` will be created for you, with the API limited
2273 to methods or attributes available on standard file handles.
2274
Michael Foord04cbe0c2013-03-19 17:22:51 -07002275 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2276 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002277 """
Michael Foord04cbe0c2013-03-19 17:22:51 -07002278 def _readlines_side_effect(*args, **kwargs):
2279 if handle.readlines.return_value is not None:
2280 return handle.readlines.return_value
2281 return list(_data)
2282
2283 def _read_side_effect(*args, **kwargs):
2284 if handle.read.return_value is not None:
2285 return handle.read.return_value
2286 return ''.join(_data)
2287
2288 def _readline_side_effect():
2289 if handle.readline.return_value is not None:
2290 while True:
2291 yield handle.readline.return_value
2292 for line in _data:
2293 yield line
2294
2295
Michael Foorda74561a2012-03-25 19:03:13 +01002296 global file_spec
2297 if file_spec is None:
2298 import _io
2299 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2300
Michael Foord345266a2012-03-14 12:24:34 -07002301 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002302 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002303
2304 handle = MagicMock(spec=file_spec)
Michael Foord345266a2012-03-14 12:24:34 -07002305 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002306
2307 _data = _iterate_read_data(read_data)
2308
2309 handle.write.return_value = None
2310 handle.read.return_value = None
2311 handle.readline.return_value = None
2312 handle.readlines.return_value = None
2313
2314 handle.read.side_effect = _read_side_effect
2315 handle.readline.side_effect = _readline_side_effect()
2316 handle.readlines.side_effect = _readlines_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002317
2318 mock.return_value = handle
2319 return mock
2320
2321
2322class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002323 """
2324 A mock intended to be used as a property, or other descriptor, on a class.
2325 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2326 a return value when it is fetched.
2327
2328 Fetching a `PropertyMock` instance from an object calls the mock, with
2329 no args. Setting it calls the mock with the value being set.
2330 """
Michael Foordc2870622012-04-13 16:57:22 +01002331 def _get_child_mock(self, **kwargs):
2332 return MagicMock(**kwargs)
2333
Michael Foord345266a2012-03-14 12:24:34 -07002334 def __get__(self, obj, obj_type):
2335 return self()
2336 def __set__(self, obj, val):
2337 self(val)