blob: be215f3552b32d49cf362cc11b1d6efd03ebd443 [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
Robert Collinsf58f88c2015-07-14 13:51:40 +1200509 if (sf is not None and not callable(sf)
510 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400511 sf = _MockIter(sf)
512 delegated.side_effect = sf
513 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700514
515 def __set_side_effect(self, value):
516 value = _try_iter(value)
517 delegated = self._mock_delegate
518 if delegated is None:
519 self._mock_side_effect = value
520 else:
521 delegated.side_effect = value
522
523 side_effect = property(__get_side_effect, __set_side_effect)
524
525
Kushal Das9cd39a12016-06-02 10:20:16 -0700526 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700527 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200528 if visited is None:
529 visited = []
530 if id(self) in visited:
531 return
532 visited.append(id(self))
533
Michael Foord345266a2012-03-14 12:24:34 -0700534 self.called = False
535 self.call_args = None
536 self.call_count = 0
537 self.mock_calls = _CallList()
538 self.call_args_list = _CallList()
539 self.method_calls = _CallList()
540
Kushal Das9cd39a12016-06-02 10:20:16 -0700541 if return_value:
542 self._mock_return_value = DEFAULT
543 if side_effect:
544 self._mock_side_effect = None
545
Michael Foord345266a2012-03-14 12:24:34 -0700546 for child in self._mock_children.values():
Michael Foord75963642012-06-09 17:31:59 +0100547 if isinstance(child, _SpecState):
548 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200549 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700550
551 ret = self._mock_return_value
552 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200553 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700554
555
556 def configure_mock(self, **kwargs):
557 """Set attributes on the mock through keyword arguments.
558
559 Attributes plus return values and side effects can be set on child
560 mocks using standard dot notation and unpacking a dictionary in the
561 method call:
562
563 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
564 >>> mock.configure_mock(**attrs)"""
565 for arg, val in sorted(kwargs.items(),
566 # we sort on the number of dots so that
567 # attributes are set before we set attributes on
568 # attributes
569 key=lambda entry: entry[0].count('.')):
570 args = arg.split('.')
571 final = args.pop()
572 obj = self
573 for entry in args:
574 obj = getattr(obj, entry)
575 setattr(obj, final, val)
576
577
578 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530579 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700580 raise AttributeError(name)
581 elif self._mock_methods is not None:
582 if name not in self._mock_methods or name in _all_magics:
583 raise AttributeError("Mock object has no attribute %r" % name)
584 elif _is_magic(name):
585 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530586 if not self._mock_unsafe:
587 if name.startswith(('assert', 'assret')):
588 raise AttributeError(name)
Michael Foord345266a2012-03-14 12:24:34 -0700589
590 result = self._mock_children.get(name)
591 if result is _deleted:
592 raise AttributeError(name)
593 elif result is None:
594 wraps = None
595 if self._mock_wraps is not None:
596 # XXXX should we get the attribute without triggering code
597 # execution?
598 wraps = getattr(self._mock_wraps, name)
599
600 result = self._get_child_mock(
601 parent=self, name=name, wraps=wraps, _new_name=name,
602 _new_parent=self
603 )
604 self._mock_children[name] = result
605
606 elif isinstance(result, _SpecState):
607 result = create_autospec(
608 result.spec, result.spec_set, result.instance,
609 result.parent, result.name
610 )
611 self._mock_children[name] = result
612
613 return result
614
615
616 def __repr__(self):
617 _name_list = [self._mock_new_name]
618 _parent = self._mock_new_parent
619 last = self
620
621 dot = '.'
622 if _name_list == ['()']:
623 dot = ''
624 seen = set()
625 while _parent is not None:
626 last = _parent
627
628 _name_list.append(_parent._mock_new_name + dot)
629 dot = '.'
630 if _parent._mock_new_name == '()':
631 dot = ''
632
633 _parent = _parent._mock_new_parent
634
635 # use ids here so as not to call __hash__ on the mocks
636 if id(_parent) in seen:
637 break
638 seen.add(id(_parent))
639
640 _name_list = list(reversed(_name_list))
641 _first = last._mock_name or 'mock'
642 if len(_name_list) > 1:
643 if _name_list[1] not in ('()', '().'):
644 _first += '.'
645 _name_list[0] = _first
646 name = ''.join(_name_list)
647
648 name_string = ''
649 if name not in ('mock', 'mock.'):
650 name_string = ' name=%r' % name
651
652 spec_string = ''
653 if self._spec_class is not None:
654 spec_string = ' spec=%r'
655 if self._spec_set:
656 spec_string = ' spec_set=%r'
657 spec_string = spec_string % self._spec_class.__name__
658 return "<%s%s%s id='%s'>" % (
659 type(self).__name__,
660 name_string,
661 spec_string,
662 id(self)
663 )
664
665
666 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700667 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100668 if not FILTER_DIR:
669 return object.__dir__(self)
670
Michael Foord345266a2012-03-14 12:24:34 -0700671 extras = self._mock_methods or []
672 from_type = dir(type(self))
673 from_dict = list(self.__dict__)
674
Michael Foord313f85f2012-03-25 18:16:07 +0100675 from_type = [e for e in from_type if not e.startswith('_')]
676 from_dict = [e for e in from_dict if not e.startswith('_') or
677 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700678 return sorted(set(extras + from_type + from_dict +
679 list(self._mock_children)))
680
681
682 def __setattr__(self, name, value):
683 if name in _allowed_names:
684 # property setters go through here
685 return object.__setattr__(self, name, value)
686 elif (self._spec_set and self._mock_methods is not None and
687 name not in self._mock_methods and
688 name not in self.__dict__):
689 raise AttributeError("Mock object has no attribute '%s'" % name)
690 elif name in _unsupported_magics:
691 msg = 'Attempting to set unsupported magic method %r.' % name
692 raise AttributeError(msg)
693 elif name in _all_magics:
694 if self._mock_methods is not None and name not in self._mock_methods:
695 raise AttributeError("Mock object has no attribute '%s'" % name)
696
697 if not _is_instance_mock(value):
698 setattr(type(self), name, _get_method(name, value))
699 original = value
700 value = lambda *args, **kw: original(self, *args, **kw)
701 else:
702 # only set _new_name and not name so that mock_calls is tracked
703 # but not method calls
704 _check_and_set_parent(self, value, None, name)
705 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100706 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700707 elif name == '__class__':
708 self._spec_class = value
709 return
710 else:
711 if _check_and_set_parent(self, value, name, name):
712 self._mock_children[name] = value
713 return object.__setattr__(self, name, value)
714
715
716 def __delattr__(self, name):
717 if name in _all_magics and name in type(self).__dict__:
718 delattr(type(self), name)
719 if name not in self.__dict__:
720 # for magic methods that are still MagicProxy objects and
721 # not set on the instance itself
722 return
723
724 if name in self.__dict__:
725 object.__delattr__(self, name)
726
727 obj = self._mock_children.get(name, _missing)
728 if obj is _deleted:
729 raise AttributeError(name)
730 if obj is not _missing:
731 del self._mock_children[name]
732 self._mock_children[name] = _deleted
733
734
Michael Foord345266a2012-03-14 12:24:34 -0700735 def _format_mock_call_signature(self, args, kwargs):
736 name = self._mock_name or 'mock'
737 return _format_call_signature(name, args, kwargs)
738
739
740 def _format_mock_failure_message(self, args, kwargs):
741 message = 'Expected call: %s\nActual call: %s'
742 expected_string = self._format_mock_call_signature(args, kwargs)
743 call_args = self.call_args
744 if len(call_args) == 3:
745 call_args = call_args[1:]
746 actual_string = self._format_mock_call_signature(*call_args)
747 return message % (expected_string, actual_string)
748
749
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100750 def _call_matcher(self, _call):
751 """
752 Given a call (or simply a (args, kwargs) tuple), return a
753 comparison key suitable for matching with other calls.
754 This is a best effort method which relies on the spec's signature,
755 if available, or falls back on the arguments themselves.
756 """
757 sig = self._spec_signature
758 if sig is not None:
759 if len(_call) == 2:
760 name = ''
761 args, kwargs = _call
762 else:
763 name, args, kwargs = _call
764 try:
765 return name, sig.bind(*args, **kwargs)
766 except TypeError as e:
767 return e.with_traceback(None)
768 else:
769 return _call
770
Kushal Das68290f42014-04-17 01:54:07 +0530771 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530772 """assert that the mock was never called.
773 """
774 self = _mock_self
775 if self.call_count != 0:
776 msg = ("Expected '%s' to not have been called. Called %s times." %
777 (self._mock_name or 'mock', self.call_count))
778 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100779
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100780 def assert_called(_mock_self):
781 """assert that the mock was called at least once
782 """
783 self = _mock_self
784 if self.call_count == 0:
785 msg = ("Expected '%s' to have been called." %
786 self._mock_name or 'mock')
787 raise AssertionError(msg)
788
789 def assert_called_once(_mock_self):
790 """assert that the mock was called only once.
791 """
792 self = _mock_self
793 if not self.call_count == 1:
794 msg = ("Expected '%s' to have been called once. Called %s times." %
795 (self._mock_name or 'mock', self.call_count))
796 raise AssertionError(msg)
797
Michael Foord345266a2012-03-14 12:24:34 -0700798 def assert_called_with(_mock_self, *args, **kwargs):
799 """assert that the mock was called with the specified arguments.
800
801 Raises an AssertionError if the args and keyword args passed in are
802 different to the last call to the mock."""
803 self = _mock_self
804 if self.call_args is None:
805 expected = self._format_mock_call_signature(args, kwargs)
806 raise AssertionError('Expected call: %s\nNot called' % (expected,))
807
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100808 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700809 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100810 return msg
811 expected = self._call_matcher((args, kwargs))
812 actual = self._call_matcher(self.call_args)
813 if expected != actual:
814 cause = expected if isinstance(expected, Exception) else None
815 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700816
817
818 def assert_called_once_with(_mock_self, *args, **kwargs):
819 """assert that the mock was called exactly once and with the specified
820 arguments."""
821 self = _mock_self
822 if not self.call_count == 1:
Michael Foord28d591c2012-09-28 16:15:22 +0100823 msg = ("Expected '%s' to be called once. Called %s times." %
824 (self._mock_name or 'mock', self.call_count))
Michael Foord345266a2012-03-14 12:24:34 -0700825 raise AssertionError(msg)
826 return self.assert_called_with(*args, **kwargs)
827
828
829 def assert_has_calls(self, calls, any_order=False):
830 """assert the mock has been called with the specified calls.
831 The `mock_calls` list is checked for the calls.
832
833 If `any_order` is False (the default) then the calls must be
834 sequential. There can be extra calls before or after the
835 specified calls.
836
837 If `any_order` is True then the calls can be in any order, but
838 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100839 expected = [self._call_matcher(c) for c in calls]
840 cause = expected if isinstance(expected, Exception) else None
841 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700842 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100843 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700844 raise AssertionError(
845 'Calls not found.\nExpected: %r\n'
Senthil Kumaran121edbf2016-01-12 06:18:32 -0800846 'Actual: %r' % (_CallList(calls), self.mock_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100847 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700848 return
849
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100850 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700851
852 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100853 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700854 try:
855 all_calls.remove(kall)
856 except ValueError:
857 not_found.append(kall)
858 if not_found:
859 raise AssertionError(
860 '%r not all found in call list' % (tuple(not_found),)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100861 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700862
863
864 def assert_any_call(self, *args, **kwargs):
865 """assert the mock has been called with the specified arguments.
866
867 The assert passes if the mock has *ever* been called, unlike
868 `assert_called_with` and `assert_called_once_with` that only pass if
869 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100870 expected = self._call_matcher((args, kwargs))
871 actual = [self._call_matcher(c) for c in self.call_args_list]
872 if expected not in actual:
873 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700874 expected_string = self._format_mock_call_signature(args, kwargs)
875 raise AssertionError(
876 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100877 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700878
879
880 def _get_child_mock(self, **kw):
881 """Create the child mocks for attributes and return value.
882 By default child mocks will be the same type as the parent.
883 Subclasses of Mock may want to override this to customize the way
884 child mocks are made.
885
886 For non-callable mocks the callable variant will be used (rather than
887 any custom subclass)."""
888 _type = type(self)
889 if not issubclass(_type, CallableMixin):
890 if issubclass(_type, NonCallableMagicMock):
891 klass = MagicMock
892 elif issubclass(_type, NonCallableMock) :
893 klass = Mock
894 else:
895 klass = _type.__mro__[1]
896 return klass(**kw)
897
898
899
900def _try_iter(obj):
901 if obj is None:
902 return obj
903 if _is_exception(obj):
904 return obj
905 if _callable(obj):
906 return obj
907 try:
908 return iter(obj)
909 except TypeError:
910 # XXXX backwards compatibility
911 # but this will blow up on first call - so maybe we should fail early?
912 return obj
913
914
915
916class CallableMixin(Base):
917
918 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
919 wraps=None, name=None, spec_set=None, parent=None,
920 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
921 self.__dict__['_mock_return_value'] = return_value
922
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000923 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700924 spec, wraps, name, spec_set, parent,
925 _spec_state, _new_name, _new_parent, **kwargs
926 )
927
928 self.side_effect = side_effect
929
930
931 def _mock_check_sig(self, *args, **kwargs):
932 # stub method that can be replaced with one with a specific signature
933 pass
934
935
936 def __call__(_mock_self, *args, **kwargs):
937 # can't use self in-case a function / method we are mocking uses self
938 # in the signature
939 _mock_self._mock_check_sig(*args, **kwargs)
940 return _mock_self._mock_call(*args, **kwargs)
941
942
943 def _mock_call(_mock_self, *args, **kwargs):
944 self = _mock_self
945 self.called = True
946 self.call_count += 1
Michael Foord345266a2012-03-14 12:24:34 -0700947 _new_name = self._mock_new_name
948 _new_parent = self._mock_new_parent
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100949
950 _call = _Call((args, kwargs), two=True)
951 self.call_args = _call
952 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700953 self.mock_calls.append(_Call(('', args, kwargs)))
954
955 seen = set()
956 skip_next_dot = _new_name == '()'
957 do_method_calls = self._mock_parent is not None
958 name = self._mock_name
959 while _new_parent is not None:
960 this_mock_call = _Call((_new_name, args, kwargs))
961 if _new_parent._mock_new_name:
962 dot = '.'
963 if skip_next_dot:
964 dot = ''
965
966 skip_next_dot = False
967 if _new_parent._mock_new_name == '()':
968 skip_next_dot = True
969
970 _new_name = _new_parent._mock_new_name + dot + _new_name
971
972 if do_method_calls:
973 if _new_name == name:
974 this_method_call = this_mock_call
975 else:
976 this_method_call = _Call((name, args, kwargs))
977 _new_parent.method_calls.append(this_method_call)
978
979 do_method_calls = _new_parent._mock_parent is not None
980 if do_method_calls:
981 name = _new_parent._mock_name + '.' + name
982
983 _new_parent.mock_calls.append(this_mock_call)
984 _new_parent = _new_parent._mock_new_parent
985
986 # use ids here so as not to call __hash__ on the mocks
987 _new_parent_id = id(_new_parent)
988 if _new_parent_id in seen:
989 break
990 seen.add(_new_parent_id)
991
992 ret_val = DEFAULT
993 effect = self.side_effect
994 if effect is not None:
995 if _is_exception(effect):
996 raise effect
997
998 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +0100999 result = next(effect)
1000 if _is_exception(result):
1001 raise result
Andrew Svetlov8b2cd752013-04-07 16:42:24 +03001002 if result is DEFAULT:
1003 result = self.return_value
Michael Foord2cd48732012-04-21 15:52:11 +01001004 return result
Michael Foord345266a2012-03-14 12:24:34 -07001005
1006 ret_val = effect(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001007
1008 if (self._mock_wraps is not None and
1009 self._mock_return_value is DEFAULT):
1010 return self._mock_wraps(*args, **kwargs)
1011 if ret_val is DEFAULT:
1012 ret_val = self.return_value
1013 return ret_val
1014
1015
1016
1017class Mock(CallableMixin, NonCallableMock):
1018 """
1019 Create a new `Mock` object. `Mock` takes several optional arguments
1020 that specify the behaviour of the Mock object:
1021
1022 * `spec`: This can be either a list of strings or an existing object (a
1023 class or instance) that acts as the specification for the mock object. If
1024 you pass in an object then a list of strings is formed by calling dir on
1025 the object (excluding unsupported magic attributes and methods). Accessing
1026 any attribute not in this list will raise an `AttributeError`.
1027
1028 If `spec` is an object (rather than a list of strings) then
1029 `mock.__class__` returns the class of the spec object. This allows mocks
1030 to pass `isinstance` tests.
1031
1032 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1033 or get an attribute on the mock that isn't on the object passed as
1034 `spec_set` will raise an `AttributeError`.
1035
1036 * `side_effect`: A function to be called whenever the Mock is called. See
1037 the `side_effect` attribute. Useful for raising exceptions or
1038 dynamically changing return values. The function is called with the same
1039 arguments as the mock, and unless it returns `DEFAULT`, the return
1040 value of this function is used as the return value.
1041
Michael Foord2cd48732012-04-21 15:52:11 +01001042 If `side_effect` is an iterable then each call to the mock will return
1043 the next value from the iterable. If any of the members of the iterable
1044 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001045
Michael Foord345266a2012-03-14 12:24:34 -07001046 * `return_value`: The value returned when the mock is called. By default
1047 this is a new Mock (created on first access). See the
1048 `return_value` attribute.
1049
Michael Foord0682a0c2012-04-13 20:51:20 +01001050 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1051 calling the Mock will pass the call through to the wrapped object
1052 (returning the real result). Attribute access on the mock will return a
1053 Mock object that wraps the corresponding attribute of the wrapped object
1054 (so attempting to access an attribute that doesn't exist will raise an
1055 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001056
1057 If the mock has an explicit `return_value` set then calls are not passed
1058 to the wrapped object and the `return_value` is returned instead.
1059
1060 * `name`: If the mock has a name then it will be used in the repr of the
1061 mock. This can be useful for debugging. The name is propagated to child
1062 mocks.
1063
1064 Mocks can also be called with arbitrary keyword arguments. These will be
1065 used to set attributes on the mock after it is created.
1066 """
1067
1068
1069
1070def _dot_lookup(thing, comp, import_path):
1071 try:
1072 return getattr(thing, comp)
1073 except AttributeError:
1074 __import__(import_path)
1075 return getattr(thing, comp)
1076
1077
1078def _importer(target):
1079 components = target.split('.')
1080 import_path = components.pop(0)
1081 thing = __import__(import_path)
1082
1083 for comp in components:
1084 import_path += ".%s" % comp
1085 thing = _dot_lookup(thing, comp, import_path)
1086 return thing
1087
1088
1089def _is_started(patcher):
1090 # XXXX horrible
1091 return hasattr(patcher, 'is_local')
1092
1093
1094class _patch(object):
1095
1096 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001097 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001098
1099 def __init__(
1100 self, getter, attribute, new, spec, create,
1101 spec_set, autospec, new_callable, kwargs
1102 ):
1103 if new_callable is not None:
1104 if new is not DEFAULT:
1105 raise ValueError(
1106 "Cannot use 'new' and 'new_callable' together"
1107 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001108 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001109 raise ValueError(
1110 "Cannot use 'autospec' and 'new_callable' together"
1111 )
1112
1113 self.getter = getter
1114 self.attribute = attribute
1115 self.new = new
1116 self.new_callable = new_callable
1117 self.spec = spec
1118 self.create = create
1119 self.has_local = False
1120 self.spec_set = spec_set
1121 self.autospec = autospec
1122 self.kwargs = kwargs
1123 self.additional_patchers = []
1124
1125
1126 def copy(self):
1127 patcher = _patch(
1128 self.getter, self.attribute, self.new, self.spec,
1129 self.create, self.spec_set,
1130 self.autospec, self.new_callable, self.kwargs
1131 )
1132 patcher.attribute_name = self.attribute_name
1133 patcher.additional_patchers = [
1134 p.copy() for p in self.additional_patchers
1135 ]
1136 return patcher
1137
1138
1139 def __call__(self, func):
1140 if isinstance(func, type):
1141 return self.decorate_class(func)
1142 return self.decorate_callable(func)
1143
1144
1145 def decorate_class(self, klass):
1146 for attr in dir(klass):
1147 if not attr.startswith(patch.TEST_PREFIX):
1148 continue
1149
1150 attr_value = getattr(klass, attr)
1151 if not hasattr(attr_value, "__call__"):
1152 continue
1153
1154 patcher = self.copy()
1155 setattr(klass, attr, patcher(attr_value))
1156 return klass
1157
1158
1159 def decorate_callable(self, func):
1160 if hasattr(func, 'patchings'):
1161 func.patchings.append(self)
1162 return func
1163
1164 @wraps(func)
1165 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001166 extra_args = []
1167 entered_patchers = []
1168
Michael Foord50a8c0e2012-03-25 18:57:58 +01001169 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001170 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001171 for patching in patched.patchings:
1172 arg = patching.__enter__()
1173 entered_patchers.append(patching)
1174 if patching.attribute_name is not None:
1175 keywargs.update(arg)
1176 elif patching.new is DEFAULT:
1177 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001178
Michael Foordd7c65e22012-03-14 14:56:54 -07001179 args += tuple(extra_args)
1180 return func(*args, **keywargs)
1181 except:
1182 if (patching not in entered_patchers and
1183 _is_started(patching)):
1184 # the patcher may have been started, but an exception
1185 # raised whilst entering one of its additional_patchers
1186 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001187 # Pass the exception to __exit__
1188 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001189 # re-raise the exception
1190 raise
Michael Foord345266a2012-03-14 12:24:34 -07001191 finally:
1192 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001193 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001194
1195 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001196 return patched
1197
1198
1199 def get_original(self):
1200 target = self.getter()
1201 name = self.attribute
1202
1203 original = DEFAULT
1204 local = False
1205
1206 try:
1207 original = target.__dict__[name]
1208 except (AttributeError, KeyError):
1209 original = getattr(target, name, DEFAULT)
1210 else:
1211 local = True
1212
Michael Foordfddcfa22014-04-14 16:25:20 -04001213 if name in _builtins and isinstance(target, ModuleType):
1214 self.create = True
1215
Michael Foord345266a2012-03-14 12:24:34 -07001216 if not self.create and original is DEFAULT:
1217 raise AttributeError(
1218 "%s does not have the attribute %r" % (target, name)
1219 )
1220 return original, local
1221
1222
1223 def __enter__(self):
1224 """Perform the patch."""
1225 new, spec, spec_set = self.new, self.spec, self.spec_set
1226 autospec, kwargs = self.autospec, self.kwargs
1227 new_callable = self.new_callable
1228 self.target = self.getter()
1229
Michael Foord50a8c0e2012-03-25 18:57:58 +01001230 # normalise False to None
1231 if spec is False:
1232 spec = None
1233 if spec_set is False:
1234 spec_set = None
1235 if autospec is False:
1236 autospec = None
1237
1238 if spec is not None and autospec is not None:
1239 raise TypeError("Can't specify spec and autospec")
1240 if ((spec is not None or autospec is not None) and
1241 spec_set not in (True, None)):
1242 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1243
Michael Foord345266a2012-03-14 12:24:34 -07001244 original, local = self.get_original()
1245
Michael Foord50a8c0e2012-03-25 18:57:58 +01001246 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001247 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001248 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001249 # set spec to the object we are replacing
1250 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001251 if spec_set is True:
1252 spec_set = original
1253 spec = None
1254 elif spec is not None:
1255 if spec_set is True:
1256 spec_set = spec
1257 spec = None
1258 elif spec_set is True:
1259 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001260
Michael Foord50a8c0e2012-03-25 18:57:58 +01001261 if spec is not None or spec_set is not None:
1262 if original is DEFAULT:
1263 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001264 if isinstance(original, type):
1265 # If we're patching out a class and there is a spec
1266 inherit = True
1267
1268 Klass = MagicMock
1269 _kwargs = {}
1270 if new_callable is not None:
1271 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001272 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001273 this_spec = spec
1274 if spec_set is not None:
1275 this_spec = spec_set
1276 if _is_list(this_spec):
1277 not_callable = '__call__' not in this_spec
1278 else:
1279 not_callable = not callable(this_spec)
1280 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001281 Klass = NonCallableMagicMock
1282
1283 if spec is not None:
1284 _kwargs['spec'] = spec
1285 if spec_set is not None:
1286 _kwargs['spec_set'] = spec_set
1287
1288 # add a name to mocks
1289 if (isinstance(Klass, type) and
1290 issubclass(Klass, NonCallableMock) and self.attribute):
1291 _kwargs['name'] = self.attribute
1292
1293 _kwargs.update(kwargs)
1294 new = Klass(**_kwargs)
1295
1296 if inherit and _is_instance_mock(new):
1297 # we can only tell if the instance should be callable if the
1298 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001299 this_spec = spec
1300 if spec_set is not None:
1301 this_spec = spec_set
1302 if (not _is_list(this_spec) and not
1303 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001304 Klass = NonCallableMagicMock
1305
1306 _kwargs.pop('name')
1307 new.return_value = Klass(_new_parent=new, _new_name='()',
1308 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001309 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001310 # spec is ignored, new *must* be default, spec_set is treated
1311 # as a boolean. Should we check spec is not None and that spec_set
1312 # is a bool?
1313 if new is not DEFAULT:
1314 raise TypeError(
1315 "autospec creates the mock for you. Can't specify "
1316 "autospec and new."
1317 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001318 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001319 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001320 spec_set = bool(spec_set)
1321 if autospec is True:
1322 autospec = original
1323
1324 new = create_autospec(autospec, spec_set=spec_set,
1325 _name=self.attribute, **kwargs)
1326 elif kwargs:
1327 # can't set keyword args when we aren't creating the mock
1328 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1329 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1330
1331 new_attr = new
1332
1333 self.temp_original = original
1334 self.is_local = local
1335 setattr(self.target, self.attribute, new_attr)
1336 if self.attribute_name is not None:
1337 extra_args = {}
1338 if self.new is DEFAULT:
1339 extra_args[self.attribute_name] = new
1340 for patching in self.additional_patchers:
1341 arg = patching.__enter__()
1342 if patching.new is DEFAULT:
1343 extra_args.update(arg)
1344 return extra_args
1345
1346 return new
1347
1348
Michael Foord50a8c0e2012-03-25 18:57:58 +01001349 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001350 """Undo the patch."""
1351 if not _is_started(self):
1352 raise RuntimeError('stop called on unstarted patcher')
1353
1354 if self.is_local and self.temp_original is not DEFAULT:
1355 setattr(self.target, self.attribute, self.temp_original)
1356 else:
1357 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001358 if not self.create and (not hasattr(self.target, self.attribute) or
1359 self.attribute in ('__doc__', '__module__',
1360 '__defaults__', '__annotations__',
1361 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001362 # needed for proxy objects like django settings
1363 setattr(self.target, self.attribute, self.temp_original)
1364
1365 del self.temp_original
1366 del self.is_local
1367 del self.target
1368 for patcher in reversed(self.additional_patchers):
1369 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001370 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001371
Michael Foordf7c41582012-06-10 20:36:32 +01001372
1373 def start(self):
1374 """Activate a patch, returning any created mock."""
1375 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001376 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001377 return result
1378
1379
1380 def stop(self):
1381 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001382 try:
1383 self._active_patches.remove(self)
1384 except ValueError:
1385 # If the patch hasn't been started this will fail
1386 pass
1387
Michael Foordf7c41582012-06-10 20:36:32 +01001388 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001389
1390
1391
1392def _get_target(target):
1393 try:
1394 target, attribute = target.rsplit('.', 1)
1395 except (TypeError, ValueError):
1396 raise TypeError("Need a valid target to patch. You supplied: %r" %
1397 (target,))
1398 getter = lambda: _importer(target)
1399 return getter, attribute
1400
1401
1402def _patch_object(
1403 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001404 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001405 new_callable=None, **kwargs
1406 ):
1407 """
Michael Foord345266a2012-03-14 12:24:34 -07001408 patch the named member (`attribute`) on an object (`target`) with a mock
1409 object.
1410
1411 `patch.object` can be used as a decorator, class decorator or a context
1412 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1413 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1414 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1415 the mock object it creates.
1416
1417 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1418 for choosing which methods to wrap.
1419 """
1420 getter = lambda: target
1421 return _patch(
1422 getter, attribute, new, spec, create,
1423 spec_set, autospec, new_callable, kwargs
1424 )
1425
1426
Michael Foord50a8c0e2012-03-25 18:57:58 +01001427def _patch_multiple(target, spec=None, create=False, spec_set=None,
1428 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001429 """Perform multiple patches in a single call. It takes the object to be
1430 patched (either as an object or a string to fetch the object by importing)
1431 and keyword arguments for the patches::
1432
1433 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1434 ...
1435
1436 Use `DEFAULT` as the value if you want `patch.multiple` to create
1437 mocks for you. In this case the created mocks are passed into a decorated
1438 function by keyword, and a dictionary is returned when `patch.multiple` is
1439 used as a context manager.
1440
1441 `patch.multiple` can be used as a decorator, class decorator or a context
1442 manager. The arguments `spec`, `spec_set`, `create`,
1443 `autospec` and `new_callable` have the same meaning as for `patch`. These
1444 arguments will be applied to *all* patches done by `patch.multiple`.
1445
1446 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1447 for choosing which methods to wrap.
1448 """
1449 if type(target) is str:
1450 getter = lambda: _importer(target)
1451 else:
1452 getter = lambda: target
1453
1454 if not kwargs:
1455 raise ValueError(
1456 'Must supply at least one keyword argument with patch.multiple'
1457 )
1458 # need to wrap in a list for python 3, where items is a view
1459 items = list(kwargs.items())
1460 attribute, new = items[0]
1461 patcher = _patch(
1462 getter, attribute, new, spec, create, spec_set,
1463 autospec, new_callable, {}
1464 )
1465 patcher.attribute_name = attribute
1466 for attribute, new in items[1:]:
1467 this_patcher = _patch(
1468 getter, attribute, new, spec, create, spec_set,
1469 autospec, new_callable, {}
1470 )
1471 this_patcher.attribute_name = attribute
1472 patcher.additional_patchers.append(this_patcher)
1473 return patcher
1474
1475
1476def patch(
1477 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001478 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001479 ):
1480 """
1481 `patch` acts as a function decorator, class decorator or a context
1482 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001483 is patched with a `new` object. When the function/with statement exits
1484 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001485
Michael Foord54b3db82012-03-28 15:08:08 +01001486 If `new` is omitted, then the target is replaced with a
1487 `MagicMock`. If `patch` is used as a decorator and `new` is
1488 omitted, the created mock is passed in as an extra argument to the
1489 decorated function. If `patch` is used as a context manager the created
1490 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001491
Michael Foord54b3db82012-03-28 15:08:08 +01001492 `target` should be a string in the form `'package.module.ClassName'`. The
1493 `target` is imported and the specified object replaced with the `new`
1494 object, so the `target` must be importable from the environment you are
1495 calling `patch` from. The target is imported when the decorated function
1496 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001497
1498 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1499 if patch is creating one for you.
1500
1501 In addition you can pass `spec=True` or `spec_set=True`, which causes
1502 patch to pass in the object being mocked as the spec/spec_set object.
1503
1504 `new_callable` allows you to specify a different class, or callable object,
1505 that will be called to create the `new` object. By default `MagicMock` is
1506 used.
1507
1508 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001509 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001510 All attributes of the mock will also have the spec of the corresponding
1511 attribute of the object being replaced. Methods and functions being
1512 mocked will have their arguments checked and will raise a `TypeError` if
1513 they are called with the wrong signature. For mocks replacing a class,
1514 their return value (the 'instance') will have the same spec as the class.
1515
1516 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1517 arbitrary object as the spec instead of the one being replaced.
1518
1519 By default `patch` will fail to replace attributes that don't exist. If
1520 you pass in `create=True`, and the attribute doesn't exist, patch will
1521 create the attribute for you when the patched function is called, and
1522 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001523 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001524 default because it can be dangerous. With it switched on you can write
1525 passing tests against APIs that don't actually exist!
1526
1527 Patch can be used as a `TestCase` class decorator. It works by
1528 decorating each test method in the class. This reduces the boilerplate
1529 code when your test methods share a common patchings set. `patch` finds
1530 tests by looking for method names that start with `patch.TEST_PREFIX`.
1531 By default this is `test`, which matches the way `unittest` finds tests.
1532 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1533
1534 Patch can be used as a context manager, with the with statement. Here the
1535 patching applies to the indented block after the with statement. If you
1536 use "as" then the patched object will be bound to the name after the
1537 "as"; very useful if `patch` is creating a mock object for you.
1538
1539 `patch` takes arbitrary keyword arguments. These will be passed to
1540 the `Mock` (or `new_callable`) on construction.
1541
1542 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1543 available for alternate use-cases.
1544 """
1545 getter, attribute = _get_target(target)
1546 return _patch(
1547 getter, attribute, new, spec, create,
1548 spec_set, autospec, new_callable, kwargs
1549 )
1550
1551
1552class _patch_dict(object):
1553 """
1554 Patch a dictionary, or dictionary like object, and restore the dictionary
1555 to its original state after the test.
1556
1557 `in_dict` can be a dictionary or a mapping like container. If it is a
1558 mapping then it must at least support getting, setting and deleting items
1559 plus iterating over keys.
1560
1561 `in_dict` can also be a string specifying the name of the dictionary, which
1562 will then be fetched by importing it.
1563
1564 `values` can be a dictionary of values to set in the dictionary. `values`
1565 can also be an iterable of `(key, value)` pairs.
1566
1567 If `clear` is True then the dictionary will be cleared before the new
1568 values are set.
1569
1570 `patch.dict` can also be called with arbitrary keyword arguments to set
1571 values in the dictionary::
1572
1573 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1574 ...
1575
1576 `patch.dict` can be used as a context manager, decorator or class
1577 decorator. When used as a class decorator `patch.dict` honours
1578 `patch.TEST_PREFIX` for choosing which methods to wrap.
1579 """
1580
1581 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1582 if isinstance(in_dict, str):
1583 in_dict = _importer(in_dict)
1584 self.in_dict = in_dict
1585 # support any argument supported by dict(...) constructor
1586 self.values = dict(values)
1587 self.values.update(kwargs)
1588 self.clear = clear
1589 self._original = None
1590
1591
1592 def __call__(self, f):
1593 if isinstance(f, type):
1594 return self.decorate_class(f)
1595 @wraps(f)
1596 def _inner(*args, **kw):
1597 self._patch_dict()
1598 try:
1599 return f(*args, **kw)
1600 finally:
1601 self._unpatch_dict()
1602
1603 return _inner
1604
1605
1606 def decorate_class(self, klass):
1607 for attr in dir(klass):
1608 attr_value = getattr(klass, attr)
1609 if (attr.startswith(patch.TEST_PREFIX) and
1610 hasattr(attr_value, "__call__")):
1611 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1612 decorated = decorator(attr_value)
1613 setattr(klass, attr, decorated)
1614 return klass
1615
1616
1617 def __enter__(self):
1618 """Patch the dict."""
1619 self._patch_dict()
1620
1621
1622 def _patch_dict(self):
1623 values = self.values
1624 in_dict = self.in_dict
1625 clear = self.clear
1626
1627 try:
1628 original = in_dict.copy()
1629 except AttributeError:
1630 # dict like object with no copy method
1631 # must support iteration over keys
1632 original = {}
1633 for key in in_dict:
1634 original[key] = in_dict[key]
1635 self._original = original
1636
1637 if clear:
1638 _clear_dict(in_dict)
1639
1640 try:
1641 in_dict.update(values)
1642 except AttributeError:
1643 # dict like object with no update method
1644 for key in values:
1645 in_dict[key] = values[key]
1646
1647
1648 def _unpatch_dict(self):
1649 in_dict = self.in_dict
1650 original = self._original
1651
1652 _clear_dict(in_dict)
1653
1654 try:
1655 in_dict.update(original)
1656 except AttributeError:
1657 for key in original:
1658 in_dict[key] = original[key]
1659
1660
1661 def __exit__(self, *args):
1662 """Unpatch the dict."""
1663 self._unpatch_dict()
1664 return False
1665
1666 start = __enter__
1667 stop = __exit__
1668
1669
1670def _clear_dict(in_dict):
1671 try:
1672 in_dict.clear()
1673 except AttributeError:
1674 keys = list(in_dict)
1675 for key in keys:
1676 del in_dict[key]
1677
1678
Michael Foordf7c41582012-06-10 20:36:32 +01001679def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001680 """Stop all active patches. LIFO to unroll nested patches."""
1681 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001682 patch.stop()
1683
1684
Michael Foord345266a2012-03-14 12:24:34 -07001685patch.object = _patch_object
1686patch.dict = _patch_dict
1687patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001688patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001689patch.TEST_PREFIX = 'test'
1690
1691magic_methods = (
1692 "lt le gt ge eq ne "
1693 "getitem setitem delitem "
1694 "len contains iter "
1695 "hash str sizeof "
1696 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001697 # we added divmod and rdivmod here instead of numerics
1698 # because there is no idivmod
1699 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001700 "complex int float index "
1701 "trunc floor ceil "
1702 "bool next "
1703)
1704
Michael Foordd2623d72014-04-14 11:23:48 -04001705numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001706 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001707)
Michael Foord345266a2012-03-14 12:24:34 -07001708inplace = ' '.join('i%s' % n for n in numerics.split())
1709right = ' '.join('r%s' % n for n in numerics.split())
1710
1711# not including __prepare__, __instancecheck__, __subclasscheck__
1712# (as they are metaclass methods)
1713# __del__ is not supported at all as it causes problems if it exists
1714
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001715_non_defaults = {
1716 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1717 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1718 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1719 '__repr__', '__dir__', '__subclasses__', '__format__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001720}
Michael Foord345266a2012-03-14 12:24:34 -07001721
1722
1723def _get_method(name, func):
1724 "Turns a callable object (like a mock) into a real function"
1725 def method(self, *args, **kw):
1726 return func(self, *args, **kw)
1727 method.__name__ = name
1728 return method
1729
1730
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001731_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001732 '__%s__' % method for method in
1733 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001734}
Michael Foord345266a2012-03-14 12:24:34 -07001735
1736_all_magics = _magics | _non_defaults
1737
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001738_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001739 '__getattr__', '__setattr__',
1740 '__init__', '__new__', '__prepare__'
1741 '__instancecheck__', '__subclasscheck__',
1742 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001743}
Michael Foord345266a2012-03-14 12:24:34 -07001744
1745_calculate_return_value = {
1746 '__hash__': lambda self: object.__hash__(self),
1747 '__str__': lambda self: object.__str__(self),
1748 '__sizeof__': lambda self: object.__sizeof__(self),
1749}
1750
1751_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001752 '__lt__': NotImplemented,
1753 '__gt__': NotImplemented,
1754 '__le__': NotImplemented,
1755 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001756 '__int__': 1,
1757 '__contains__': False,
1758 '__len__': 0,
1759 '__exit__': False,
1760 '__complex__': 1j,
1761 '__float__': 1.0,
1762 '__bool__': True,
1763 '__index__': 1,
1764}
1765
1766
1767def _get_eq(self):
1768 def __eq__(other):
1769 ret_val = self.__eq__._mock_return_value
1770 if ret_val is not DEFAULT:
1771 return ret_val
1772 return self is other
1773 return __eq__
1774
1775def _get_ne(self):
1776 def __ne__(other):
1777 if self.__ne__._mock_return_value is not DEFAULT:
1778 return DEFAULT
1779 return self is not other
1780 return __ne__
1781
1782def _get_iter(self):
1783 def __iter__():
1784 ret_val = self.__iter__._mock_return_value
1785 if ret_val is DEFAULT:
1786 return iter([])
1787 # if ret_val was already an iterator, then calling iter on it should
1788 # return the iterator unchanged
1789 return iter(ret_val)
1790 return __iter__
1791
1792_side_effect_methods = {
1793 '__eq__': _get_eq,
1794 '__ne__': _get_ne,
1795 '__iter__': _get_iter,
1796}
1797
1798
1799
1800def _set_return_value(mock, method, name):
1801 fixed = _return_values.get(name, DEFAULT)
1802 if fixed is not DEFAULT:
1803 method.return_value = fixed
1804 return
1805
1806 return_calulator = _calculate_return_value.get(name)
1807 if return_calulator is not None:
1808 try:
1809 return_value = return_calulator(mock)
1810 except AttributeError:
1811 # XXXX why do we return AttributeError here?
1812 # set it as a side_effect instead?
1813 return_value = AttributeError(name)
1814 method.return_value = return_value
1815 return
1816
1817 side_effector = _side_effect_methods.get(name)
1818 if side_effector is not None:
1819 method.side_effect = side_effector(mock)
1820
1821
1822
1823class MagicMixin(object):
1824 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001825 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001826 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001827 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001828
1829
1830 def _mock_set_magics(self):
1831 these_magics = _magics
1832
Łukasz Langaa468db92015-04-13 23:12:42 -07001833 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001834 these_magics = _magics.intersection(self._mock_methods)
1835
1836 remove_magics = set()
1837 remove_magics = _magics - these_magics
1838
1839 for entry in remove_magics:
1840 if entry in type(self).__dict__:
1841 # remove unneeded magic methods
1842 delattr(self, entry)
1843
1844 # don't overwrite existing attributes if called a second time
1845 these_magics = these_magics - set(type(self).__dict__)
1846
1847 _type = type(self)
1848 for entry in these_magics:
1849 setattr(_type, entry, MagicProxy(entry, self))
1850
1851
1852
1853class NonCallableMagicMock(MagicMixin, NonCallableMock):
1854 """A version of `MagicMock` that isn't callable."""
1855 def mock_add_spec(self, spec, spec_set=False):
1856 """Add a spec to a mock. `spec` can either be an object or a
1857 list of strings. Only attributes on the `spec` can be fetched as
1858 attributes from the mock.
1859
1860 If `spec_set` is True then only attributes on the spec can be set."""
1861 self._mock_add_spec(spec, spec_set)
1862 self._mock_set_magics()
1863
1864
1865
1866class MagicMock(MagicMixin, Mock):
1867 """
1868 MagicMock is a subclass of Mock with default implementations
1869 of most of the magic methods. You can use MagicMock without having to
1870 configure the magic methods yourself.
1871
1872 If you use the `spec` or `spec_set` arguments then *only* magic
1873 methods that exist in the spec will be created.
1874
1875 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1876 """
1877 def mock_add_spec(self, spec, spec_set=False):
1878 """Add a spec to a mock. `spec` can either be an object or a
1879 list of strings. Only attributes on the `spec` can be fetched as
1880 attributes from the mock.
1881
1882 If `spec_set` is True then only attributes on the spec can be set."""
1883 self._mock_add_spec(spec, spec_set)
1884 self._mock_set_magics()
1885
1886
1887
1888class MagicProxy(object):
1889 def __init__(self, name, parent):
1890 self.name = name
1891 self.parent = parent
1892
1893 def __call__(self, *args, **kwargs):
1894 m = self.create_mock()
1895 return m(*args, **kwargs)
1896
1897 def create_mock(self):
1898 entry = self.name
1899 parent = self.parent
1900 m = parent._get_child_mock(name=entry, _new_name=entry,
1901 _new_parent=parent)
1902 setattr(parent, entry, m)
1903 _set_return_value(parent, m, entry)
1904 return m
1905
1906 def __get__(self, obj, _type=None):
1907 return self.create_mock()
1908
1909
1910
1911class _ANY(object):
1912 "A helper object that compares equal to everything."
1913
1914 def __eq__(self, other):
1915 return True
1916
1917 def __ne__(self, other):
1918 return False
1919
1920 def __repr__(self):
1921 return '<ANY>'
1922
1923ANY = _ANY()
1924
1925
1926
1927def _format_call_signature(name, args, kwargs):
1928 message = '%s(%%s)' % name
1929 formatted_args = ''
1930 args_string = ', '.join([repr(arg) for arg in args])
1931 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301932 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001933 ])
1934 if args_string:
1935 formatted_args = args_string
1936 if kwargs_string:
1937 if formatted_args:
1938 formatted_args += ', '
1939 formatted_args += kwargs_string
1940
1941 return message % formatted_args
1942
1943
1944
1945class _Call(tuple):
1946 """
1947 A tuple for holding the results of a call to a mock, either in the form
1948 `(args, kwargs)` or `(name, args, kwargs)`.
1949
1950 If args or kwargs are empty then a call tuple will compare equal to
1951 a tuple without those values. This makes comparisons less verbose::
1952
1953 _Call(('name', (), {})) == ('name',)
1954 _Call(('name', (1,), {})) == ('name', (1,))
1955 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1956
1957 The `_Call` object provides a useful shortcut for comparing with call::
1958
1959 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1960 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1961
1962 If the _Call has no name then it will match any name.
1963 """
1964 def __new__(cls, value=(), name=None, parent=None, two=False,
1965 from_kall=True):
1966 name = ''
1967 args = ()
1968 kwargs = {}
1969 _len = len(value)
1970 if _len == 3:
1971 name, args, kwargs = value
1972 elif _len == 2:
1973 first, second = value
1974 if isinstance(first, str):
1975 name = first
1976 if isinstance(second, tuple):
1977 args = second
1978 else:
1979 kwargs = second
1980 else:
1981 args, kwargs = first, second
1982 elif _len == 1:
1983 value, = value
1984 if isinstance(value, str):
1985 name = value
1986 elif isinstance(value, tuple):
1987 args = value
1988 else:
1989 kwargs = value
1990
1991 if two:
1992 return tuple.__new__(cls, (args, kwargs))
1993
1994 return tuple.__new__(cls, (name, args, kwargs))
1995
1996
1997 def __init__(self, value=(), name=None, parent=None, two=False,
1998 from_kall=True):
1999 self.name = name
2000 self.parent = parent
2001 self.from_kall = from_kall
2002
2003
2004 def __eq__(self, other):
2005 if other is ANY:
2006 return True
2007 try:
2008 len_other = len(other)
2009 except TypeError:
2010 return False
2011
2012 self_name = ''
2013 if len(self) == 2:
2014 self_args, self_kwargs = self
2015 else:
2016 self_name, self_args, self_kwargs = self
2017
2018 other_name = ''
2019 if len_other == 0:
2020 other_args, other_kwargs = (), {}
2021 elif len_other == 3:
2022 other_name, other_args, other_kwargs = other
2023 elif len_other == 1:
2024 value, = other
2025 if isinstance(value, tuple):
2026 other_args = value
2027 other_kwargs = {}
2028 elif isinstance(value, str):
2029 other_name = value
2030 other_args, other_kwargs = (), {}
2031 else:
2032 other_args = ()
2033 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002034 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002035 # could be (name, args) or (name, kwargs) or (args, kwargs)
2036 first, second = other
2037 if isinstance(first, str):
2038 other_name = first
2039 if isinstance(second, tuple):
2040 other_args, other_kwargs = second, {}
2041 else:
2042 other_args, other_kwargs = (), second
2043 else:
2044 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002045 else:
2046 return False
Michael Foord345266a2012-03-14 12:24:34 -07002047
2048 if self_name and other_name != self_name:
2049 return False
2050
2051 # this order is important for ANY to work!
2052 return (other_args, other_kwargs) == (self_args, self_kwargs)
2053
2054
Berker Peksagce913872016-03-28 00:30:02 +03002055 __ne__ = object.__ne__
2056
2057
Michael Foord345266a2012-03-14 12:24:34 -07002058 def __call__(self, *args, **kwargs):
2059 if self.name is None:
2060 return _Call(('', args, kwargs), name='()')
2061
2062 name = self.name + '()'
2063 return _Call((self.name, args, kwargs), name=name, parent=self)
2064
2065
2066 def __getattr__(self, attr):
2067 if self.name is None:
2068 return _Call(name=attr, from_kall=False)
2069 name = '%s.%s' % (self.name, attr)
2070 return _Call(name=name, parent=self, from_kall=False)
2071
2072
Kushal Dasa37b9582014-09-16 18:33:37 +05302073 def count(self, *args, **kwargs):
2074 return self.__getattr__('count')(*args, **kwargs)
2075
2076 def index(self, *args, **kwargs):
2077 return self.__getattr__('index')(*args, **kwargs)
2078
Michael Foord345266a2012-03-14 12:24:34 -07002079 def __repr__(self):
2080 if not self.from_kall:
2081 name = self.name or 'call'
2082 if name.startswith('()'):
2083 name = 'call%s' % name
2084 return name
2085
2086 if len(self) == 2:
2087 name = 'call'
2088 args, kwargs = self
2089 else:
2090 name, args, kwargs = self
2091 if not name:
2092 name = 'call'
2093 elif not name.startswith('()'):
2094 name = 'call.%s' % name
2095 else:
2096 name = 'call%s' % name
2097 return _format_call_signature(name, args, kwargs)
2098
2099
2100 def call_list(self):
2101 """For a call object that represents multiple calls, `call_list`
2102 returns a list of all the intermediate calls as well as the
2103 final call."""
2104 vals = []
2105 thing = self
2106 while thing is not None:
2107 if thing.from_kall:
2108 vals.append(thing)
2109 thing = thing.parent
2110 return _CallList(reversed(vals))
2111
2112
2113call = _Call(from_kall=False)
2114
2115
2116
2117def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2118 _name=None, **kwargs):
2119 """Create a mock object using another object as a spec. Attributes on the
2120 mock will use the corresponding attribute on the `spec` object as their
2121 spec.
2122
2123 Functions or methods being mocked will have their arguments checked
2124 to check that they are called with the correct signature.
2125
2126 If `spec_set` is True then attempting to set attributes that don't exist
2127 on the spec object will raise an `AttributeError`.
2128
2129 If a class is used as a spec then the return value of the mock (the
2130 instance of the class) will have the same spec. You can use a class as the
2131 spec for an instance object by passing `instance=True`. The returned mock
2132 will only be callable if instances of the mock are callable.
2133
2134 `create_autospec` also takes arbitrary keyword arguments that are passed to
2135 the constructor of the created mock."""
2136 if _is_list(spec):
2137 # can't pass a list instance to the mock constructor as it will be
2138 # interpreted as a list of strings
2139 spec = type(spec)
2140
2141 is_type = isinstance(spec, type)
2142
2143 _kwargs = {'spec': spec}
2144 if spec_set:
2145 _kwargs = {'spec_set': spec}
2146 elif spec is None:
2147 # None we mock with a normal mock without a spec
2148 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002149 if _kwargs and instance:
2150 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002151
2152 _kwargs.update(kwargs)
2153
2154 Klass = MagicMock
2155 if type(spec) in DescriptorTypes:
2156 # descriptors don't have a spec
2157 # because we don't know what type they return
2158 _kwargs = {}
2159 elif not _callable(spec):
2160 Klass = NonCallableMagicMock
2161 elif is_type and instance and not _instance_callable(spec):
2162 Klass = NonCallableMagicMock
2163
Kushal Das484f8a82014-04-16 01:05:50 +05302164 _name = _kwargs.pop('name', _name)
2165
Michael Foord345266a2012-03-14 12:24:34 -07002166 _new_name = _name
2167 if _parent is None:
2168 # for a top level object no _new_name should be set
2169 _new_name = ''
2170
2171 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2172 name=_name, **_kwargs)
2173
2174 if isinstance(spec, FunctionTypes):
2175 # should only happen at the top level because we don't
2176 # recurse for functions
2177 mock = _set_signature(mock, spec)
2178 else:
2179 _check_signature(spec, mock, is_type, instance)
2180
2181 if _parent is not None and not instance:
2182 _parent._mock_children[_name] = mock
2183
2184 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002185 mock.return_value = create_autospec(spec, spec_set, instance=True,
2186 _name='()', _parent=mock)
2187
2188 for entry in dir(spec):
2189 if _is_magic(entry):
2190 # MagicMock already does the useful magic methods for us
2191 continue
2192
Michael Foord345266a2012-03-14 12:24:34 -07002193 # XXXX do we need a better way of getting attributes without
2194 # triggering code execution (?) Probably not - we need the actual
2195 # object to mock it so we would rather trigger a property than mock
2196 # the property descriptor. Likewise we want to mock out dynamically
2197 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002198 # XXXX what about attributes that raise exceptions other than
2199 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002200 # we could be resilient against it, or catch and propagate the
2201 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002202 try:
2203 original = getattr(spec, entry)
2204 except AttributeError:
2205 continue
Michael Foord345266a2012-03-14 12:24:34 -07002206
2207 kwargs = {'spec': original}
2208 if spec_set:
2209 kwargs = {'spec_set': original}
2210
2211 if not isinstance(original, FunctionTypes):
2212 new = _SpecState(original, spec_set, mock, entry, instance)
2213 mock._mock_children[entry] = new
2214 else:
2215 parent = mock
2216 if isinstance(spec, FunctionTypes):
2217 parent = mock.mock
2218
Michael Foord345266a2012-03-14 12:24:34 -07002219 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002220 kwargs['_eat_self'] = skipfirst
2221 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2222 _new_parent=parent,
2223 **kwargs)
2224 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002225 _check_signature(original, new, skipfirst=skipfirst)
2226
2227 # so functions created with _set_signature become instance attributes,
2228 # *plus* their underlying mock exists in _mock_children of the parent
2229 # mock. Adding to _mock_children may be unnecessary where we are also
2230 # setting as an instance attribute?
2231 if isinstance(new, FunctionTypes):
2232 setattr(mock, entry, new)
2233
2234 return mock
2235
2236
2237def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002238 """
2239 Return whether we should skip the first argument on spec's `entry`
2240 attribute.
2241 """
Michael Foord345266a2012-03-14 12:24:34 -07002242 if not isinstance(spec, type):
2243 if entry in getattr(spec, '__dict__', {}):
2244 # instance attribute - shouldn't skip
2245 return False
Michael Foord345266a2012-03-14 12:24:34 -07002246 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002247
2248 for klass in spec.__mro__:
2249 result = klass.__dict__.get(entry, DEFAULT)
2250 if result is DEFAULT:
2251 continue
2252 if isinstance(result, (staticmethod, classmethod)):
2253 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002254 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2255 # Normal method => skip if looked up on type
2256 # (if looked up on instance, self is already skipped)
2257 return is_type
2258 else:
2259 return False
Michael Foord345266a2012-03-14 12:24:34 -07002260
2261 # shouldn't get here unless function is a dynamically provided attribute
2262 # XXXX untested behaviour
2263 return is_type
2264
2265
2266def _get_class(obj):
2267 try:
2268 return obj.__class__
2269 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002270 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002271 return type(obj)
2272
2273
2274class _SpecState(object):
2275
2276 def __init__(self, spec, spec_set=False, parent=None,
2277 name=None, ids=None, instance=False):
2278 self.spec = spec
2279 self.ids = ids
2280 self.spec_set = spec_set
2281 self.parent = parent
2282 self.instance = instance
2283 self.name = name
2284
2285
2286FunctionTypes = (
2287 # python function
2288 type(create_autospec),
2289 # instance method
2290 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002291)
2292
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002293MethodWrapperTypes = (
2294 type(ANY.__eq__.__get__),
2295)
2296
Michael Foord345266a2012-03-14 12:24:34 -07002297
Michael Foorda74561a2012-03-25 19:03:13 +01002298file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002299
Michael Foord04cbe0c2013-03-19 17:22:51 -07002300def _iterate_read_data(read_data):
2301 # Helper for mock_open:
2302 # Retrieve lines from read_data via a generator so that separate calls to
2303 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002304 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2305 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002306
Berker Peksag86b34da2015-08-06 13:15:51 +03002307 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002308 # If the last line ended in a newline, the list comprehension will have an
2309 # extra entry that's just a newline. Remove this.
2310 data_as_list = data_as_list[:-1]
2311 else:
2312 # If there wasn't an extra newline by itself, then the file being
2313 # emulated doesn't have a newline to end the last line remove the
2314 # newline that our naive format() added
2315 data_as_list[-1] = data_as_list[-1][:-1]
2316
2317 for line in data_as_list:
2318 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002319
Robert Collins5329aaa2015-07-17 20:08:45 +12002320
Michael Foord0dccf652012-03-25 19:11:50 +01002321def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002322 """
2323 A helper function to create a mock to replace the use of `open`. It works
2324 for `open` called directly or used as a context manager.
2325
2326 The `mock` argument is the mock object to configure. If `None` (the
2327 default) then a `MagicMock` will be created for you, with the API limited
2328 to methods or attributes available on standard file handles.
2329
Michael Foord04cbe0c2013-03-19 17:22:51 -07002330 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2331 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002332 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002333 def _readlines_side_effect(*args, **kwargs):
2334 if handle.readlines.return_value is not None:
2335 return handle.readlines.return_value
2336 return list(_state[0])
2337
2338 def _read_side_effect(*args, **kwargs):
2339 if handle.read.return_value is not None:
2340 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002341 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002342
2343 def _readline_side_effect():
2344 if handle.readline.return_value is not None:
2345 while True:
2346 yield handle.readline.return_value
2347 for line in _state[0]:
2348 yield line
Robert Collins9549a3e2016-05-16 15:22:01 +12002349 while True:
2350 yield type(read_data)()
Robert Collinsca647ef2015-07-24 03:48:20 +12002351
2352
Michael Foorda74561a2012-03-25 19:03:13 +01002353 global file_spec
2354 if file_spec is None:
2355 import _io
2356 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2357
Michael Foord345266a2012-03-14 12:24:34 -07002358 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002359 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002360
Robert Collinsca647ef2015-07-24 03:48:20 +12002361 handle = MagicMock(spec=file_spec)
2362 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002363
Robert Collinsca647ef2015-07-24 03:48:20 +12002364 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002365
Robert Collinsca647ef2015-07-24 03:48:20 +12002366 handle.write.return_value = None
2367 handle.read.return_value = None
2368 handle.readline.return_value = None
2369 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002370
Robert Collinsca647ef2015-07-24 03:48:20 +12002371 handle.read.side_effect = _read_side_effect
2372 _state[1] = _readline_side_effect()
2373 handle.readline.side_effect = _state[1]
2374 handle.readlines.side_effect = _readlines_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002375
Robert Collinsca647ef2015-07-24 03:48:20 +12002376 def reset_data(*args, **kwargs):
2377 _state[0] = _iterate_read_data(read_data)
2378 if handle.readline.side_effect == _state[1]:
2379 # Only reset the side effect if the user hasn't overridden it.
2380 _state[1] = _readline_side_effect()
2381 handle.readline.side_effect = _state[1]
2382 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002383
Robert Collinsca647ef2015-07-24 03:48:20 +12002384 mock.side_effect = reset_data
2385 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002386 return mock
2387
2388
2389class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002390 """
2391 A mock intended to be used as a property, or other descriptor, on a class.
2392 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2393 a return value when it is fetched.
2394
2395 Fetching a `PropertyMock` instance from an object calls the mock, with
2396 no args. Setting it calls the mock with the value being set.
2397 """
Michael Foordc2870622012-04-13 16:57:22 +01002398 def _get_child_mock(self, **kwargs):
2399 return MagicMock(**kwargs)
2400
Michael Foord345266a2012-03-14 12:24:34 -07002401 def __get__(self, obj, obj_type):
2402 return self()
2403 def __set__(self, obj, val):
2404 self(val)