blob: d00197688ae0f04b1111bac6f8315942ae9b3931 [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,
Kushal Das8c145342014-04-16 23:32:21 +0530382 _spec_as_instance=False, _eat_self=None, unsafe=False, **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()
Kushal Das8c145342014-04-16 23:32:21 +0530412 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700413
414 if kwargs:
415 self.configure_mock(**kwargs)
416
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000417 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700418 spec, wraps, name, spec_set, parent,
419 _spec_state
420 )
421
422
423 def attach_mock(self, mock, attribute):
424 """
425 Attach a mock as an attribute of this one, replacing its name and
426 parent. Calls to the attached mock will be recorded in the
427 `method_calls` and `mock_calls` attributes of this one."""
428 mock._mock_parent = None
429 mock._mock_new_parent = None
430 mock._mock_name = ''
431 mock._mock_new_name = None
432
433 setattr(self, attribute, mock)
434
435
436 def mock_add_spec(self, spec, spec_set=False):
437 """Add a spec to a mock. `spec` can either be an object or a
438 list of strings. Only attributes on the `spec` can be fetched as
439 attributes from the mock.
440
441 If `spec_set` is True then only attributes on the spec can be set."""
442 self._mock_add_spec(spec, spec_set)
443
444
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100445 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
446 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700447 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100448 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700449
450 if spec is not None and not _is_list(spec):
451 if isinstance(spec, type):
452 _spec_class = spec
453 else:
454 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100455 res = _get_signature_object(spec,
456 _spec_as_instance, _eat_self)
457 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700458
459 spec = dir(spec)
460
461 __dict__ = self.__dict__
462 __dict__['_spec_class'] = _spec_class
463 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100464 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700465 __dict__['_mock_methods'] = spec
466
467
468 def __get_return_value(self):
469 ret = self._mock_return_value
470 if self._mock_delegate is not None:
471 ret = self._mock_delegate.return_value
472
473 if ret is DEFAULT:
474 ret = self._get_child_mock(
475 _new_parent=self, _new_name='()'
476 )
477 self.return_value = ret
478 return ret
479
480
481 def __set_return_value(self, value):
482 if self._mock_delegate is not None:
483 self._mock_delegate.return_value = value
484 else:
485 self._mock_return_value = value
486 _check_and_set_parent(self, value, None, '()')
487
488 __return_value_doc = "The value to be returned when the mock is called."
489 return_value = property(__get_return_value, __set_return_value,
490 __return_value_doc)
491
492
493 @property
494 def __class__(self):
495 if self._spec_class is None:
496 return type(self)
497 return self._spec_class
498
499 called = _delegating_property('called')
500 call_count = _delegating_property('call_count')
501 call_args = _delegating_property('call_args')
502 call_args_list = _delegating_property('call_args_list')
503 mock_calls = _delegating_property('mock_calls')
504
505
506 def __get_side_effect(self):
507 delegated = self._mock_delegate
508 if delegated is None:
509 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400510 sf = delegated.side_effect
511 if sf is not None and not callable(sf) and not isinstance(sf, _MockIter):
512 sf = _MockIter(sf)
513 delegated.side_effect = sf
514 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700515
516 def __set_side_effect(self, value):
517 value = _try_iter(value)
518 delegated = self._mock_delegate
519 if delegated is None:
520 self._mock_side_effect = value
521 else:
522 delegated.side_effect = value
523
524 side_effect = property(__get_side_effect, __set_side_effect)
525
526
527 def reset_mock(self):
528 "Restore the mock object to its initial state."
529 self.called = False
530 self.call_args = None
531 self.call_count = 0
532 self.mock_calls = _CallList()
533 self.call_args_list = _CallList()
534 self.method_calls = _CallList()
535
536 for child in self._mock_children.values():
Michael Foord75963642012-06-09 17:31:59 +0100537 if isinstance(child, _SpecState):
538 continue
Michael Foord345266a2012-03-14 12:24:34 -0700539 child.reset_mock()
540
541 ret = self._mock_return_value
542 if _is_instance_mock(ret) and ret is not self:
543 ret.reset_mock()
544
545
546 def configure_mock(self, **kwargs):
547 """Set attributes on the mock through keyword arguments.
548
549 Attributes plus return values and side effects can be set on child
550 mocks using standard dot notation and unpacking a dictionary in the
551 method call:
552
553 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
554 >>> mock.configure_mock(**attrs)"""
555 for arg, val in sorted(kwargs.items(),
556 # we sort on the number of dots so that
557 # attributes are set before we set attributes on
558 # attributes
559 key=lambda entry: entry[0].count('.')):
560 args = arg.split('.')
561 final = args.pop()
562 obj = self
563 for entry in args:
564 obj = getattr(obj, entry)
565 setattr(obj, final, val)
566
567
568 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530569 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700570 raise AttributeError(name)
571 elif self._mock_methods is not None:
572 if name not in self._mock_methods or name in _all_magics:
573 raise AttributeError("Mock object has no attribute %r" % name)
574 elif _is_magic(name):
575 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530576 if not self._mock_unsafe:
577 if name.startswith(('assert', 'assret')):
578 raise AttributeError(name)
Michael Foord345266a2012-03-14 12:24:34 -0700579
580 result = self._mock_children.get(name)
581 if result is _deleted:
582 raise AttributeError(name)
583 elif result is None:
584 wraps = None
585 if self._mock_wraps is not None:
586 # XXXX should we get the attribute without triggering code
587 # execution?
588 wraps = getattr(self._mock_wraps, name)
589
590 result = self._get_child_mock(
591 parent=self, name=name, wraps=wraps, _new_name=name,
592 _new_parent=self
593 )
594 self._mock_children[name] = result
595
596 elif isinstance(result, _SpecState):
597 result = create_autospec(
598 result.spec, result.spec_set, result.instance,
599 result.parent, result.name
600 )
601 self._mock_children[name] = result
602
603 return result
604
605
606 def __repr__(self):
607 _name_list = [self._mock_new_name]
608 _parent = self._mock_new_parent
609 last = self
610
611 dot = '.'
612 if _name_list == ['()']:
613 dot = ''
614 seen = set()
615 while _parent is not None:
616 last = _parent
617
618 _name_list.append(_parent._mock_new_name + dot)
619 dot = '.'
620 if _parent._mock_new_name == '()':
621 dot = ''
622
623 _parent = _parent._mock_new_parent
624
625 # use ids here so as not to call __hash__ on the mocks
626 if id(_parent) in seen:
627 break
628 seen.add(id(_parent))
629
630 _name_list = list(reversed(_name_list))
631 _first = last._mock_name or 'mock'
632 if len(_name_list) > 1:
633 if _name_list[1] not in ('()', '().'):
634 _first += '.'
635 _name_list[0] = _first
636 name = ''.join(_name_list)
637
638 name_string = ''
639 if name not in ('mock', 'mock.'):
640 name_string = ' name=%r' % name
641
642 spec_string = ''
643 if self._spec_class is not None:
644 spec_string = ' spec=%r'
645 if self._spec_set:
646 spec_string = ' spec_set=%r'
647 spec_string = spec_string % self._spec_class.__name__
648 return "<%s%s%s id='%s'>" % (
649 type(self).__name__,
650 name_string,
651 spec_string,
652 id(self)
653 )
654
655
656 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700657 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100658 if not FILTER_DIR:
659 return object.__dir__(self)
660
Michael Foord345266a2012-03-14 12:24:34 -0700661 extras = self._mock_methods or []
662 from_type = dir(type(self))
663 from_dict = list(self.__dict__)
664
Michael Foord313f85f2012-03-25 18:16:07 +0100665 from_type = [e for e in from_type if not e.startswith('_')]
666 from_dict = [e for e in from_dict if not e.startswith('_') or
667 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700668 return sorted(set(extras + from_type + from_dict +
669 list(self._mock_children)))
670
671
672 def __setattr__(self, name, value):
673 if name in _allowed_names:
674 # property setters go through here
675 return object.__setattr__(self, name, value)
676 elif (self._spec_set and self._mock_methods is not None and
677 name not in self._mock_methods and
678 name not in self.__dict__):
679 raise AttributeError("Mock object has no attribute '%s'" % name)
680 elif name in _unsupported_magics:
681 msg = 'Attempting to set unsupported magic method %r.' % name
682 raise AttributeError(msg)
683 elif name in _all_magics:
684 if self._mock_methods is not None and name not in self._mock_methods:
685 raise AttributeError("Mock object has no attribute '%s'" % name)
686
687 if not _is_instance_mock(value):
688 setattr(type(self), name, _get_method(name, value))
689 original = value
690 value = lambda *args, **kw: original(self, *args, **kw)
691 else:
692 # only set _new_name and not name so that mock_calls is tracked
693 # but not method calls
694 _check_and_set_parent(self, value, None, name)
695 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100696 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700697 elif name == '__class__':
698 self._spec_class = value
699 return
700 else:
701 if _check_and_set_parent(self, value, name, name):
702 self._mock_children[name] = value
703 return object.__setattr__(self, name, value)
704
705
706 def __delattr__(self, name):
707 if name in _all_magics and name in type(self).__dict__:
708 delattr(type(self), name)
709 if name not in self.__dict__:
710 # for magic methods that are still MagicProxy objects and
711 # not set on the instance itself
712 return
713
714 if name in self.__dict__:
715 object.__delattr__(self, name)
716
717 obj = self._mock_children.get(name, _missing)
718 if obj is _deleted:
719 raise AttributeError(name)
720 if obj is not _missing:
721 del self._mock_children[name]
722 self._mock_children[name] = _deleted
723
724
Michael Foord345266a2012-03-14 12:24:34 -0700725 def _format_mock_call_signature(self, args, kwargs):
726 name = self._mock_name or 'mock'
727 return _format_call_signature(name, args, kwargs)
728
729
730 def _format_mock_failure_message(self, args, kwargs):
731 message = 'Expected call: %s\nActual call: %s'
732 expected_string = self._format_mock_call_signature(args, kwargs)
733 call_args = self.call_args
734 if len(call_args) == 3:
735 call_args = call_args[1:]
736 actual_string = self._format_mock_call_signature(*call_args)
737 return message % (expected_string, actual_string)
738
739
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100740 def _call_matcher(self, _call):
741 """
742 Given a call (or simply a (args, kwargs) tuple), return a
743 comparison key suitable for matching with other calls.
744 This is a best effort method which relies on the spec's signature,
745 if available, or falls back on the arguments themselves.
746 """
747 sig = self._spec_signature
748 if sig is not None:
749 if len(_call) == 2:
750 name = ''
751 args, kwargs = _call
752 else:
753 name, args, kwargs = _call
754 try:
755 return name, sig.bind(*args, **kwargs)
756 except TypeError as e:
757 return e.with_traceback(None)
758 else:
759 return _call
760
Kushal Das68290f42014-04-17 01:54:07 +0530761 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530762 """assert that the mock was never called.
763 """
764 self = _mock_self
765 if self.call_count != 0:
766 msg = ("Expected '%s' to not have been called. Called %s times." %
767 (self._mock_name or 'mock', self.call_count))
768 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100769
Michael Foord345266a2012-03-14 12:24:34 -0700770 def assert_called_with(_mock_self, *args, **kwargs):
771 """assert that the mock was called with the specified arguments.
772
773 Raises an AssertionError if the args and keyword args passed in are
774 different to the last call to the mock."""
775 self = _mock_self
776 if self.call_args is None:
777 expected = self._format_mock_call_signature(args, kwargs)
778 raise AssertionError('Expected call: %s\nNot called' % (expected,))
779
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100780 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700781 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100782 return msg
783 expected = self._call_matcher((args, kwargs))
784 actual = self._call_matcher(self.call_args)
785 if expected != actual:
786 cause = expected if isinstance(expected, Exception) else None
787 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700788
789
790 def assert_called_once_with(_mock_self, *args, **kwargs):
791 """assert that the mock was called exactly once and with the specified
792 arguments."""
793 self = _mock_self
794 if not self.call_count == 1:
Michael Foord28d591c2012-09-28 16:15:22 +0100795 msg = ("Expected '%s' to be called once. Called %s times." %
796 (self._mock_name or 'mock', self.call_count))
Michael Foord345266a2012-03-14 12:24:34 -0700797 raise AssertionError(msg)
798 return self.assert_called_with(*args, **kwargs)
799
800
801 def assert_has_calls(self, calls, any_order=False):
802 """assert the mock has been called with the specified calls.
803 The `mock_calls` list is checked for the calls.
804
805 If `any_order` is False (the default) then the calls must be
806 sequential. There can be extra calls before or after the
807 specified calls.
808
809 If `any_order` is True then the calls can be in any order, but
810 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100811 expected = [self._call_matcher(c) for c in calls]
812 cause = expected if isinstance(expected, Exception) else None
813 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700814 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100815 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700816 raise AssertionError(
817 'Calls not found.\nExpected: %r\n'
818 'Actual: %r' % (calls, self.mock_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100819 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700820 return
821
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100822 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700823
824 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100825 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700826 try:
827 all_calls.remove(kall)
828 except ValueError:
829 not_found.append(kall)
830 if not_found:
831 raise AssertionError(
832 '%r not all found in call list' % (tuple(not_found),)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100833 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700834
835
836 def assert_any_call(self, *args, **kwargs):
837 """assert the mock has been called with the specified arguments.
838
839 The assert passes if the mock has *ever* been called, unlike
840 `assert_called_with` and `assert_called_once_with` that only pass if
841 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100842 expected = self._call_matcher((args, kwargs))
843 actual = [self._call_matcher(c) for c in self.call_args_list]
844 if expected not in actual:
845 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700846 expected_string = self._format_mock_call_signature(args, kwargs)
847 raise AssertionError(
848 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100849 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700850
851
852 def _get_child_mock(self, **kw):
853 """Create the child mocks for attributes and return value.
854 By default child mocks will be the same type as the parent.
855 Subclasses of Mock may want to override this to customize the way
856 child mocks are made.
857
858 For non-callable mocks the callable variant will be used (rather than
859 any custom subclass)."""
860 _type = type(self)
861 if not issubclass(_type, CallableMixin):
862 if issubclass(_type, NonCallableMagicMock):
863 klass = MagicMock
864 elif issubclass(_type, NonCallableMock) :
865 klass = Mock
866 else:
867 klass = _type.__mro__[1]
868 return klass(**kw)
869
870
871
872def _try_iter(obj):
873 if obj is None:
874 return obj
875 if _is_exception(obj):
876 return obj
877 if _callable(obj):
878 return obj
879 try:
880 return iter(obj)
881 except TypeError:
882 # XXXX backwards compatibility
883 # but this will blow up on first call - so maybe we should fail early?
884 return obj
885
886
887
888class CallableMixin(Base):
889
890 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
891 wraps=None, name=None, spec_set=None, parent=None,
892 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
893 self.__dict__['_mock_return_value'] = return_value
894
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000895 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700896 spec, wraps, name, spec_set, parent,
897 _spec_state, _new_name, _new_parent, **kwargs
898 )
899
900 self.side_effect = side_effect
901
902
903 def _mock_check_sig(self, *args, **kwargs):
904 # stub method that can be replaced with one with a specific signature
905 pass
906
907
908 def __call__(_mock_self, *args, **kwargs):
909 # can't use self in-case a function / method we are mocking uses self
910 # in the signature
911 _mock_self._mock_check_sig(*args, **kwargs)
912 return _mock_self._mock_call(*args, **kwargs)
913
914
915 def _mock_call(_mock_self, *args, **kwargs):
916 self = _mock_self
917 self.called = True
918 self.call_count += 1
Michael Foord345266a2012-03-14 12:24:34 -0700919 _new_name = self._mock_new_name
920 _new_parent = self._mock_new_parent
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100921
922 _call = _Call((args, kwargs), two=True)
923 self.call_args = _call
924 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700925 self.mock_calls.append(_Call(('', args, kwargs)))
926
927 seen = set()
928 skip_next_dot = _new_name == '()'
929 do_method_calls = self._mock_parent is not None
930 name = self._mock_name
931 while _new_parent is not None:
932 this_mock_call = _Call((_new_name, args, kwargs))
933 if _new_parent._mock_new_name:
934 dot = '.'
935 if skip_next_dot:
936 dot = ''
937
938 skip_next_dot = False
939 if _new_parent._mock_new_name == '()':
940 skip_next_dot = True
941
942 _new_name = _new_parent._mock_new_name + dot + _new_name
943
944 if do_method_calls:
945 if _new_name == name:
946 this_method_call = this_mock_call
947 else:
948 this_method_call = _Call((name, args, kwargs))
949 _new_parent.method_calls.append(this_method_call)
950
951 do_method_calls = _new_parent._mock_parent is not None
952 if do_method_calls:
953 name = _new_parent._mock_name + '.' + name
954
955 _new_parent.mock_calls.append(this_mock_call)
956 _new_parent = _new_parent._mock_new_parent
957
958 # use ids here so as not to call __hash__ on the mocks
959 _new_parent_id = id(_new_parent)
960 if _new_parent_id in seen:
961 break
962 seen.add(_new_parent_id)
963
964 ret_val = DEFAULT
965 effect = self.side_effect
966 if effect is not None:
967 if _is_exception(effect):
968 raise effect
969
970 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +0100971 result = next(effect)
972 if _is_exception(result):
973 raise result
Andrew Svetlov8b2cd752013-04-07 16:42:24 +0300974 if result is DEFAULT:
975 result = self.return_value
Michael Foord2cd48732012-04-21 15:52:11 +0100976 return result
Michael Foord345266a2012-03-14 12:24:34 -0700977
978 ret_val = effect(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700979
980 if (self._mock_wraps is not None and
981 self._mock_return_value is DEFAULT):
982 return self._mock_wraps(*args, **kwargs)
983 if ret_val is DEFAULT:
984 ret_val = self.return_value
985 return ret_val
986
987
988
989class Mock(CallableMixin, NonCallableMock):
990 """
991 Create a new `Mock` object. `Mock` takes several optional arguments
992 that specify the behaviour of the Mock object:
993
994 * `spec`: This can be either a list of strings or an existing object (a
995 class or instance) that acts as the specification for the mock object. If
996 you pass in an object then a list of strings is formed by calling dir on
997 the object (excluding unsupported magic attributes and methods). Accessing
998 any attribute not in this list will raise an `AttributeError`.
999
1000 If `spec` is an object (rather than a list of strings) then
1001 `mock.__class__` returns the class of the spec object. This allows mocks
1002 to pass `isinstance` tests.
1003
1004 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1005 or get an attribute on the mock that isn't on the object passed as
1006 `spec_set` will raise an `AttributeError`.
1007
1008 * `side_effect`: A function to be called whenever the Mock is called. See
1009 the `side_effect` attribute. Useful for raising exceptions or
1010 dynamically changing return values. The function is called with the same
1011 arguments as the mock, and unless it returns `DEFAULT`, the return
1012 value of this function is used as the return value.
1013
Michael Foord2cd48732012-04-21 15:52:11 +01001014 If `side_effect` is an iterable then each call to the mock will return
1015 the next value from the iterable. If any of the members of the iterable
1016 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001017
Michael Foord345266a2012-03-14 12:24:34 -07001018 * `return_value`: The value returned when the mock is called. By default
1019 this is a new Mock (created on first access). See the
1020 `return_value` attribute.
1021
Michael Foord0682a0c2012-04-13 20:51:20 +01001022 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1023 calling the Mock will pass the call through to the wrapped object
1024 (returning the real result). Attribute access on the mock will return a
1025 Mock object that wraps the corresponding attribute of the wrapped object
1026 (so attempting to access an attribute that doesn't exist will raise an
1027 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001028
1029 If the mock has an explicit `return_value` set then calls are not passed
1030 to the wrapped object and the `return_value` is returned instead.
1031
1032 * `name`: If the mock has a name then it will be used in the repr of the
1033 mock. This can be useful for debugging. The name is propagated to child
1034 mocks.
1035
1036 Mocks can also be called with arbitrary keyword arguments. These will be
1037 used to set attributes on the mock after it is created.
1038 """
1039
1040
1041
1042def _dot_lookup(thing, comp, import_path):
1043 try:
1044 return getattr(thing, comp)
1045 except AttributeError:
1046 __import__(import_path)
1047 return getattr(thing, comp)
1048
1049
1050def _importer(target):
1051 components = target.split('.')
1052 import_path = components.pop(0)
1053 thing = __import__(import_path)
1054
1055 for comp in components:
1056 import_path += ".%s" % comp
1057 thing = _dot_lookup(thing, comp, import_path)
1058 return thing
1059
1060
1061def _is_started(patcher):
1062 # XXXX horrible
1063 return hasattr(patcher, 'is_local')
1064
1065
1066class _patch(object):
1067
1068 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001069 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001070
1071 def __init__(
1072 self, getter, attribute, new, spec, create,
1073 spec_set, autospec, new_callable, kwargs
1074 ):
1075 if new_callable is not None:
1076 if new is not DEFAULT:
1077 raise ValueError(
1078 "Cannot use 'new' and 'new_callable' together"
1079 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001080 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001081 raise ValueError(
1082 "Cannot use 'autospec' and 'new_callable' together"
1083 )
1084
1085 self.getter = getter
1086 self.attribute = attribute
1087 self.new = new
1088 self.new_callable = new_callable
1089 self.spec = spec
1090 self.create = create
1091 self.has_local = False
1092 self.spec_set = spec_set
1093 self.autospec = autospec
1094 self.kwargs = kwargs
1095 self.additional_patchers = []
1096
1097
1098 def copy(self):
1099 patcher = _patch(
1100 self.getter, self.attribute, self.new, self.spec,
1101 self.create, self.spec_set,
1102 self.autospec, self.new_callable, self.kwargs
1103 )
1104 patcher.attribute_name = self.attribute_name
1105 patcher.additional_patchers = [
1106 p.copy() for p in self.additional_patchers
1107 ]
1108 return patcher
1109
1110
1111 def __call__(self, func):
1112 if isinstance(func, type):
1113 return self.decorate_class(func)
1114 return self.decorate_callable(func)
1115
1116
1117 def decorate_class(self, klass):
1118 for attr in dir(klass):
1119 if not attr.startswith(patch.TEST_PREFIX):
1120 continue
1121
1122 attr_value = getattr(klass, attr)
1123 if not hasattr(attr_value, "__call__"):
1124 continue
1125
1126 patcher = self.copy()
1127 setattr(klass, attr, patcher(attr_value))
1128 return klass
1129
1130
1131 def decorate_callable(self, func):
1132 if hasattr(func, 'patchings'):
1133 func.patchings.append(self)
1134 return func
1135
1136 @wraps(func)
1137 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001138 extra_args = []
1139 entered_patchers = []
1140
Michael Foord50a8c0e2012-03-25 18:57:58 +01001141 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001142 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001143 for patching in patched.patchings:
1144 arg = patching.__enter__()
1145 entered_patchers.append(patching)
1146 if patching.attribute_name is not None:
1147 keywargs.update(arg)
1148 elif patching.new is DEFAULT:
1149 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001150
Michael Foordd7c65e22012-03-14 14:56:54 -07001151 args += tuple(extra_args)
1152 return func(*args, **keywargs)
1153 except:
1154 if (patching not in entered_patchers and
1155 _is_started(patching)):
1156 # the patcher may have been started, but an exception
1157 # raised whilst entering one of its additional_patchers
1158 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001159 # Pass the exception to __exit__
1160 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001161 # re-raise the exception
1162 raise
Michael Foord345266a2012-03-14 12:24:34 -07001163 finally:
1164 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001165 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001166
1167 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001168 return patched
1169
1170
1171 def get_original(self):
1172 target = self.getter()
1173 name = self.attribute
1174
1175 original = DEFAULT
1176 local = False
1177
1178 try:
1179 original = target.__dict__[name]
1180 except (AttributeError, KeyError):
1181 original = getattr(target, name, DEFAULT)
1182 else:
1183 local = True
1184
Michael Foordfddcfa22014-04-14 16:25:20 -04001185 if name in _builtins and isinstance(target, ModuleType):
1186 self.create = True
1187
Michael Foord345266a2012-03-14 12:24:34 -07001188 if not self.create and original is DEFAULT:
1189 raise AttributeError(
1190 "%s does not have the attribute %r" % (target, name)
1191 )
1192 return original, local
1193
1194
1195 def __enter__(self):
1196 """Perform the patch."""
1197 new, spec, spec_set = self.new, self.spec, self.spec_set
1198 autospec, kwargs = self.autospec, self.kwargs
1199 new_callable = self.new_callable
1200 self.target = self.getter()
1201
Michael Foord50a8c0e2012-03-25 18:57:58 +01001202 # normalise False to None
1203 if spec is False:
1204 spec = None
1205 if spec_set is False:
1206 spec_set = None
1207 if autospec is False:
1208 autospec = None
1209
1210 if spec is not None and autospec is not None:
1211 raise TypeError("Can't specify spec and autospec")
1212 if ((spec is not None or autospec is not None) and
1213 spec_set not in (True, None)):
1214 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1215
Michael Foord345266a2012-03-14 12:24:34 -07001216 original, local = self.get_original()
1217
Michael Foord50a8c0e2012-03-25 18:57:58 +01001218 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001219 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001220 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001221 # set spec to the object we are replacing
1222 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001223 if spec_set is True:
1224 spec_set = original
1225 spec = None
1226 elif spec is not None:
1227 if spec_set is True:
1228 spec_set = spec
1229 spec = None
1230 elif spec_set is True:
1231 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001232
Michael Foord50a8c0e2012-03-25 18:57:58 +01001233 if spec is not None or spec_set is not None:
1234 if original is DEFAULT:
1235 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001236 if isinstance(original, type):
1237 # If we're patching out a class and there is a spec
1238 inherit = True
1239
1240 Klass = MagicMock
1241 _kwargs = {}
1242 if new_callable is not None:
1243 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001244 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001245 this_spec = spec
1246 if spec_set is not None:
1247 this_spec = spec_set
1248 if _is_list(this_spec):
1249 not_callable = '__call__' not in this_spec
1250 else:
1251 not_callable = not callable(this_spec)
1252 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001253 Klass = NonCallableMagicMock
1254
1255 if spec is not None:
1256 _kwargs['spec'] = spec
1257 if spec_set is not None:
1258 _kwargs['spec_set'] = spec_set
1259
1260 # add a name to mocks
1261 if (isinstance(Klass, type) and
1262 issubclass(Klass, NonCallableMock) and self.attribute):
1263 _kwargs['name'] = self.attribute
1264
1265 _kwargs.update(kwargs)
1266 new = Klass(**_kwargs)
1267
1268 if inherit and _is_instance_mock(new):
1269 # we can only tell if the instance should be callable if the
1270 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001271 this_spec = spec
1272 if spec_set is not None:
1273 this_spec = spec_set
1274 if (not _is_list(this_spec) and not
1275 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001276 Klass = NonCallableMagicMock
1277
1278 _kwargs.pop('name')
1279 new.return_value = Klass(_new_parent=new, _new_name='()',
1280 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001281 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001282 # spec is ignored, new *must* be default, spec_set is treated
1283 # as a boolean. Should we check spec is not None and that spec_set
1284 # is a bool?
1285 if new is not DEFAULT:
1286 raise TypeError(
1287 "autospec creates the mock for you. Can't specify "
1288 "autospec and new."
1289 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001290 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001291 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001292 spec_set = bool(spec_set)
1293 if autospec is True:
1294 autospec = original
1295
1296 new = create_autospec(autospec, spec_set=spec_set,
1297 _name=self.attribute, **kwargs)
1298 elif kwargs:
1299 # can't set keyword args when we aren't creating the mock
1300 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1301 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1302
1303 new_attr = new
1304
1305 self.temp_original = original
1306 self.is_local = local
1307 setattr(self.target, self.attribute, new_attr)
1308 if self.attribute_name is not None:
1309 extra_args = {}
1310 if self.new is DEFAULT:
1311 extra_args[self.attribute_name] = new
1312 for patching in self.additional_patchers:
1313 arg = patching.__enter__()
1314 if patching.new is DEFAULT:
1315 extra_args.update(arg)
1316 return extra_args
1317
1318 return new
1319
1320
Michael Foord50a8c0e2012-03-25 18:57:58 +01001321 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001322 """Undo the patch."""
1323 if not _is_started(self):
1324 raise RuntimeError('stop called on unstarted patcher')
1325
1326 if self.is_local and self.temp_original is not DEFAULT:
1327 setattr(self.target, self.attribute, self.temp_original)
1328 else:
1329 delattr(self.target, self.attribute)
1330 if not self.create and not hasattr(self.target, self.attribute):
1331 # needed for proxy objects like django settings
1332 setattr(self.target, self.attribute, self.temp_original)
1333
1334 del self.temp_original
1335 del self.is_local
1336 del self.target
1337 for patcher in reversed(self.additional_patchers):
1338 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001339 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001340
Michael Foordf7c41582012-06-10 20:36:32 +01001341
1342 def start(self):
1343 """Activate a patch, returning any created mock."""
1344 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001345 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001346 return result
1347
1348
1349 def stop(self):
1350 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001351 try:
1352 self._active_patches.remove(self)
1353 except ValueError:
1354 # If the patch hasn't been started this will fail
1355 pass
1356
Michael Foordf7c41582012-06-10 20:36:32 +01001357 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001358
1359
1360
1361def _get_target(target):
1362 try:
1363 target, attribute = target.rsplit('.', 1)
1364 except (TypeError, ValueError):
1365 raise TypeError("Need a valid target to patch. You supplied: %r" %
1366 (target,))
1367 getter = lambda: _importer(target)
1368 return getter, attribute
1369
1370
1371def _patch_object(
1372 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001373 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001374 new_callable=None, **kwargs
1375 ):
1376 """
Michael Foord345266a2012-03-14 12:24:34 -07001377 patch the named member (`attribute`) on an object (`target`) with a mock
1378 object.
1379
1380 `patch.object` can be used as a decorator, class decorator or a context
1381 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1382 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1383 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1384 the mock object it creates.
1385
1386 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1387 for choosing which methods to wrap.
1388 """
1389 getter = lambda: target
1390 return _patch(
1391 getter, attribute, new, spec, create,
1392 spec_set, autospec, new_callable, kwargs
1393 )
1394
1395
Michael Foord50a8c0e2012-03-25 18:57:58 +01001396def _patch_multiple(target, spec=None, create=False, spec_set=None,
1397 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001398 """Perform multiple patches in a single call. It takes the object to be
1399 patched (either as an object or a string to fetch the object by importing)
1400 and keyword arguments for the patches::
1401
1402 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1403 ...
1404
1405 Use `DEFAULT` as the value if you want `patch.multiple` to create
1406 mocks for you. In this case the created mocks are passed into a decorated
1407 function by keyword, and a dictionary is returned when `patch.multiple` is
1408 used as a context manager.
1409
1410 `patch.multiple` can be used as a decorator, class decorator or a context
1411 manager. The arguments `spec`, `spec_set`, `create`,
1412 `autospec` and `new_callable` have the same meaning as for `patch`. These
1413 arguments will be applied to *all* patches done by `patch.multiple`.
1414
1415 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1416 for choosing which methods to wrap.
1417 """
1418 if type(target) is str:
1419 getter = lambda: _importer(target)
1420 else:
1421 getter = lambda: target
1422
1423 if not kwargs:
1424 raise ValueError(
1425 'Must supply at least one keyword argument with patch.multiple'
1426 )
1427 # need to wrap in a list for python 3, where items is a view
1428 items = list(kwargs.items())
1429 attribute, new = items[0]
1430 patcher = _patch(
1431 getter, attribute, new, spec, create, spec_set,
1432 autospec, new_callable, {}
1433 )
1434 patcher.attribute_name = attribute
1435 for attribute, new in items[1:]:
1436 this_patcher = _patch(
1437 getter, attribute, new, spec, create, spec_set,
1438 autospec, new_callable, {}
1439 )
1440 this_patcher.attribute_name = attribute
1441 patcher.additional_patchers.append(this_patcher)
1442 return patcher
1443
1444
1445def patch(
1446 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001447 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001448 ):
1449 """
1450 `patch` acts as a function decorator, class decorator or a context
1451 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001452 is patched with a `new` object. When the function/with statement exits
1453 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001454
Michael Foord54b3db82012-03-28 15:08:08 +01001455 If `new` is omitted, then the target is replaced with a
1456 `MagicMock`. If `patch` is used as a decorator and `new` is
1457 omitted, the created mock is passed in as an extra argument to the
1458 decorated function. If `patch` is used as a context manager the created
1459 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001460
Michael Foord54b3db82012-03-28 15:08:08 +01001461 `target` should be a string in the form `'package.module.ClassName'`. The
1462 `target` is imported and the specified object replaced with the `new`
1463 object, so the `target` must be importable from the environment you are
1464 calling `patch` from. The target is imported when the decorated function
1465 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001466
1467 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1468 if patch is creating one for you.
1469
1470 In addition you can pass `spec=True` or `spec_set=True`, which causes
1471 patch to pass in the object being mocked as the spec/spec_set object.
1472
1473 `new_callable` allows you to specify a different class, or callable object,
1474 that will be called to create the `new` object. By default `MagicMock` is
1475 used.
1476
1477 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1478 then the mock with be created with a spec from the object being replaced.
1479 All attributes of the mock will also have the spec of the corresponding
1480 attribute of the object being replaced. Methods and functions being
1481 mocked will have their arguments checked and will raise a `TypeError` if
1482 they are called with the wrong signature. For mocks replacing a class,
1483 their return value (the 'instance') will have the same spec as the class.
1484
1485 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1486 arbitrary object as the spec instead of the one being replaced.
1487
1488 By default `patch` will fail to replace attributes that don't exist. If
1489 you pass in `create=True`, and the attribute doesn't exist, patch will
1490 create the attribute for you when the patched function is called, and
1491 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001492 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001493 default because it can be dangerous. With it switched on you can write
1494 passing tests against APIs that don't actually exist!
1495
1496 Patch can be used as a `TestCase` class decorator. It works by
1497 decorating each test method in the class. This reduces the boilerplate
1498 code when your test methods share a common patchings set. `patch` finds
1499 tests by looking for method names that start with `patch.TEST_PREFIX`.
1500 By default this is `test`, which matches the way `unittest` finds tests.
1501 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1502
1503 Patch can be used as a context manager, with the with statement. Here the
1504 patching applies to the indented block after the with statement. If you
1505 use "as" then the patched object will be bound to the name after the
1506 "as"; very useful if `patch` is creating a mock object for you.
1507
1508 `patch` takes arbitrary keyword arguments. These will be passed to
1509 the `Mock` (or `new_callable`) on construction.
1510
1511 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1512 available for alternate use-cases.
1513 """
1514 getter, attribute = _get_target(target)
1515 return _patch(
1516 getter, attribute, new, spec, create,
1517 spec_set, autospec, new_callable, kwargs
1518 )
1519
1520
1521class _patch_dict(object):
1522 """
1523 Patch a dictionary, or dictionary like object, and restore the dictionary
1524 to its original state after the test.
1525
1526 `in_dict` can be a dictionary or a mapping like container. If it is a
1527 mapping then it must at least support getting, setting and deleting items
1528 plus iterating over keys.
1529
1530 `in_dict` can also be a string specifying the name of the dictionary, which
1531 will then be fetched by importing it.
1532
1533 `values` can be a dictionary of values to set in the dictionary. `values`
1534 can also be an iterable of `(key, value)` pairs.
1535
1536 If `clear` is True then the dictionary will be cleared before the new
1537 values are set.
1538
1539 `patch.dict` can also be called with arbitrary keyword arguments to set
1540 values in the dictionary::
1541
1542 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1543 ...
1544
1545 `patch.dict` can be used as a context manager, decorator or class
1546 decorator. When used as a class decorator `patch.dict` honours
1547 `patch.TEST_PREFIX` for choosing which methods to wrap.
1548 """
1549
1550 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1551 if isinstance(in_dict, str):
1552 in_dict = _importer(in_dict)
1553 self.in_dict = in_dict
1554 # support any argument supported by dict(...) constructor
1555 self.values = dict(values)
1556 self.values.update(kwargs)
1557 self.clear = clear
1558 self._original = None
1559
1560
1561 def __call__(self, f):
1562 if isinstance(f, type):
1563 return self.decorate_class(f)
1564 @wraps(f)
1565 def _inner(*args, **kw):
1566 self._patch_dict()
1567 try:
1568 return f(*args, **kw)
1569 finally:
1570 self._unpatch_dict()
1571
1572 return _inner
1573
1574
1575 def decorate_class(self, klass):
1576 for attr in dir(klass):
1577 attr_value = getattr(klass, attr)
1578 if (attr.startswith(patch.TEST_PREFIX) and
1579 hasattr(attr_value, "__call__")):
1580 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1581 decorated = decorator(attr_value)
1582 setattr(klass, attr, decorated)
1583 return klass
1584
1585
1586 def __enter__(self):
1587 """Patch the dict."""
1588 self._patch_dict()
1589
1590
1591 def _patch_dict(self):
1592 values = self.values
1593 in_dict = self.in_dict
1594 clear = self.clear
1595
1596 try:
1597 original = in_dict.copy()
1598 except AttributeError:
1599 # dict like object with no copy method
1600 # must support iteration over keys
1601 original = {}
1602 for key in in_dict:
1603 original[key] = in_dict[key]
1604 self._original = original
1605
1606 if clear:
1607 _clear_dict(in_dict)
1608
1609 try:
1610 in_dict.update(values)
1611 except AttributeError:
1612 # dict like object with no update method
1613 for key in values:
1614 in_dict[key] = values[key]
1615
1616
1617 def _unpatch_dict(self):
1618 in_dict = self.in_dict
1619 original = self._original
1620
1621 _clear_dict(in_dict)
1622
1623 try:
1624 in_dict.update(original)
1625 except AttributeError:
1626 for key in original:
1627 in_dict[key] = original[key]
1628
1629
1630 def __exit__(self, *args):
1631 """Unpatch the dict."""
1632 self._unpatch_dict()
1633 return False
1634
1635 start = __enter__
1636 stop = __exit__
1637
1638
1639def _clear_dict(in_dict):
1640 try:
1641 in_dict.clear()
1642 except AttributeError:
1643 keys = list(in_dict)
1644 for key in keys:
1645 del in_dict[key]
1646
1647
Michael Foordf7c41582012-06-10 20:36:32 +01001648def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001649 """Stop all active patches. LIFO to unroll nested patches."""
1650 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001651 patch.stop()
1652
1653
Michael Foord345266a2012-03-14 12:24:34 -07001654patch.object = _patch_object
1655patch.dict = _patch_dict
1656patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001657patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001658patch.TEST_PREFIX = 'test'
1659
1660magic_methods = (
1661 "lt le gt ge eq ne "
1662 "getitem setitem delitem "
1663 "len contains iter "
1664 "hash str sizeof "
1665 "enter exit "
1666 "divmod neg pos abs invert "
1667 "complex int float index "
1668 "trunc floor ceil "
1669 "bool next "
1670)
1671
Michael Foordd2623d72014-04-14 11:23:48 -04001672numerics = (
1673 "add sub mul div floordiv mod lshift rshift and xor or pow truediv"
1674)
Michael Foord345266a2012-03-14 12:24:34 -07001675inplace = ' '.join('i%s' % n for n in numerics.split())
1676right = ' '.join('r%s' % n for n in numerics.split())
1677
1678# not including __prepare__, __instancecheck__, __subclasscheck__
1679# (as they are metaclass methods)
1680# __del__ is not supported at all as it causes problems if it exists
1681
1682_non_defaults = set('__%s__' % method for method in [
Michael Foord944e02d2012-03-25 23:12:55 +01001683 'get', 'set', 'delete', 'reversed', 'missing', 'reduce', 'reduce_ex',
1684 'getinitargs', 'getnewargs', 'getstate', 'setstate', 'getformat',
1685 'setformat', 'repr', 'dir', 'subclasses', 'format',
Michael Foord345266a2012-03-14 12:24:34 -07001686])
1687
1688
1689def _get_method(name, func):
1690 "Turns a callable object (like a mock) into a real function"
1691 def method(self, *args, **kw):
1692 return func(self, *args, **kw)
1693 method.__name__ = name
1694 return method
1695
1696
1697_magics = set(
1698 '__%s__' % method for method in
1699 ' '.join([magic_methods, numerics, inplace, right]).split()
1700)
1701
1702_all_magics = _magics | _non_defaults
1703
1704_unsupported_magics = set([
1705 '__getattr__', '__setattr__',
1706 '__init__', '__new__', '__prepare__'
1707 '__instancecheck__', '__subclasscheck__',
1708 '__del__'
1709])
1710
1711_calculate_return_value = {
1712 '__hash__': lambda self: object.__hash__(self),
1713 '__str__': lambda self: object.__str__(self),
1714 '__sizeof__': lambda self: object.__sizeof__(self),
1715}
1716
1717_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001718 '__lt__': NotImplemented,
1719 '__gt__': NotImplemented,
1720 '__le__': NotImplemented,
1721 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001722 '__int__': 1,
1723 '__contains__': False,
1724 '__len__': 0,
1725 '__exit__': False,
1726 '__complex__': 1j,
1727 '__float__': 1.0,
1728 '__bool__': True,
1729 '__index__': 1,
1730}
1731
1732
1733def _get_eq(self):
1734 def __eq__(other):
1735 ret_val = self.__eq__._mock_return_value
1736 if ret_val is not DEFAULT:
1737 return ret_val
1738 return self is other
1739 return __eq__
1740
1741def _get_ne(self):
1742 def __ne__(other):
1743 if self.__ne__._mock_return_value is not DEFAULT:
1744 return DEFAULT
1745 return self is not other
1746 return __ne__
1747
1748def _get_iter(self):
1749 def __iter__():
1750 ret_val = self.__iter__._mock_return_value
1751 if ret_val is DEFAULT:
1752 return iter([])
1753 # if ret_val was already an iterator, then calling iter on it should
1754 # return the iterator unchanged
1755 return iter(ret_val)
1756 return __iter__
1757
1758_side_effect_methods = {
1759 '__eq__': _get_eq,
1760 '__ne__': _get_ne,
1761 '__iter__': _get_iter,
1762}
1763
1764
1765
1766def _set_return_value(mock, method, name):
1767 fixed = _return_values.get(name, DEFAULT)
1768 if fixed is not DEFAULT:
1769 method.return_value = fixed
1770 return
1771
1772 return_calulator = _calculate_return_value.get(name)
1773 if return_calulator is not None:
1774 try:
1775 return_value = return_calulator(mock)
1776 except AttributeError:
1777 # XXXX why do we return AttributeError here?
1778 # set it as a side_effect instead?
1779 return_value = AttributeError(name)
1780 method.return_value = return_value
1781 return
1782
1783 side_effector = _side_effect_methods.get(name)
1784 if side_effector is not None:
1785 method.side_effect = side_effector(mock)
1786
1787
1788
1789class MagicMixin(object):
1790 def __init__(self, *args, **kw):
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001791 _safe_super(MagicMixin, self).__init__(*args, **kw)
Michael Foord345266a2012-03-14 12:24:34 -07001792 self._mock_set_magics()
1793
1794
1795 def _mock_set_magics(self):
1796 these_magics = _magics
1797
1798 if self._mock_methods is not None:
1799 these_magics = _magics.intersection(self._mock_methods)
1800
1801 remove_magics = set()
1802 remove_magics = _magics - these_magics
1803
1804 for entry in remove_magics:
1805 if entry in type(self).__dict__:
1806 # remove unneeded magic methods
1807 delattr(self, entry)
1808
1809 # don't overwrite existing attributes if called a second time
1810 these_magics = these_magics - set(type(self).__dict__)
1811
1812 _type = type(self)
1813 for entry in these_magics:
1814 setattr(_type, entry, MagicProxy(entry, self))
1815
1816
1817
1818class NonCallableMagicMock(MagicMixin, NonCallableMock):
1819 """A version of `MagicMock` that isn't callable."""
1820 def mock_add_spec(self, spec, spec_set=False):
1821 """Add a spec to a mock. `spec` can either be an object or a
1822 list of strings. Only attributes on the `spec` can be fetched as
1823 attributes from the mock.
1824
1825 If `spec_set` is True then only attributes on the spec can be set."""
1826 self._mock_add_spec(spec, spec_set)
1827 self._mock_set_magics()
1828
1829
1830
1831class MagicMock(MagicMixin, Mock):
1832 """
1833 MagicMock is a subclass of Mock with default implementations
1834 of most of the magic methods. You can use MagicMock without having to
1835 configure the magic methods yourself.
1836
1837 If you use the `spec` or `spec_set` arguments then *only* magic
1838 methods that exist in the spec will be created.
1839
1840 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1841 """
1842 def mock_add_spec(self, spec, spec_set=False):
1843 """Add a spec to a mock. `spec` can either be an object or a
1844 list of strings. Only attributes on the `spec` can be fetched as
1845 attributes from the mock.
1846
1847 If `spec_set` is True then only attributes on the spec can be set."""
1848 self._mock_add_spec(spec, spec_set)
1849 self._mock_set_magics()
1850
1851
1852
1853class MagicProxy(object):
1854 def __init__(self, name, parent):
1855 self.name = name
1856 self.parent = parent
1857
1858 def __call__(self, *args, **kwargs):
1859 m = self.create_mock()
1860 return m(*args, **kwargs)
1861
1862 def create_mock(self):
1863 entry = self.name
1864 parent = self.parent
1865 m = parent._get_child_mock(name=entry, _new_name=entry,
1866 _new_parent=parent)
1867 setattr(parent, entry, m)
1868 _set_return_value(parent, m, entry)
1869 return m
1870
1871 def __get__(self, obj, _type=None):
1872 return self.create_mock()
1873
1874
1875
1876class _ANY(object):
1877 "A helper object that compares equal to everything."
1878
1879 def __eq__(self, other):
1880 return True
1881
1882 def __ne__(self, other):
1883 return False
1884
1885 def __repr__(self):
1886 return '<ANY>'
1887
1888ANY = _ANY()
1889
1890
1891
1892def _format_call_signature(name, args, kwargs):
1893 message = '%s(%%s)' % name
1894 formatted_args = ''
1895 args_string = ', '.join([repr(arg) for arg in args])
1896 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301897 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001898 ])
1899 if args_string:
1900 formatted_args = args_string
1901 if kwargs_string:
1902 if formatted_args:
1903 formatted_args += ', '
1904 formatted_args += kwargs_string
1905
1906 return message % formatted_args
1907
1908
1909
1910class _Call(tuple):
1911 """
1912 A tuple for holding the results of a call to a mock, either in the form
1913 `(args, kwargs)` or `(name, args, kwargs)`.
1914
1915 If args or kwargs are empty then a call tuple will compare equal to
1916 a tuple without those values. This makes comparisons less verbose::
1917
1918 _Call(('name', (), {})) == ('name',)
1919 _Call(('name', (1,), {})) == ('name', (1,))
1920 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1921
1922 The `_Call` object provides a useful shortcut for comparing with call::
1923
1924 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1925 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1926
1927 If the _Call has no name then it will match any name.
1928 """
1929 def __new__(cls, value=(), name=None, parent=None, two=False,
1930 from_kall=True):
1931 name = ''
1932 args = ()
1933 kwargs = {}
1934 _len = len(value)
1935 if _len == 3:
1936 name, args, kwargs = value
1937 elif _len == 2:
1938 first, second = value
1939 if isinstance(first, str):
1940 name = first
1941 if isinstance(second, tuple):
1942 args = second
1943 else:
1944 kwargs = second
1945 else:
1946 args, kwargs = first, second
1947 elif _len == 1:
1948 value, = value
1949 if isinstance(value, str):
1950 name = value
1951 elif isinstance(value, tuple):
1952 args = value
1953 else:
1954 kwargs = value
1955
1956 if two:
1957 return tuple.__new__(cls, (args, kwargs))
1958
1959 return tuple.__new__(cls, (name, args, kwargs))
1960
1961
1962 def __init__(self, value=(), name=None, parent=None, two=False,
1963 from_kall=True):
1964 self.name = name
1965 self.parent = parent
1966 self.from_kall = from_kall
1967
1968
1969 def __eq__(self, other):
1970 if other is ANY:
1971 return True
1972 try:
1973 len_other = len(other)
1974 except TypeError:
1975 return False
1976
1977 self_name = ''
1978 if len(self) == 2:
1979 self_args, self_kwargs = self
1980 else:
1981 self_name, self_args, self_kwargs = self
1982
1983 other_name = ''
1984 if len_other == 0:
1985 other_args, other_kwargs = (), {}
1986 elif len_other == 3:
1987 other_name, other_args, other_kwargs = other
1988 elif len_other == 1:
1989 value, = other
1990 if isinstance(value, tuple):
1991 other_args = value
1992 other_kwargs = {}
1993 elif isinstance(value, str):
1994 other_name = value
1995 other_args, other_kwargs = (), {}
1996 else:
1997 other_args = ()
1998 other_kwargs = value
1999 else:
2000 # len 2
2001 # could be (name, args) or (name, kwargs) or (args, kwargs)
2002 first, second = other
2003 if isinstance(first, str):
2004 other_name = first
2005 if isinstance(second, tuple):
2006 other_args, other_kwargs = second, {}
2007 else:
2008 other_args, other_kwargs = (), second
2009 else:
2010 other_args, other_kwargs = first, second
2011
2012 if self_name and other_name != self_name:
2013 return False
2014
2015 # this order is important for ANY to work!
2016 return (other_args, other_kwargs) == (self_args, self_kwargs)
2017
2018
2019 def __ne__(self, other):
2020 return not self.__eq__(other)
2021
2022
2023 def __call__(self, *args, **kwargs):
2024 if self.name is None:
2025 return _Call(('', args, kwargs), name='()')
2026
2027 name = self.name + '()'
2028 return _Call((self.name, args, kwargs), name=name, parent=self)
2029
2030
2031 def __getattr__(self, attr):
2032 if self.name is None:
2033 return _Call(name=attr, from_kall=False)
2034 name = '%s.%s' % (self.name, attr)
2035 return _Call(name=name, parent=self, from_kall=False)
2036
2037
2038 def __repr__(self):
2039 if not self.from_kall:
2040 name = self.name or 'call'
2041 if name.startswith('()'):
2042 name = 'call%s' % name
2043 return name
2044
2045 if len(self) == 2:
2046 name = 'call'
2047 args, kwargs = self
2048 else:
2049 name, args, kwargs = self
2050 if not name:
2051 name = 'call'
2052 elif not name.startswith('()'):
2053 name = 'call.%s' % name
2054 else:
2055 name = 'call%s' % name
2056 return _format_call_signature(name, args, kwargs)
2057
2058
2059 def call_list(self):
2060 """For a call object that represents multiple calls, `call_list`
2061 returns a list of all the intermediate calls as well as the
2062 final call."""
2063 vals = []
2064 thing = self
2065 while thing is not None:
2066 if thing.from_kall:
2067 vals.append(thing)
2068 thing = thing.parent
2069 return _CallList(reversed(vals))
2070
2071
2072call = _Call(from_kall=False)
2073
2074
2075
2076def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2077 _name=None, **kwargs):
2078 """Create a mock object using another object as a spec. Attributes on the
2079 mock will use the corresponding attribute on the `spec` object as their
2080 spec.
2081
2082 Functions or methods being mocked will have their arguments checked
2083 to check that they are called with the correct signature.
2084
2085 If `spec_set` is True then attempting to set attributes that don't exist
2086 on the spec object will raise an `AttributeError`.
2087
2088 If a class is used as a spec then the return value of the mock (the
2089 instance of the class) will have the same spec. You can use a class as the
2090 spec for an instance object by passing `instance=True`. The returned mock
2091 will only be callable if instances of the mock are callable.
2092
2093 `create_autospec` also takes arbitrary keyword arguments that are passed to
2094 the constructor of the created mock."""
2095 if _is_list(spec):
2096 # can't pass a list instance to the mock constructor as it will be
2097 # interpreted as a list of strings
2098 spec = type(spec)
2099
2100 is_type = isinstance(spec, type)
2101
2102 _kwargs = {'spec': spec}
2103 if spec_set:
2104 _kwargs = {'spec_set': spec}
2105 elif spec is None:
2106 # None we mock with a normal mock without a spec
2107 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002108 if _kwargs and instance:
2109 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002110
2111 _kwargs.update(kwargs)
2112
2113 Klass = MagicMock
2114 if type(spec) in DescriptorTypes:
2115 # descriptors don't have a spec
2116 # because we don't know what type they return
2117 _kwargs = {}
2118 elif not _callable(spec):
2119 Klass = NonCallableMagicMock
2120 elif is_type and instance and not _instance_callable(spec):
2121 Klass = NonCallableMagicMock
2122
Kushal Das484f8a82014-04-16 01:05:50 +05302123 _name = _kwargs.pop('name', _name)
2124
Michael Foord345266a2012-03-14 12:24:34 -07002125 _new_name = _name
2126 if _parent is None:
2127 # for a top level object no _new_name should be set
2128 _new_name = ''
2129
2130 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2131 name=_name, **_kwargs)
2132
2133 if isinstance(spec, FunctionTypes):
2134 # should only happen at the top level because we don't
2135 # recurse for functions
2136 mock = _set_signature(mock, spec)
2137 else:
2138 _check_signature(spec, mock, is_type, instance)
2139
2140 if _parent is not None and not instance:
2141 _parent._mock_children[_name] = mock
2142
2143 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002144 mock.return_value = create_autospec(spec, spec_set, instance=True,
2145 _name='()', _parent=mock)
2146
2147 for entry in dir(spec):
2148 if _is_magic(entry):
2149 # MagicMock already does the useful magic methods for us
2150 continue
2151
Michael Foord345266a2012-03-14 12:24:34 -07002152 # XXXX do we need a better way of getting attributes without
2153 # triggering code execution (?) Probably not - we need the actual
2154 # object to mock it so we would rather trigger a property than mock
2155 # the property descriptor. Likewise we want to mock out dynamically
2156 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002157 # XXXX what about attributes that raise exceptions other than
2158 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002159 # we could be resilient against it, or catch and propagate the
2160 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002161 try:
2162 original = getattr(spec, entry)
2163 except AttributeError:
2164 continue
Michael Foord345266a2012-03-14 12:24:34 -07002165
2166 kwargs = {'spec': original}
2167 if spec_set:
2168 kwargs = {'spec_set': original}
2169
2170 if not isinstance(original, FunctionTypes):
2171 new = _SpecState(original, spec_set, mock, entry, instance)
2172 mock._mock_children[entry] = new
2173 else:
2174 parent = mock
2175 if isinstance(spec, FunctionTypes):
2176 parent = mock.mock
2177
Michael Foord345266a2012-03-14 12:24:34 -07002178 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002179 kwargs['_eat_self'] = skipfirst
2180 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2181 _new_parent=parent,
2182 **kwargs)
2183 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002184 _check_signature(original, new, skipfirst=skipfirst)
2185
2186 # so functions created with _set_signature become instance attributes,
2187 # *plus* their underlying mock exists in _mock_children of the parent
2188 # mock. Adding to _mock_children may be unnecessary where we are also
2189 # setting as an instance attribute?
2190 if isinstance(new, FunctionTypes):
2191 setattr(mock, entry, new)
2192
2193 return mock
2194
2195
2196def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002197 """
2198 Return whether we should skip the first argument on spec's `entry`
2199 attribute.
2200 """
Michael Foord345266a2012-03-14 12:24:34 -07002201 if not isinstance(spec, type):
2202 if entry in getattr(spec, '__dict__', {}):
2203 # instance attribute - shouldn't skip
2204 return False
Michael Foord345266a2012-03-14 12:24:34 -07002205 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002206
2207 for klass in spec.__mro__:
2208 result = klass.__dict__.get(entry, DEFAULT)
2209 if result is DEFAULT:
2210 continue
2211 if isinstance(result, (staticmethod, classmethod)):
2212 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002213 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2214 # Normal method => skip if looked up on type
2215 # (if looked up on instance, self is already skipped)
2216 return is_type
2217 else:
2218 return False
Michael Foord345266a2012-03-14 12:24:34 -07002219
2220 # shouldn't get here unless function is a dynamically provided attribute
2221 # XXXX untested behaviour
2222 return is_type
2223
2224
2225def _get_class(obj):
2226 try:
2227 return obj.__class__
2228 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002229 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002230 return type(obj)
2231
2232
2233class _SpecState(object):
2234
2235 def __init__(self, spec, spec_set=False, parent=None,
2236 name=None, ids=None, instance=False):
2237 self.spec = spec
2238 self.ids = ids
2239 self.spec_set = spec_set
2240 self.parent = parent
2241 self.instance = instance
2242 self.name = name
2243
2244
2245FunctionTypes = (
2246 # python function
2247 type(create_autospec),
2248 # instance method
2249 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002250)
2251
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002252MethodWrapperTypes = (
2253 type(ANY.__eq__.__get__),
2254)
2255
Michael Foord345266a2012-03-14 12:24:34 -07002256
Michael Foorda74561a2012-03-25 19:03:13 +01002257file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002258
Michael Foord04cbe0c2013-03-19 17:22:51 -07002259def _iterate_read_data(read_data):
2260 # Helper for mock_open:
2261 # Retrieve lines from read_data via a generator so that separate calls to
2262 # readline, read, and readlines are properly interleaved
2263 data_as_list = ['{}\n'.format(l) for l in read_data.split('\n')]
2264
2265 if data_as_list[-1] == '\n':
2266 # If the last line ended in a newline, the list comprehension will have an
2267 # extra entry that's just a newline. Remove this.
2268 data_as_list = data_as_list[:-1]
2269 else:
2270 # If there wasn't an extra newline by itself, then the file being
2271 # emulated doesn't have a newline to end the last line remove the
2272 # newline that our naive format() added
2273 data_as_list[-1] = data_as_list[-1][:-1]
2274
2275 for line in data_as_list:
2276 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002277
2278def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002279 """
2280 A helper function to create a mock to replace the use of `open`. It works
2281 for `open` called directly or used as a context manager.
2282
2283 The `mock` argument is the mock object to configure. If `None` (the
2284 default) then a `MagicMock` will be created for you, with the API limited
2285 to methods or attributes available on standard file handles.
2286
Michael Foord04cbe0c2013-03-19 17:22:51 -07002287 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2288 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002289 """
Michael Foord04cbe0c2013-03-19 17:22:51 -07002290 def _readlines_side_effect(*args, **kwargs):
2291 if handle.readlines.return_value is not None:
2292 return handle.readlines.return_value
2293 return list(_data)
2294
2295 def _read_side_effect(*args, **kwargs):
2296 if handle.read.return_value is not None:
2297 return handle.read.return_value
2298 return ''.join(_data)
2299
2300 def _readline_side_effect():
2301 if handle.readline.return_value is not None:
2302 while True:
2303 yield handle.readline.return_value
2304 for line in _data:
2305 yield line
2306
2307
Michael Foorda74561a2012-03-25 19:03:13 +01002308 global file_spec
2309 if file_spec is None:
2310 import _io
2311 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2312
Michael Foord345266a2012-03-14 12:24:34 -07002313 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002314 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002315
2316 handle = MagicMock(spec=file_spec)
Michael Foord345266a2012-03-14 12:24:34 -07002317 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002318
2319 _data = _iterate_read_data(read_data)
2320
2321 handle.write.return_value = None
2322 handle.read.return_value = None
2323 handle.readline.return_value = None
2324 handle.readlines.return_value = None
2325
2326 handle.read.side_effect = _read_side_effect
2327 handle.readline.side_effect = _readline_side_effect()
2328 handle.readlines.side_effect = _readlines_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002329
2330 mock.return_value = handle
2331 return mock
2332
2333
2334class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002335 """
2336 A mock intended to be used as a property, or other descriptor, on a class.
2337 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2338 a return value when it is fetched.
2339
2340 Fetching a `PropertyMock` instance from an object calls the mock, with
2341 no args. Setting it calls the mock with the value being set.
2342 """
Michael Foordc2870622012-04-13 16:57:22 +01002343 def _get_child_mock(self, **kwargs):
2344 return MagicMock(**kwargs)
2345
Michael Foord345266a2012-03-14 12:24:34 -07002346 def __get__(self, obj, obj_type):
2347 return self()
2348 def __set__(self, obj, val):
2349 self(val)