blob: 3b7c157c7d475e819e4eb883864f842503f6e5a4 [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
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200278_allowed_names = {
279 'return_value', '_mock_return_value', 'side_effect',
280 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
281 '_mock_name', '_mock_new_name'
282}
Michael Foord345266a2012-03-14 12:24:34 -0700283
284
285def _delegating_property(name):
286 _allowed_names.add(name)
287 _the_name = '_mock_' + name
288 def _get(self, name=name, _the_name=_the_name):
289 sig = self._mock_delegate
290 if sig is None:
291 return getattr(self, _the_name)
292 return getattr(sig, name)
293 def _set(self, value, name=name, _the_name=_the_name):
294 sig = self._mock_delegate
295 if sig is None:
296 self.__dict__[_the_name] = value
297 else:
298 setattr(sig, name, value)
299
300 return property(_get, _set)
301
302
303
304class _CallList(list):
305
306 def __contains__(self, value):
307 if not isinstance(value, list):
308 return list.__contains__(self, value)
309 len_value = len(value)
310 len_self = len(self)
311 if len_value > len_self:
312 return False
313
314 for i in range(0, len_self - len_value + 1):
315 sub_list = self[i:i+len_value]
316 if sub_list == value:
317 return True
318 return False
319
320 def __repr__(self):
321 return pprint.pformat(list(self))
322
323
324def _check_and_set_parent(parent, value, name, new_name):
325 if not _is_instance_mock(value):
326 return False
327 if ((value._mock_name or value._mock_new_name) or
328 (value._mock_parent is not None) or
329 (value._mock_new_parent is not None)):
330 return False
331
332 _parent = parent
333 while _parent is not None:
334 # setting a mock (value) as a child or return value of itself
335 # should not modify the mock
336 if _parent is value:
337 return False
338 _parent = _parent._mock_new_parent
339
340 if new_name:
341 value._mock_new_parent = parent
342 value._mock_new_name = new_name
343 if name:
344 value._mock_parent = parent
345 value._mock_name = name
346 return True
347
Michael Foord01bafdc2014-04-14 16:09:42 -0400348# Internal class to identify if we wrapped an iterator object or not.
349class _MockIter(object):
350 def __init__(self, obj):
351 self.obj = iter(obj)
352 def __iter__(self):
353 return self
354 def __next__(self):
355 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700356
357class Base(object):
358 _mock_return_value = DEFAULT
359 _mock_side_effect = None
360 def __init__(self, *args, **kwargs):
361 pass
362
363
364
365class NonCallableMock(Base):
366 """A non-callable version of `Mock`"""
367
368 def __new__(cls, *args, **kw):
369 # every instance has its own class
370 # so we can create magic methods on the
371 # class without stomping on other mocks
372 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
373 instance = object.__new__(new)
374 return instance
375
376
377 def __init__(
378 self, spec=None, wraps=None, name=None, spec_set=None,
379 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530380 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700381 ):
382 if _new_parent is None:
383 _new_parent = parent
384
385 __dict__ = self.__dict__
386 __dict__['_mock_parent'] = parent
387 __dict__['_mock_name'] = name
388 __dict__['_mock_new_name'] = _new_name
389 __dict__['_mock_new_parent'] = _new_parent
390
391 if spec_set is not None:
392 spec = spec_set
393 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100394 if _eat_self is None:
395 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700396
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100397 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700398
399 __dict__['_mock_children'] = {}
400 __dict__['_mock_wraps'] = wraps
401 __dict__['_mock_delegate'] = None
402
403 __dict__['_mock_called'] = False
404 __dict__['_mock_call_args'] = None
405 __dict__['_mock_call_count'] = 0
406 __dict__['_mock_call_args_list'] = _CallList()
407 __dict__['_mock_mock_calls'] = _CallList()
408
409 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530410 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700411
412 if kwargs:
413 self.configure_mock(**kwargs)
414
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000415 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700416 spec, wraps, name, spec_set, parent,
417 _spec_state
418 )
419
420
421 def attach_mock(self, mock, attribute):
422 """
423 Attach a mock as an attribute of this one, replacing its name and
424 parent. Calls to the attached mock will be recorded in the
425 `method_calls` and `mock_calls` attributes of this one."""
426 mock._mock_parent = None
427 mock._mock_new_parent = None
428 mock._mock_name = ''
429 mock._mock_new_name = None
430
431 setattr(self, attribute, mock)
432
433
434 def mock_add_spec(self, spec, spec_set=False):
435 """Add a spec to a mock. `spec` can either be an object or a
436 list of strings. Only attributes on the `spec` can be fetched as
437 attributes from the mock.
438
439 If `spec_set` is True then only attributes on the spec can be set."""
440 self._mock_add_spec(spec, spec_set)
441
442
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100443 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
444 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700445 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100446 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700447
448 if spec is not None and not _is_list(spec):
449 if isinstance(spec, type):
450 _spec_class = spec
451 else:
452 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100453 res = _get_signature_object(spec,
454 _spec_as_instance, _eat_self)
455 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700456
457 spec = dir(spec)
458
459 __dict__ = self.__dict__
460 __dict__['_spec_class'] = _spec_class
461 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100462 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700463 __dict__['_mock_methods'] = spec
464
465
466 def __get_return_value(self):
467 ret = self._mock_return_value
468 if self._mock_delegate is not None:
469 ret = self._mock_delegate.return_value
470
471 if ret is DEFAULT:
472 ret = self._get_child_mock(
473 _new_parent=self, _new_name='()'
474 )
475 self.return_value = ret
476 return ret
477
478
479 def __set_return_value(self, value):
480 if self._mock_delegate is not None:
481 self._mock_delegate.return_value = value
482 else:
483 self._mock_return_value = value
484 _check_and_set_parent(self, value, None, '()')
485
486 __return_value_doc = "The value to be returned when the mock is called."
487 return_value = property(__get_return_value, __set_return_value,
488 __return_value_doc)
489
490
491 @property
492 def __class__(self):
493 if self._spec_class is None:
494 return type(self)
495 return self._spec_class
496
497 called = _delegating_property('called')
498 call_count = _delegating_property('call_count')
499 call_args = _delegating_property('call_args')
500 call_args_list = _delegating_property('call_args_list')
501 mock_calls = _delegating_property('mock_calls')
502
503
504 def __get_side_effect(self):
505 delegated = self._mock_delegate
506 if delegated is None:
507 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400508 sf = delegated.side_effect
509 if sf is not None and not callable(sf) and not isinstance(sf, _MockIter):
510 sf = _MockIter(sf)
511 delegated.side_effect = sf
512 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700513
514 def __set_side_effect(self, value):
515 value = _try_iter(value)
516 delegated = self._mock_delegate
517 if delegated is None:
518 self._mock_side_effect = value
519 else:
520 delegated.side_effect = value
521
522 side_effect = property(__get_side_effect, __set_side_effect)
523
524
525 def reset_mock(self):
526 "Restore the mock object to its initial state."
527 self.called = False
528 self.call_args = None
529 self.call_count = 0
530 self.mock_calls = _CallList()
531 self.call_args_list = _CallList()
532 self.method_calls = _CallList()
533
534 for child in self._mock_children.values():
Michael Foord75963642012-06-09 17:31:59 +0100535 if isinstance(child, _SpecState):
536 continue
Michael Foord345266a2012-03-14 12:24:34 -0700537 child.reset_mock()
538
539 ret = self._mock_return_value
540 if _is_instance_mock(ret) and ret is not self:
541 ret.reset_mock()
542
543
544 def configure_mock(self, **kwargs):
545 """Set attributes on the mock through keyword arguments.
546
547 Attributes plus return values and side effects can be set on child
548 mocks using standard dot notation and unpacking a dictionary in the
549 method call:
550
551 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
552 >>> mock.configure_mock(**attrs)"""
553 for arg, val in sorted(kwargs.items(),
554 # we sort on the number of dots so that
555 # attributes are set before we set attributes on
556 # attributes
557 key=lambda entry: entry[0].count('.')):
558 args = arg.split('.')
559 final = args.pop()
560 obj = self
561 for entry in args:
562 obj = getattr(obj, entry)
563 setattr(obj, final, val)
564
565
566 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530567 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700568 raise AttributeError(name)
569 elif self._mock_methods is not None:
570 if name not in self._mock_methods or name in _all_magics:
571 raise AttributeError("Mock object has no attribute %r" % name)
572 elif _is_magic(name):
573 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530574 if not self._mock_unsafe:
575 if name.startswith(('assert', 'assret')):
576 raise AttributeError(name)
Michael Foord345266a2012-03-14 12:24:34 -0700577
578 result = self._mock_children.get(name)
579 if result is _deleted:
580 raise AttributeError(name)
581 elif result is None:
582 wraps = None
583 if self._mock_wraps is not None:
584 # XXXX should we get the attribute without triggering code
585 # execution?
586 wraps = getattr(self._mock_wraps, name)
587
588 result = self._get_child_mock(
589 parent=self, name=name, wraps=wraps, _new_name=name,
590 _new_parent=self
591 )
592 self._mock_children[name] = result
593
594 elif isinstance(result, _SpecState):
595 result = create_autospec(
596 result.spec, result.spec_set, result.instance,
597 result.parent, result.name
598 )
599 self._mock_children[name] = result
600
601 return result
602
603
604 def __repr__(self):
605 _name_list = [self._mock_new_name]
606 _parent = self._mock_new_parent
607 last = self
608
609 dot = '.'
610 if _name_list == ['()']:
611 dot = ''
612 seen = set()
613 while _parent is not None:
614 last = _parent
615
616 _name_list.append(_parent._mock_new_name + dot)
617 dot = '.'
618 if _parent._mock_new_name == '()':
619 dot = ''
620
621 _parent = _parent._mock_new_parent
622
623 # use ids here so as not to call __hash__ on the mocks
624 if id(_parent) in seen:
625 break
626 seen.add(id(_parent))
627
628 _name_list = list(reversed(_name_list))
629 _first = last._mock_name or 'mock'
630 if len(_name_list) > 1:
631 if _name_list[1] not in ('()', '().'):
632 _first += '.'
633 _name_list[0] = _first
634 name = ''.join(_name_list)
635
636 name_string = ''
637 if name not in ('mock', 'mock.'):
638 name_string = ' name=%r' % name
639
640 spec_string = ''
641 if self._spec_class is not None:
642 spec_string = ' spec=%r'
643 if self._spec_set:
644 spec_string = ' spec_set=%r'
645 spec_string = spec_string % self._spec_class.__name__
646 return "<%s%s%s id='%s'>" % (
647 type(self).__name__,
648 name_string,
649 spec_string,
650 id(self)
651 )
652
653
654 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700655 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100656 if not FILTER_DIR:
657 return object.__dir__(self)
658
Michael Foord345266a2012-03-14 12:24:34 -0700659 extras = self._mock_methods or []
660 from_type = dir(type(self))
661 from_dict = list(self.__dict__)
662
Michael Foord313f85f2012-03-25 18:16:07 +0100663 from_type = [e for e in from_type if not e.startswith('_')]
664 from_dict = [e for e in from_dict if not e.startswith('_') or
665 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700666 return sorted(set(extras + from_type + from_dict +
667 list(self._mock_children)))
668
669
670 def __setattr__(self, name, value):
671 if name in _allowed_names:
672 # property setters go through here
673 return object.__setattr__(self, name, value)
674 elif (self._spec_set and self._mock_methods is not None and
675 name not in self._mock_methods and
676 name not in self.__dict__):
677 raise AttributeError("Mock object has no attribute '%s'" % name)
678 elif name in _unsupported_magics:
679 msg = 'Attempting to set unsupported magic method %r.' % name
680 raise AttributeError(msg)
681 elif name in _all_magics:
682 if self._mock_methods is not None and name not in self._mock_methods:
683 raise AttributeError("Mock object has no attribute '%s'" % name)
684
685 if not _is_instance_mock(value):
686 setattr(type(self), name, _get_method(name, value))
687 original = value
688 value = lambda *args, **kw: original(self, *args, **kw)
689 else:
690 # only set _new_name and not name so that mock_calls is tracked
691 # but not method calls
692 _check_and_set_parent(self, value, None, name)
693 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100694 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700695 elif name == '__class__':
696 self._spec_class = value
697 return
698 else:
699 if _check_and_set_parent(self, value, name, name):
700 self._mock_children[name] = value
701 return object.__setattr__(self, name, value)
702
703
704 def __delattr__(self, name):
705 if name in _all_magics and name in type(self).__dict__:
706 delattr(type(self), name)
707 if name not in self.__dict__:
708 # for magic methods that are still MagicProxy objects and
709 # not set on the instance itself
710 return
711
712 if name in self.__dict__:
713 object.__delattr__(self, name)
714
715 obj = self._mock_children.get(name, _missing)
716 if obj is _deleted:
717 raise AttributeError(name)
718 if obj is not _missing:
719 del self._mock_children[name]
720 self._mock_children[name] = _deleted
721
722
Michael Foord345266a2012-03-14 12:24:34 -0700723 def _format_mock_call_signature(self, args, kwargs):
724 name = self._mock_name or 'mock'
725 return _format_call_signature(name, args, kwargs)
726
727
728 def _format_mock_failure_message(self, args, kwargs):
729 message = 'Expected call: %s\nActual call: %s'
730 expected_string = self._format_mock_call_signature(args, kwargs)
731 call_args = self.call_args
732 if len(call_args) == 3:
733 call_args = call_args[1:]
734 actual_string = self._format_mock_call_signature(*call_args)
735 return message % (expected_string, actual_string)
736
737
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100738 def _call_matcher(self, _call):
739 """
740 Given a call (or simply a (args, kwargs) tuple), return a
741 comparison key suitable for matching with other calls.
742 This is a best effort method which relies on the spec's signature,
743 if available, or falls back on the arguments themselves.
744 """
745 sig = self._spec_signature
746 if sig is not None:
747 if len(_call) == 2:
748 name = ''
749 args, kwargs = _call
750 else:
751 name, args, kwargs = _call
752 try:
753 return name, sig.bind(*args, **kwargs)
754 except TypeError as e:
755 return e.with_traceback(None)
756 else:
757 return _call
758
Kushal Das68290f42014-04-17 01:54:07 +0530759 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530760 """assert that the mock was never called.
761 """
762 self = _mock_self
763 if self.call_count != 0:
764 msg = ("Expected '%s' to not have been called. Called %s times." %
765 (self._mock_name or 'mock', self.call_count))
766 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100767
Michael Foord345266a2012-03-14 12:24:34 -0700768 def assert_called_with(_mock_self, *args, **kwargs):
769 """assert that the mock was called with the specified arguments.
770
771 Raises an AssertionError if the args and keyword args passed in are
772 different to the last call to the mock."""
773 self = _mock_self
774 if self.call_args is None:
775 expected = self._format_mock_call_signature(args, kwargs)
776 raise AssertionError('Expected call: %s\nNot called' % (expected,))
777
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100778 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700779 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100780 return msg
781 expected = self._call_matcher((args, kwargs))
782 actual = self._call_matcher(self.call_args)
783 if expected != actual:
784 cause = expected if isinstance(expected, Exception) else None
785 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700786
787
788 def assert_called_once_with(_mock_self, *args, **kwargs):
789 """assert that the mock was called exactly once and with the specified
790 arguments."""
791 self = _mock_self
792 if not self.call_count == 1:
Michael Foord28d591c2012-09-28 16:15:22 +0100793 msg = ("Expected '%s' to be called once. Called %s times." %
794 (self._mock_name or 'mock', self.call_count))
Michael Foord345266a2012-03-14 12:24:34 -0700795 raise AssertionError(msg)
796 return self.assert_called_with(*args, **kwargs)
797
798
799 def assert_has_calls(self, calls, any_order=False):
800 """assert the mock has been called with the specified calls.
801 The `mock_calls` list is checked for the calls.
802
803 If `any_order` is False (the default) then the calls must be
804 sequential. There can be extra calls before or after the
805 specified calls.
806
807 If `any_order` is True then the calls can be in any order, but
808 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100809 expected = [self._call_matcher(c) for c in calls]
810 cause = expected if isinstance(expected, Exception) else None
811 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700812 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100813 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700814 raise AssertionError(
815 'Calls not found.\nExpected: %r\n'
816 'Actual: %r' % (calls, self.mock_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100817 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700818 return
819
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100820 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700821
822 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100823 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700824 try:
825 all_calls.remove(kall)
826 except ValueError:
827 not_found.append(kall)
828 if not_found:
829 raise AssertionError(
830 '%r not all found in call list' % (tuple(not_found),)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100831 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700832
833
834 def assert_any_call(self, *args, **kwargs):
835 """assert the mock has been called with the specified arguments.
836
837 The assert passes if the mock has *ever* been called, unlike
838 `assert_called_with` and `assert_called_once_with` that only pass if
839 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100840 expected = self._call_matcher((args, kwargs))
841 actual = [self._call_matcher(c) for c in self.call_args_list]
842 if expected not in actual:
843 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700844 expected_string = self._format_mock_call_signature(args, kwargs)
845 raise AssertionError(
846 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100847 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700848
849
850 def _get_child_mock(self, **kw):
851 """Create the child mocks for attributes and return value.
852 By default child mocks will be the same type as the parent.
853 Subclasses of Mock may want to override this to customize the way
854 child mocks are made.
855
856 For non-callable mocks the callable variant will be used (rather than
857 any custom subclass)."""
858 _type = type(self)
859 if not issubclass(_type, CallableMixin):
860 if issubclass(_type, NonCallableMagicMock):
861 klass = MagicMock
862 elif issubclass(_type, NonCallableMock) :
863 klass = Mock
864 else:
865 klass = _type.__mro__[1]
866 return klass(**kw)
867
868
869
870def _try_iter(obj):
871 if obj is None:
872 return obj
873 if _is_exception(obj):
874 return obj
875 if _callable(obj):
876 return obj
877 try:
878 return iter(obj)
879 except TypeError:
880 # XXXX backwards compatibility
881 # but this will blow up on first call - so maybe we should fail early?
882 return obj
883
884
885
886class CallableMixin(Base):
887
888 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
889 wraps=None, name=None, spec_set=None, parent=None,
890 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
891 self.__dict__['_mock_return_value'] = return_value
892
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000893 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700894 spec, wraps, name, spec_set, parent,
895 _spec_state, _new_name, _new_parent, **kwargs
896 )
897
898 self.side_effect = side_effect
899
900
901 def _mock_check_sig(self, *args, **kwargs):
902 # stub method that can be replaced with one with a specific signature
903 pass
904
905
906 def __call__(_mock_self, *args, **kwargs):
907 # can't use self in-case a function / method we are mocking uses self
908 # in the signature
909 _mock_self._mock_check_sig(*args, **kwargs)
910 return _mock_self._mock_call(*args, **kwargs)
911
912
913 def _mock_call(_mock_self, *args, **kwargs):
914 self = _mock_self
915 self.called = True
916 self.call_count += 1
Michael Foord345266a2012-03-14 12:24:34 -0700917 _new_name = self._mock_new_name
918 _new_parent = self._mock_new_parent
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100919
920 _call = _Call((args, kwargs), two=True)
921 self.call_args = _call
922 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700923 self.mock_calls.append(_Call(('', args, kwargs)))
924
925 seen = set()
926 skip_next_dot = _new_name == '()'
927 do_method_calls = self._mock_parent is not None
928 name = self._mock_name
929 while _new_parent is not None:
930 this_mock_call = _Call((_new_name, args, kwargs))
931 if _new_parent._mock_new_name:
932 dot = '.'
933 if skip_next_dot:
934 dot = ''
935
936 skip_next_dot = False
937 if _new_parent._mock_new_name == '()':
938 skip_next_dot = True
939
940 _new_name = _new_parent._mock_new_name + dot + _new_name
941
942 if do_method_calls:
943 if _new_name == name:
944 this_method_call = this_mock_call
945 else:
946 this_method_call = _Call((name, args, kwargs))
947 _new_parent.method_calls.append(this_method_call)
948
949 do_method_calls = _new_parent._mock_parent is not None
950 if do_method_calls:
951 name = _new_parent._mock_name + '.' + name
952
953 _new_parent.mock_calls.append(this_mock_call)
954 _new_parent = _new_parent._mock_new_parent
955
956 # use ids here so as not to call __hash__ on the mocks
957 _new_parent_id = id(_new_parent)
958 if _new_parent_id in seen:
959 break
960 seen.add(_new_parent_id)
961
962 ret_val = DEFAULT
963 effect = self.side_effect
964 if effect is not None:
965 if _is_exception(effect):
966 raise effect
967
968 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +0100969 result = next(effect)
970 if _is_exception(result):
971 raise result
Andrew Svetlov8b2cd752013-04-07 16:42:24 +0300972 if result is DEFAULT:
973 result = self.return_value
Michael Foord2cd48732012-04-21 15:52:11 +0100974 return result
Michael Foord345266a2012-03-14 12:24:34 -0700975
976 ret_val = effect(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700977
978 if (self._mock_wraps is not None and
979 self._mock_return_value is DEFAULT):
980 return self._mock_wraps(*args, **kwargs)
981 if ret_val is DEFAULT:
982 ret_val = self.return_value
983 return ret_val
984
985
986
987class Mock(CallableMixin, NonCallableMock):
988 """
989 Create a new `Mock` object. `Mock` takes several optional arguments
990 that specify the behaviour of the Mock object:
991
992 * `spec`: This can be either a list of strings or an existing object (a
993 class or instance) that acts as the specification for the mock object. If
994 you pass in an object then a list of strings is formed by calling dir on
995 the object (excluding unsupported magic attributes and methods). Accessing
996 any attribute not in this list will raise an `AttributeError`.
997
998 If `spec` is an object (rather than a list of strings) then
999 `mock.__class__` returns the class of the spec object. This allows mocks
1000 to pass `isinstance` tests.
1001
1002 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1003 or get an attribute on the mock that isn't on the object passed as
1004 `spec_set` will raise an `AttributeError`.
1005
1006 * `side_effect`: A function to be called whenever the Mock is called. See
1007 the `side_effect` attribute. Useful for raising exceptions or
1008 dynamically changing return values. The function is called with the same
1009 arguments as the mock, and unless it returns `DEFAULT`, the return
1010 value of this function is used as the return value.
1011
Michael Foord2cd48732012-04-21 15:52:11 +01001012 If `side_effect` is an iterable then each call to the mock will return
1013 the next value from the iterable. If any of the members of the iterable
1014 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001015
Michael Foord345266a2012-03-14 12:24:34 -07001016 * `return_value`: The value returned when the mock is called. By default
1017 this is a new Mock (created on first access). See the
1018 `return_value` attribute.
1019
Michael Foord0682a0c2012-04-13 20:51:20 +01001020 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1021 calling the Mock will pass the call through to the wrapped object
1022 (returning the real result). Attribute access on the mock will return a
1023 Mock object that wraps the corresponding attribute of the wrapped object
1024 (so attempting to access an attribute that doesn't exist will raise an
1025 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001026
1027 If the mock has an explicit `return_value` set then calls are not passed
1028 to the wrapped object and the `return_value` is returned instead.
1029
1030 * `name`: If the mock has a name then it will be used in the repr of the
1031 mock. This can be useful for debugging. The name is propagated to child
1032 mocks.
1033
1034 Mocks can also be called with arbitrary keyword arguments. These will be
1035 used to set attributes on the mock after it is created.
1036 """
1037
1038
1039
1040def _dot_lookup(thing, comp, import_path):
1041 try:
1042 return getattr(thing, comp)
1043 except AttributeError:
1044 __import__(import_path)
1045 return getattr(thing, comp)
1046
1047
1048def _importer(target):
1049 components = target.split('.')
1050 import_path = components.pop(0)
1051 thing = __import__(import_path)
1052
1053 for comp in components:
1054 import_path += ".%s" % comp
1055 thing = _dot_lookup(thing, comp, import_path)
1056 return thing
1057
1058
1059def _is_started(patcher):
1060 # XXXX horrible
1061 return hasattr(patcher, 'is_local')
1062
1063
1064class _patch(object):
1065
1066 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001067 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001068
1069 def __init__(
1070 self, getter, attribute, new, spec, create,
1071 spec_set, autospec, new_callable, kwargs
1072 ):
1073 if new_callable is not None:
1074 if new is not DEFAULT:
1075 raise ValueError(
1076 "Cannot use 'new' and 'new_callable' together"
1077 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001078 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001079 raise ValueError(
1080 "Cannot use 'autospec' and 'new_callable' together"
1081 )
1082
1083 self.getter = getter
1084 self.attribute = attribute
1085 self.new = new
1086 self.new_callable = new_callable
1087 self.spec = spec
1088 self.create = create
1089 self.has_local = False
1090 self.spec_set = spec_set
1091 self.autospec = autospec
1092 self.kwargs = kwargs
1093 self.additional_patchers = []
1094
1095
1096 def copy(self):
1097 patcher = _patch(
1098 self.getter, self.attribute, self.new, self.spec,
1099 self.create, self.spec_set,
1100 self.autospec, self.new_callable, self.kwargs
1101 )
1102 patcher.attribute_name = self.attribute_name
1103 patcher.additional_patchers = [
1104 p.copy() for p in self.additional_patchers
1105 ]
1106 return patcher
1107
1108
1109 def __call__(self, func):
1110 if isinstance(func, type):
1111 return self.decorate_class(func)
1112 return self.decorate_callable(func)
1113
1114
1115 def decorate_class(self, klass):
1116 for attr in dir(klass):
1117 if not attr.startswith(patch.TEST_PREFIX):
1118 continue
1119
1120 attr_value = getattr(klass, attr)
1121 if not hasattr(attr_value, "__call__"):
1122 continue
1123
1124 patcher = self.copy()
1125 setattr(klass, attr, patcher(attr_value))
1126 return klass
1127
1128
1129 def decorate_callable(self, func):
1130 if hasattr(func, 'patchings'):
1131 func.patchings.append(self)
1132 return func
1133
1134 @wraps(func)
1135 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001136 extra_args = []
1137 entered_patchers = []
1138
Michael Foord50a8c0e2012-03-25 18:57:58 +01001139 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001140 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001141 for patching in patched.patchings:
1142 arg = patching.__enter__()
1143 entered_patchers.append(patching)
1144 if patching.attribute_name is not None:
1145 keywargs.update(arg)
1146 elif patching.new is DEFAULT:
1147 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001148
Michael Foordd7c65e22012-03-14 14:56:54 -07001149 args += tuple(extra_args)
1150 return func(*args, **keywargs)
1151 except:
1152 if (patching not in entered_patchers and
1153 _is_started(patching)):
1154 # the patcher may have been started, but an exception
1155 # raised whilst entering one of its additional_patchers
1156 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001157 # Pass the exception to __exit__
1158 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001159 # re-raise the exception
1160 raise
Michael Foord345266a2012-03-14 12:24:34 -07001161 finally:
1162 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001163 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001164
1165 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001166 return patched
1167
1168
1169 def get_original(self):
1170 target = self.getter()
1171 name = self.attribute
1172
1173 original = DEFAULT
1174 local = False
1175
1176 try:
1177 original = target.__dict__[name]
1178 except (AttributeError, KeyError):
1179 original = getattr(target, name, DEFAULT)
1180 else:
1181 local = True
1182
Michael Foordfddcfa22014-04-14 16:25:20 -04001183 if name in _builtins and isinstance(target, ModuleType):
1184 self.create = True
1185
Michael Foord345266a2012-03-14 12:24:34 -07001186 if not self.create and original is DEFAULT:
1187 raise AttributeError(
1188 "%s does not have the attribute %r" % (target, name)
1189 )
1190 return original, local
1191
1192
1193 def __enter__(self):
1194 """Perform the patch."""
1195 new, spec, spec_set = self.new, self.spec, self.spec_set
1196 autospec, kwargs = self.autospec, self.kwargs
1197 new_callable = self.new_callable
1198 self.target = self.getter()
1199
Michael Foord50a8c0e2012-03-25 18:57:58 +01001200 # normalise False to None
1201 if spec is False:
1202 spec = None
1203 if spec_set is False:
1204 spec_set = None
1205 if autospec is False:
1206 autospec = None
1207
1208 if spec is not None and autospec is not None:
1209 raise TypeError("Can't specify spec and autospec")
1210 if ((spec is not None or autospec is not None) and
1211 spec_set not in (True, None)):
1212 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1213
Michael Foord345266a2012-03-14 12:24:34 -07001214 original, local = self.get_original()
1215
Michael Foord50a8c0e2012-03-25 18:57:58 +01001216 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001217 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001218 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001219 # set spec to the object we are replacing
1220 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001221 if spec_set is True:
1222 spec_set = original
1223 spec = None
1224 elif spec is not None:
1225 if spec_set is True:
1226 spec_set = spec
1227 spec = None
1228 elif spec_set is True:
1229 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001230
Michael Foord50a8c0e2012-03-25 18:57:58 +01001231 if spec is not None or spec_set is not None:
1232 if original is DEFAULT:
1233 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001234 if isinstance(original, type):
1235 # If we're patching out a class and there is a spec
1236 inherit = True
1237
1238 Klass = MagicMock
1239 _kwargs = {}
1240 if new_callable is not None:
1241 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001242 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001243 this_spec = spec
1244 if spec_set is not None:
1245 this_spec = spec_set
1246 if _is_list(this_spec):
1247 not_callable = '__call__' not in this_spec
1248 else:
1249 not_callable = not callable(this_spec)
1250 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001251 Klass = NonCallableMagicMock
1252
1253 if spec is not None:
1254 _kwargs['spec'] = spec
1255 if spec_set is not None:
1256 _kwargs['spec_set'] = spec_set
1257
1258 # add a name to mocks
1259 if (isinstance(Klass, type) and
1260 issubclass(Klass, NonCallableMock) and self.attribute):
1261 _kwargs['name'] = self.attribute
1262
1263 _kwargs.update(kwargs)
1264 new = Klass(**_kwargs)
1265
1266 if inherit and _is_instance_mock(new):
1267 # we can only tell if the instance should be callable if the
1268 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001269 this_spec = spec
1270 if spec_set is not None:
1271 this_spec = spec_set
1272 if (not _is_list(this_spec) and not
1273 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001274 Klass = NonCallableMagicMock
1275
1276 _kwargs.pop('name')
1277 new.return_value = Klass(_new_parent=new, _new_name='()',
1278 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001279 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001280 # spec is ignored, new *must* be default, spec_set is treated
1281 # as a boolean. Should we check spec is not None and that spec_set
1282 # is a bool?
1283 if new is not DEFAULT:
1284 raise TypeError(
1285 "autospec creates the mock for you. Can't specify "
1286 "autospec and new."
1287 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001288 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001289 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001290 spec_set = bool(spec_set)
1291 if autospec is True:
1292 autospec = original
1293
1294 new = create_autospec(autospec, spec_set=spec_set,
1295 _name=self.attribute, **kwargs)
1296 elif kwargs:
1297 # can't set keyword args when we aren't creating the mock
1298 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1299 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1300
1301 new_attr = new
1302
1303 self.temp_original = original
1304 self.is_local = local
1305 setattr(self.target, self.attribute, new_attr)
1306 if self.attribute_name is not None:
1307 extra_args = {}
1308 if self.new is DEFAULT:
1309 extra_args[self.attribute_name] = new
1310 for patching in self.additional_patchers:
1311 arg = patching.__enter__()
1312 if patching.new is DEFAULT:
1313 extra_args.update(arg)
1314 return extra_args
1315
1316 return new
1317
1318
Michael Foord50a8c0e2012-03-25 18:57:58 +01001319 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001320 """Undo the patch."""
1321 if not _is_started(self):
1322 raise RuntimeError('stop called on unstarted patcher')
1323
1324 if self.is_local and self.temp_original is not DEFAULT:
1325 setattr(self.target, self.attribute, self.temp_original)
1326 else:
1327 delattr(self.target, self.attribute)
1328 if not self.create and not hasattr(self.target, self.attribute):
1329 # needed for proxy objects like django settings
1330 setattr(self.target, self.attribute, self.temp_original)
1331
1332 del self.temp_original
1333 del self.is_local
1334 del self.target
1335 for patcher in reversed(self.additional_patchers):
1336 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001337 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001338
Michael Foordf7c41582012-06-10 20:36:32 +01001339
1340 def start(self):
1341 """Activate a patch, returning any created mock."""
1342 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001343 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001344 return result
1345
1346
1347 def stop(self):
1348 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001349 try:
1350 self._active_patches.remove(self)
1351 except ValueError:
1352 # If the patch hasn't been started this will fail
1353 pass
1354
Michael Foordf7c41582012-06-10 20:36:32 +01001355 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001356
1357
1358
1359def _get_target(target):
1360 try:
1361 target, attribute = target.rsplit('.', 1)
1362 except (TypeError, ValueError):
1363 raise TypeError("Need a valid target to patch. You supplied: %r" %
1364 (target,))
1365 getter = lambda: _importer(target)
1366 return getter, attribute
1367
1368
1369def _patch_object(
1370 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001371 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001372 new_callable=None, **kwargs
1373 ):
1374 """
Michael Foord345266a2012-03-14 12:24:34 -07001375 patch the named member (`attribute`) on an object (`target`) with a mock
1376 object.
1377
1378 `patch.object` can be used as a decorator, class decorator or a context
1379 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1380 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1381 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1382 the mock object it creates.
1383
1384 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1385 for choosing which methods to wrap.
1386 """
1387 getter = lambda: target
1388 return _patch(
1389 getter, attribute, new, spec, create,
1390 spec_set, autospec, new_callable, kwargs
1391 )
1392
1393
Michael Foord50a8c0e2012-03-25 18:57:58 +01001394def _patch_multiple(target, spec=None, create=False, spec_set=None,
1395 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001396 """Perform multiple patches in a single call. It takes the object to be
1397 patched (either as an object or a string to fetch the object by importing)
1398 and keyword arguments for the patches::
1399
1400 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1401 ...
1402
1403 Use `DEFAULT` as the value if you want `patch.multiple` to create
1404 mocks for you. In this case the created mocks are passed into a decorated
1405 function by keyword, and a dictionary is returned when `patch.multiple` is
1406 used as a context manager.
1407
1408 `patch.multiple` can be used as a decorator, class decorator or a context
1409 manager. The arguments `spec`, `spec_set`, `create`,
1410 `autospec` and `new_callable` have the same meaning as for `patch`. These
1411 arguments will be applied to *all* patches done by `patch.multiple`.
1412
1413 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1414 for choosing which methods to wrap.
1415 """
1416 if type(target) is str:
1417 getter = lambda: _importer(target)
1418 else:
1419 getter = lambda: target
1420
1421 if not kwargs:
1422 raise ValueError(
1423 'Must supply at least one keyword argument with patch.multiple'
1424 )
1425 # need to wrap in a list for python 3, where items is a view
1426 items = list(kwargs.items())
1427 attribute, new = items[0]
1428 patcher = _patch(
1429 getter, attribute, new, spec, create, spec_set,
1430 autospec, new_callable, {}
1431 )
1432 patcher.attribute_name = attribute
1433 for attribute, new in items[1:]:
1434 this_patcher = _patch(
1435 getter, attribute, new, spec, create, spec_set,
1436 autospec, new_callable, {}
1437 )
1438 this_patcher.attribute_name = attribute
1439 patcher.additional_patchers.append(this_patcher)
1440 return patcher
1441
1442
1443def patch(
1444 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001445 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001446 ):
1447 """
1448 `patch` acts as a function decorator, class decorator or a context
1449 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001450 is patched with a `new` object. When the function/with statement exits
1451 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001452
Michael Foord54b3db82012-03-28 15:08:08 +01001453 If `new` is omitted, then the target is replaced with a
1454 `MagicMock`. If `patch` is used as a decorator and `new` is
1455 omitted, the created mock is passed in as an extra argument to the
1456 decorated function. If `patch` is used as a context manager the created
1457 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001458
Michael Foord54b3db82012-03-28 15:08:08 +01001459 `target` should be a string in the form `'package.module.ClassName'`. The
1460 `target` is imported and the specified object replaced with the `new`
1461 object, so the `target` must be importable from the environment you are
1462 calling `patch` from. The target is imported when the decorated function
1463 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001464
1465 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1466 if patch is creating one for you.
1467
1468 In addition you can pass `spec=True` or `spec_set=True`, which causes
1469 patch to pass in the object being mocked as the spec/spec_set object.
1470
1471 `new_callable` allows you to specify a different class, or callable object,
1472 that will be called to create the `new` object. By default `MagicMock` is
1473 used.
1474
1475 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1476 then the mock with be created with a spec from the object being replaced.
1477 All attributes of the mock will also have the spec of the corresponding
1478 attribute of the object being replaced. Methods and functions being
1479 mocked will have their arguments checked and will raise a `TypeError` if
1480 they are called with the wrong signature. For mocks replacing a class,
1481 their return value (the 'instance') will have the same spec as the class.
1482
1483 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1484 arbitrary object as the spec instead of the one being replaced.
1485
1486 By default `patch` will fail to replace attributes that don't exist. If
1487 you pass in `create=True`, and the attribute doesn't exist, patch will
1488 create the attribute for you when the patched function is called, and
1489 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001490 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001491 default because it can be dangerous. With it switched on you can write
1492 passing tests against APIs that don't actually exist!
1493
1494 Patch can be used as a `TestCase` class decorator. It works by
1495 decorating each test method in the class. This reduces the boilerplate
1496 code when your test methods share a common patchings set. `patch` finds
1497 tests by looking for method names that start with `patch.TEST_PREFIX`.
1498 By default this is `test`, which matches the way `unittest` finds tests.
1499 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1500
1501 Patch can be used as a context manager, with the with statement. Here the
1502 patching applies to the indented block after the with statement. If you
1503 use "as" then the patched object will be bound to the name after the
1504 "as"; very useful if `patch` is creating a mock object for you.
1505
1506 `patch` takes arbitrary keyword arguments. These will be passed to
1507 the `Mock` (or `new_callable`) on construction.
1508
1509 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1510 available for alternate use-cases.
1511 """
1512 getter, attribute = _get_target(target)
1513 return _patch(
1514 getter, attribute, new, spec, create,
1515 spec_set, autospec, new_callable, kwargs
1516 )
1517
1518
1519class _patch_dict(object):
1520 """
1521 Patch a dictionary, or dictionary like object, and restore the dictionary
1522 to its original state after the test.
1523
1524 `in_dict` can be a dictionary or a mapping like container. If it is a
1525 mapping then it must at least support getting, setting and deleting items
1526 plus iterating over keys.
1527
1528 `in_dict` can also be a string specifying the name of the dictionary, which
1529 will then be fetched by importing it.
1530
1531 `values` can be a dictionary of values to set in the dictionary. `values`
1532 can also be an iterable of `(key, value)` pairs.
1533
1534 If `clear` is True then the dictionary will be cleared before the new
1535 values are set.
1536
1537 `patch.dict` can also be called with arbitrary keyword arguments to set
1538 values in the dictionary::
1539
1540 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1541 ...
1542
1543 `patch.dict` can be used as a context manager, decorator or class
1544 decorator. When used as a class decorator `patch.dict` honours
1545 `patch.TEST_PREFIX` for choosing which methods to wrap.
1546 """
1547
1548 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1549 if isinstance(in_dict, str):
1550 in_dict = _importer(in_dict)
1551 self.in_dict = in_dict
1552 # support any argument supported by dict(...) constructor
1553 self.values = dict(values)
1554 self.values.update(kwargs)
1555 self.clear = clear
1556 self._original = None
1557
1558
1559 def __call__(self, f):
1560 if isinstance(f, type):
1561 return self.decorate_class(f)
1562 @wraps(f)
1563 def _inner(*args, **kw):
1564 self._patch_dict()
1565 try:
1566 return f(*args, **kw)
1567 finally:
1568 self._unpatch_dict()
1569
1570 return _inner
1571
1572
1573 def decorate_class(self, klass):
1574 for attr in dir(klass):
1575 attr_value = getattr(klass, attr)
1576 if (attr.startswith(patch.TEST_PREFIX) and
1577 hasattr(attr_value, "__call__")):
1578 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1579 decorated = decorator(attr_value)
1580 setattr(klass, attr, decorated)
1581 return klass
1582
1583
1584 def __enter__(self):
1585 """Patch the dict."""
1586 self._patch_dict()
1587
1588
1589 def _patch_dict(self):
1590 values = self.values
1591 in_dict = self.in_dict
1592 clear = self.clear
1593
1594 try:
1595 original = in_dict.copy()
1596 except AttributeError:
1597 # dict like object with no copy method
1598 # must support iteration over keys
1599 original = {}
1600 for key in in_dict:
1601 original[key] = in_dict[key]
1602 self._original = original
1603
1604 if clear:
1605 _clear_dict(in_dict)
1606
1607 try:
1608 in_dict.update(values)
1609 except AttributeError:
1610 # dict like object with no update method
1611 for key in values:
1612 in_dict[key] = values[key]
1613
1614
1615 def _unpatch_dict(self):
1616 in_dict = self.in_dict
1617 original = self._original
1618
1619 _clear_dict(in_dict)
1620
1621 try:
1622 in_dict.update(original)
1623 except AttributeError:
1624 for key in original:
1625 in_dict[key] = original[key]
1626
1627
1628 def __exit__(self, *args):
1629 """Unpatch the dict."""
1630 self._unpatch_dict()
1631 return False
1632
1633 start = __enter__
1634 stop = __exit__
1635
1636
1637def _clear_dict(in_dict):
1638 try:
1639 in_dict.clear()
1640 except AttributeError:
1641 keys = list(in_dict)
1642 for key in keys:
1643 del in_dict[key]
1644
1645
Michael Foordf7c41582012-06-10 20:36:32 +01001646def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001647 """Stop all active patches. LIFO to unroll nested patches."""
1648 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001649 patch.stop()
1650
1651
Michael Foord345266a2012-03-14 12:24:34 -07001652patch.object = _patch_object
1653patch.dict = _patch_dict
1654patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001655patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001656patch.TEST_PREFIX = 'test'
1657
1658magic_methods = (
1659 "lt le gt ge eq ne "
1660 "getitem setitem delitem "
1661 "len contains iter "
1662 "hash str sizeof "
1663 "enter exit "
1664 "divmod neg pos abs invert "
1665 "complex int float index "
1666 "trunc floor ceil "
1667 "bool next "
1668)
1669
Michael Foordd2623d72014-04-14 11:23:48 -04001670numerics = (
1671 "add sub mul div floordiv mod lshift rshift and xor or pow truediv"
1672)
Michael Foord345266a2012-03-14 12:24:34 -07001673inplace = ' '.join('i%s' % n for n in numerics.split())
1674right = ' '.join('r%s' % n for n in numerics.split())
1675
1676# not including __prepare__, __instancecheck__, __subclasscheck__
1677# (as they are metaclass methods)
1678# __del__ is not supported at all as it causes problems if it exists
1679
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001680_non_defaults = {
1681 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1682 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1683 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1684 '__repr__', '__dir__', '__subclasses__', '__format__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001685}
Michael Foord345266a2012-03-14 12:24:34 -07001686
1687
1688def _get_method(name, func):
1689 "Turns a callable object (like a mock) into a real function"
1690 def method(self, *args, **kw):
1691 return func(self, *args, **kw)
1692 method.__name__ = name
1693 return method
1694
1695
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001696_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001697 '__%s__' % method for method in
1698 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001699}
Michael Foord345266a2012-03-14 12:24:34 -07001700
1701_all_magics = _magics | _non_defaults
1702
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001703_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001704 '__getattr__', '__setattr__',
1705 '__init__', '__new__', '__prepare__'
1706 '__instancecheck__', '__subclasscheck__',
1707 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001708}
Michael Foord345266a2012-03-14 12:24:34 -07001709
1710_calculate_return_value = {
1711 '__hash__': lambda self: object.__hash__(self),
1712 '__str__': lambda self: object.__str__(self),
1713 '__sizeof__': lambda self: object.__sizeof__(self),
1714}
1715
1716_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001717 '__lt__': NotImplemented,
1718 '__gt__': NotImplemented,
1719 '__le__': NotImplemented,
1720 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001721 '__int__': 1,
1722 '__contains__': False,
1723 '__len__': 0,
1724 '__exit__': False,
1725 '__complex__': 1j,
1726 '__float__': 1.0,
1727 '__bool__': True,
1728 '__index__': 1,
1729}
1730
1731
1732def _get_eq(self):
1733 def __eq__(other):
1734 ret_val = self.__eq__._mock_return_value
1735 if ret_val is not DEFAULT:
1736 return ret_val
1737 return self is other
1738 return __eq__
1739
1740def _get_ne(self):
1741 def __ne__(other):
1742 if self.__ne__._mock_return_value is not DEFAULT:
1743 return DEFAULT
1744 return self is not other
1745 return __ne__
1746
1747def _get_iter(self):
1748 def __iter__():
1749 ret_val = self.__iter__._mock_return_value
1750 if ret_val is DEFAULT:
1751 return iter([])
1752 # if ret_val was already an iterator, then calling iter on it should
1753 # return the iterator unchanged
1754 return iter(ret_val)
1755 return __iter__
1756
1757_side_effect_methods = {
1758 '__eq__': _get_eq,
1759 '__ne__': _get_ne,
1760 '__iter__': _get_iter,
1761}
1762
1763
1764
1765def _set_return_value(mock, method, name):
1766 fixed = _return_values.get(name, DEFAULT)
1767 if fixed is not DEFAULT:
1768 method.return_value = fixed
1769 return
1770
1771 return_calulator = _calculate_return_value.get(name)
1772 if return_calulator is not None:
1773 try:
1774 return_value = return_calulator(mock)
1775 except AttributeError:
1776 # XXXX why do we return AttributeError here?
1777 # set it as a side_effect instead?
1778 return_value = AttributeError(name)
1779 method.return_value = return_value
1780 return
1781
1782 side_effector = _side_effect_methods.get(name)
1783 if side_effector is not None:
1784 method.side_effect = side_effector(mock)
1785
1786
1787
1788class MagicMixin(object):
1789 def __init__(self, *args, **kw):
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001790 _safe_super(MagicMixin, self).__init__(*args, **kw)
Michael Foord345266a2012-03-14 12:24:34 -07001791 self._mock_set_magics()
1792
1793
1794 def _mock_set_magics(self):
1795 these_magics = _magics
1796
1797 if self._mock_methods is not None:
1798 these_magics = _magics.intersection(self._mock_methods)
1799
1800 remove_magics = set()
1801 remove_magics = _magics - these_magics
1802
1803 for entry in remove_magics:
1804 if entry in type(self).__dict__:
1805 # remove unneeded magic methods
1806 delattr(self, entry)
1807
1808 # don't overwrite existing attributes if called a second time
1809 these_magics = these_magics - set(type(self).__dict__)
1810
1811 _type = type(self)
1812 for entry in these_magics:
1813 setattr(_type, entry, MagicProxy(entry, self))
1814
1815
1816
1817class NonCallableMagicMock(MagicMixin, NonCallableMock):
1818 """A version of `MagicMock` that isn't callable."""
1819 def mock_add_spec(self, spec, spec_set=False):
1820 """Add a spec to a mock. `spec` can either be an object or a
1821 list of strings. Only attributes on the `spec` can be fetched as
1822 attributes from the mock.
1823
1824 If `spec_set` is True then only attributes on the spec can be set."""
1825 self._mock_add_spec(spec, spec_set)
1826 self._mock_set_magics()
1827
1828
1829
1830class MagicMock(MagicMixin, Mock):
1831 """
1832 MagicMock is a subclass of Mock with default implementations
1833 of most of the magic methods. You can use MagicMock without having to
1834 configure the magic methods yourself.
1835
1836 If you use the `spec` or `spec_set` arguments then *only* magic
1837 methods that exist in the spec will be created.
1838
1839 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1840 """
1841 def mock_add_spec(self, spec, spec_set=False):
1842 """Add a spec to a mock. `spec` can either be an object or a
1843 list of strings. Only attributes on the `spec` can be fetched as
1844 attributes from the mock.
1845
1846 If `spec_set` is True then only attributes on the spec can be set."""
1847 self._mock_add_spec(spec, spec_set)
1848 self._mock_set_magics()
1849
1850
1851
1852class MagicProxy(object):
1853 def __init__(self, name, parent):
1854 self.name = name
1855 self.parent = parent
1856
1857 def __call__(self, *args, **kwargs):
1858 m = self.create_mock()
1859 return m(*args, **kwargs)
1860
1861 def create_mock(self):
1862 entry = self.name
1863 parent = self.parent
1864 m = parent._get_child_mock(name=entry, _new_name=entry,
1865 _new_parent=parent)
1866 setattr(parent, entry, m)
1867 _set_return_value(parent, m, entry)
1868 return m
1869
1870 def __get__(self, obj, _type=None):
1871 return self.create_mock()
1872
1873
1874
1875class _ANY(object):
1876 "A helper object that compares equal to everything."
1877
1878 def __eq__(self, other):
1879 return True
1880
1881 def __ne__(self, other):
1882 return False
1883
1884 def __repr__(self):
1885 return '<ANY>'
1886
1887ANY = _ANY()
1888
1889
1890
1891def _format_call_signature(name, args, kwargs):
1892 message = '%s(%%s)' % name
1893 formatted_args = ''
1894 args_string = ', '.join([repr(arg) for arg in args])
1895 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301896 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001897 ])
1898 if args_string:
1899 formatted_args = args_string
1900 if kwargs_string:
1901 if formatted_args:
1902 formatted_args += ', '
1903 formatted_args += kwargs_string
1904
1905 return message % formatted_args
1906
1907
1908
1909class _Call(tuple):
1910 """
1911 A tuple for holding the results of a call to a mock, either in the form
1912 `(args, kwargs)` or `(name, args, kwargs)`.
1913
1914 If args or kwargs are empty then a call tuple will compare equal to
1915 a tuple without those values. This makes comparisons less verbose::
1916
1917 _Call(('name', (), {})) == ('name',)
1918 _Call(('name', (1,), {})) == ('name', (1,))
1919 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1920
1921 The `_Call` object provides a useful shortcut for comparing with call::
1922
1923 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1924 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1925
1926 If the _Call has no name then it will match any name.
1927 """
1928 def __new__(cls, value=(), name=None, parent=None, two=False,
1929 from_kall=True):
1930 name = ''
1931 args = ()
1932 kwargs = {}
1933 _len = len(value)
1934 if _len == 3:
1935 name, args, kwargs = value
1936 elif _len == 2:
1937 first, second = value
1938 if isinstance(first, str):
1939 name = first
1940 if isinstance(second, tuple):
1941 args = second
1942 else:
1943 kwargs = second
1944 else:
1945 args, kwargs = first, second
1946 elif _len == 1:
1947 value, = value
1948 if isinstance(value, str):
1949 name = value
1950 elif isinstance(value, tuple):
1951 args = value
1952 else:
1953 kwargs = value
1954
1955 if two:
1956 return tuple.__new__(cls, (args, kwargs))
1957
1958 return tuple.__new__(cls, (name, args, kwargs))
1959
1960
1961 def __init__(self, value=(), name=None, parent=None, two=False,
1962 from_kall=True):
1963 self.name = name
1964 self.parent = parent
1965 self.from_kall = from_kall
1966
1967
1968 def __eq__(self, other):
1969 if other is ANY:
1970 return True
1971 try:
1972 len_other = len(other)
1973 except TypeError:
1974 return False
1975
1976 self_name = ''
1977 if len(self) == 2:
1978 self_args, self_kwargs = self
1979 else:
1980 self_name, self_args, self_kwargs = self
1981
1982 other_name = ''
1983 if len_other == 0:
1984 other_args, other_kwargs = (), {}
1985 elif len_other == 3:
1986 other_name, other_args, other_kwargs = other
1987 elif len_other == 1:
1988 value, = other
1989 if isinstance(value, tuple):
1990 other_args = value
1991 other_kwargs = {}
1992 elif isinstance(value, str):
1993 other_name = value
1994 other_args, other_kwargs = (), {}
1995 else:
1996 other_args = ()
1997 other_kwargs = value
1998 else:
1999 # len 2
2000 # could be (name, args) or (name, kwargs) or (args, kwargs)
2001 first, second = other
2002 if isinstance(first, str):
2003 other_name = first
2004 if isinstance(second, tuple):
2005 other_args, other_kwargs = second, {}
2006 else:
2007 other_args, other_kwargs = (), second
2008 else:
2009 other_args, other_kwargs = first, second
2010
2011 if self_name and other_name != self_name:
2012 return False
2013
2014 # this order is important for ANY to work!
2015 return (other_args, other_kwargs) == (self_args, self_kwargs)
2016
2017
Michael Foord345266a2012-03-14 12:24:34 -07002018 def __call__(self, *args, **kwargs):
2019 if self.name is None:
2020 return _Call(('', args, kwargs), name='()')
2021
2022 name = self.name + '()'
2023 return _Call((self.name, args, kwargs), name=name, parent=self)
2024
2025
2026 def __getattr__(self, attr):
2027 if self.name is None:
2028 return _Call(name=attr, from_kall=False)
2029 name = '%s.%s' % (self.name, attr)
2030 return _Call(name=name, parent=self, from_kall=False)
2031
2032
Kushal Dasa37b9582014-09-16 18:33:37 +05302033 def count(self, *args, **kwargs):
2034 return self.__getattr__('count')(*args, **kwargs)
2035
2036 def index(self, *args, **kwargs):
2037 return self.__getattr__('index')(*args, **kwargs)
2038
Michael Foord345266a2012-03-14 12:24:34 -07002039 def __repr__(self):
2040 if not self.from_kall:
2041 name = self.name or 'call'
2042 if name.startswith('()'):
2043 name = 'call%s' % name
2044 return name
2045
2046 if len(self) == 2:
2047 name = 'call'
2048 args, kwargs = self
2049 else:
2050 name, args, kwargs = self
2051 if not name:
2052 name = 'call'
2053 elif not name.startswith('()'):
2054 name = 'call.%s' % name
2055 else:
2056 name = 'call%s' % name
2057 return _format_call_signature(name, args, kwargs)
2058
2059
2060 def call_list(self):
2061 """For a call object that represents multiple calls, `call_list`
2062 returns a list of all the intermediate calls as well as the
2063 final call."""
2064 vals = []
2065 thing = self
2066 while thing is not None:
2067 if thing.from_kall:
2068 vals.append(thing)
2069 thing = thing.parent
2070 return _CallList(reversed(vals))
2071
2072
2073call = _Call(from_kall=False)
2074
2075
2076
2077def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2078 _name=None, **kwargs):
2079 """Create a mock object using another object as a spec. Attributes on the
2080 mock will use the corresponding attribute on the `spec` object as their
2081 spec.
2082
2083 Functions or methods being mocked will have their arguments checked
2084 to check that they are called with the correct signature.
2085
2086 If `spec_set` is True then attempting to set attributes that don't exist
2087 on the spec object will raise an `AttributeError`.
2088
2089 If a class is used as a spec then the return value of the mock (the
2090 instance of the class) will have the same spec. You can use a class as the
2091 spec for an instance object by passing `instance=True`. The returned mock
2092 will only be callable if instances of the mock are callable.
2093
2094 `create_autospec` also takes arbitrary keyword arguments that are passed to
2095 the constructor of the created mock."""
2096 if _is_list(spec):
2097 # can't pass a list instance to the mock constructor as it will be
2098 # interpreted as a list of strings
2099 spec = type(spec)
2100
2101 is_type = isinstance(spec, type)
2102
2103 _kwargs = {'spec': spec}
2104 if spec_set:
2105 _kwargs = {'spec_set': spec}
2106 elif spec is None:
2107 # None we mock with a normal mock without a spec
2108 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002109 if _kwargs and instance:
2110 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002111
2112 _kwargs.update(kwargs)
2113
2114 Klass = MagicMock
2115 if type(spec) in DescriptorTypes:
2116 # descriptors don't have a spec
2117 # because we don't know what type they return
2118 _kwargs = {}
2119 elif not _callable(spec):
2120 Klass = NonCallableMagicMock
2121 elif is_type and instance and not _instance_callable(spec):
2122 Klass = NonCallableMagicMock
2123
Kushal Das484f8a82014-04-16 01:05:50 +05302124 _name = _kwargs.pop('name', _name)
2125
Michael Foord345266a2012-03-14 12:24:34 -07002126 _new_name = _name
2127 if _parent is None:
2128 # for a top level object no _new_name should be set
2129 _new_name = ''
2130
2131 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2132 name=_name, **_kwargs)
2133
2134 if isinstance(spec, FunctionTypes):
2135 # should only happen at the top level because we don't
2136 # recurse for functions
2137 mock = _set_signature(mock, spec)
2138 else:
2139 _check_signature(spec, mock, is_type, instance)
2140
2141 if _parent is not None and not instance:
2142 _parent._mock_children[_name] = mock
2143
2144 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002145 mock.return_value = create_autospec(spec, spec_set, instance=True,
2146 _name='()', _parent=mock)
2147
2148 for entry in dir(spec):
2149 if _is_magic(entry):
2150 # MagicMock already does the useful magic methods for us
2151 continue
2152
Michael Foord345266a2012-03-14 12:24:34 -07002153 # XXXX do we need a better way of getting attributes without
2154 # triggering code execution (?) Probably not - we need the actual
2155 # object to mock it so we would rather trigger a property than mock
2156 # the property descriptor. Likewise we want to mock out dynamically
2157 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002158 # XXXX what about attributes that raise exceptions other than
2159 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002160 # we could be resilient against it, or catch and propagate the
2161 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002162 try:
2163 original = getattr(spec, entry)
2164 except AttributeError:
2165 continue
Michael Foord345266a2012-03-14 12:24:34 -07002166
2167 kwargs = {'spec': original}
2168 if spec_set:
2169 kwargs = {'spec_set': original}
2170
2171 if not isinstance(original, FunctionTypes):
2172 new = _SpecState(original, spec_set, mock, entry, instance)
2173 mock._mock_children[entry] = new
2174 else:
2175 parent = mock
2176 if isinstance(spec, FunctionTypes):
2177 parent = mock.mock
2178
Michael Foord345266a2012-03-14 12:24:34 -07002179 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002180 kwargs['_eat_self'] = skipfirst
2181 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2182 _new_parent=parent,
2183 **kwargs)
2184 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002185 _check_signature(original, new, skipfirst=skipfirst)
2186
2187 # so functions created with _set_signature become instance attributes,
2188 # *plus* their underlying mock exists in _mock_children of the parent
2189 # mock. Adding to _mock_children may be unnecessary where we are also
2190 # setting as an instance attribute?
2191 if isinstance(new, FunctionTypes):
2192 setattr(mock, entry, new)
2193
2194 return mock
2195
2196
2197def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002198 """
2199 Return whether we should skip the first argument on spec's `entry`
2200 attribute.
2201 """
Michael Foord345266a2012-03-14 12:24:34 -07002202 if not isinstance(spec, type):
2203 if entry in getattr(spec, '__dict__', {}):
2204 # instance attribute - shouldn't skip
2205 return False
Michael Foord345266a2012-03-14 12:24:34 -07002206 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002207
2208 for klass in spec.__mro__:
2209 result = klass.__dict__.get(entry, DEFAULT)
2210 if result is DEFAULT:
2211 continue
2212 if isinstance(result, (staticmethod, classmethod)):
2213 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002214 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2215 # Normal method => skip if looked up on type
2216 # (if looked up on instance, self is already skipped)
2217 return is_type
2218 else:
2219 return False
Michael Foord345266a2012-03-14 12:24:34 -07002220
2221 # shouldn't get here unless function is a dynamically provided attribute
2222 # XXXX untested behaviour
2223 return is_type
2224
2225
2226def _get_class(obj):
2227 try:
2228 return obj.__class__
2229 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002230 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002231 return type(obj)
2232
2233
2234class _SpecState(object):
2235
2236 def __init__(self, spec, spec_set=False, parent=None,
2237 name=None, ids=None, instance=False):
2238 self.spec = spec
2239 self.ids = ids
2240 self.spec_set = spec_set
2241 self.parent = parent
2242 self.instance = instance
2243 self.name = name
2244
2245
2246FunctionTypes = (
2247 # python function
2248 type(create_autospec),
2249 # instance method
2250 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002251)
2252
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002253MethodWrapperTypes = (
2254 type(ANY.__eq__.__get__),
2255)
2256
Michael Foord345266a2012-03-14 12:24:34 -07002257
Michael Foorda74561a2012-03-25 19:03:13 +01002258file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002259
Michael Foord04cbe0c2013-03-19 17:22:51 -07002260def _iterate_read_data(read_data):
2261 # Helper for mock_open:
2262 # Retrieve lines from read_data via a generator so that separate calls to
2263 # readline, read, and readlines are properly interleaved
2264 data_as_list = ['{}\n'.format(l) for l in read_data.split('\n')]
2265
2266 if data_as_list[-1] == '\n':
2267 # If the last line ended in a newline, the list comprehension will have an
2268 # extra entry that's just a newline. Remove this.
2269 data_as_list = data_as_list[:-1]
2270 else:
2271 # If there wasn't an extra newline by itself, then the file being
2272 # emulated doesn't have a newline to end the last line remove the
2273 # newline that our naive format() added
2274 data_as_list[-1] = data_as_list[-1][:-1]
2275
2276 for line in data_as_list:
2277 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002278
2279def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002280 """
2281 A helper function to create a mock to replace the use of `open`. It works
2282 for `open` called directly or used as a context manager.
2283
2284 The `mock` argument is the mock object to configure. If `None` (the
2285 default) then a `MagicMock` will be created for you, with the API limited
2286 to methods or attributes available on standard file handles.
2287
Michael Foord04cbe0c2013-03-19 17:22:51 -07002288 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2289 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002290 """
Michael Foord04cbe0c2013-03-19 17:22:51 -07002291 def _readlines_side_effect(*args, **kwargs):
2292 if handle.readlines.return_value is not None:
2293 return handle.readlines.return_value
2294 return list(_data)
2295
2296 def _read_side_effect(*args, **kwargs):
2297 if handle.read.return_value is not None:
2298 return handle.read.return_value
2299 return ''.join(_data)
2300
2301 def _readline_side_effect():
2302 if handle.readline.return_value is not None:
2303 while True:
2304 yield handle.readline.return_value
2305 for line in _data:
2306 yield line
2307
2308
Michael Foorda74561a2012-03-25 19:03:13 +01002309 global file_spec
2310 if file_spec is None:
2311 import _io
2312 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2313
Michael Foord345266a2012-03-14 12:24:34 -07002314 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002315 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002316
2317 handle = MagicMock(spec=file_spec)
Michael Foord345266a2012-03-14 12:24:34 -07002318 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002319
2320 _data = _iterate_read_data(read_data)
2321
2322 handle.write.return_value = None
2323 handle.read.return_value = None
2324 handle.readline.return_value = None
2325 handle.readlines.return_value = None
2326
2327 handle.read.side_effect = _read_side_effect
2328 handle.readline.side_effect = _readline_side_effect()
2329 handle.readlines.side_effect = _readlines_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002330
2331 mock.return_value = handle
2332 return mock
2333
2334
2335class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002336 """
2337 A mock intended to be used as a property, or other descriptor, on a class.
2338 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2339 a return value when it is fetched.
2340
2341 Fetching a `PropertyMock` instance from an object calls the mock, with
2342 no args. Setting it calls the mock with the value being set.
2343 """
Michael Foordc2870622012-04-13 16:57:22 +01002344 def _get_child_mock(self, **kwargs):
2345 return MagicMock(**kwargs)
2346
Michael Foord345266a2012-03-14 12:24:34 -07002347 def __get__(self, obj, obj_type):
2348 return self()
2349 def __set__(self, obj, val):
2350 self(val)