blob: eaa9c3d5850e33a7043651f6831ca7a2976fa52e [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
Antoine Pitrou5c64df72013-02-03 00:23:58 +010063def _get_signature_object(func, as_instance, eat_self):
64 """
65 Given an arbitrary, possibly callable object, try to create a suitable
66 signature object.
67 Return a (reduced func, signature) tuple, or None.
68 """
69 if isinstance(func, type) and not as_instance:
70 # If it's a type and should be modelled as a type, use __init__.
Michael Foord345266a2012-03-14 12:24:34 -070071 try:
72 func = func.__init__
73 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010074 return None
75 # Skip the `self` argument in __init__
76 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070077 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010078 # If we really want to model an instance of the passed type,
79 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070080 try:
81 func = func.__call__
82 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010083 return None
84 if eat_self:
85 sig_func = partial(func, None)
86 else:
87 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -070088 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010089 return func, inspect.signature(sig_func)
90 except ValueError:
91 # Certain callable types are not supported by inspect.signature()
92 return None
Michael Foord345266a2012-03-14 12:24:34 -070093
94
95def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010096 sig = _get_signature_object(func, instance, skipfirst)
97 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -070098 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +010099 func, sig = sig
100 def checksig(_mock_self, *args, **kwargs):
101 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700102 _copy_func_details(func, checksig)
103 type(mock)._mock_check_sig = checksig
104
105
106def _copy_func_details(func, funcopy):
107 funcopy.__name__ = func.__name__
108 funcopy.__doc__ = func.__doc__
Larry Hastings5c661892014-01-24 06:17:25 -0800109 try:
110 funcopy.__text_signature__ = func.__text_signature__
111 except AttributeError:
112 pass
Michael Foord345266a2012-03-14 12:24:34 -0700113 # we explicitly don't copy func.__dict__ into this copy as it would
114 # expose original attributes that should be mocked
Larry Hastings5c661892014-01-24 06:17:25 -0800115 try:
116 funcopy.__module__ = func.__module__
117 except AttributeError:
118 pass
119 try:
120 funcopy.__defaults__ = func.__defaults__
121 except AttributeError:
122 pass
123 try:
124 funcopy.__kwdefaults__ = func.__kwdefaults__
125 except AttributeError:
126 pass
Michael Foord345266a2012-03-14 12:24:34 -0700127
128
129def _callable(obj):
130 if isinstance(obj, type):
131 return True
132 if getattr(obj, '__call__', None) is not None:
133 return True
134 return False
135
136
137def _is_list(obj):
138 # checks for list or tuples
139 # XXXX badly named!
140 return type(obj) in (list, tuple)
141
142
143def _instance_callable(obj):
144 """Given an object, return True if the object is callable.
145 For classes, return True if instances would be callable."""
146 if not isinstance(obj, type):
147 # already an instance
148 return getattr(obj, '__call__', None) is not None
149
Michael Foorda74b3aa2012-03-14 14:40:22 -0700150 # *could* be broken by a class overriding __mro__ or __dict__ via
151 # a metaclass
152 for base in (obj,) + obj.__mro__:
153 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700154 return True
155 return False
156
157
158def _set_signature(mock, original, instance=False):
159 # creates a function with signature (*args, **kwargs) that delegates to a
160 # mock. It still does signature checking by calling a lambda with the same
161 # signature as the original.
162 if not _callable(original):
163 return
164
165 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100166 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700167 if result is None:
Michael Foord345266a2012-03-14 12:24:34 -0700168 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100169 func, sig = result
170 def checksig(*args, **kwargs):
171 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700172 _copy_func_details(func, checksig)
173
174 name = original.__name__
175 if not name.isidentifier():
176 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100177 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700178 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100179 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700180 return mock(*args, **kwargs)""" % name
181 exec (src, context)
182 funcopy = context[name]
183 _setup_func(funcopy, mock)
184 return funcopy
185
186
187def _setup_func(funcopy, mock):
188 funcopy.mock = mock
189
190 # can't use isinstance with mocks
191 if not _is_instance_mock(mock):
192 return
193
194 def assert_called_with(*args, **kwargs):
195 return mock.assert_called_with(*args, **kwargs)
196 def assert_called_once_with(*args, **kwargs):
197 return mock.assert_called_once_with(*args, **kwargs)
198 def assert_has_calls(*args, **kwargs):
199 return mock.assert_has_calls(*args, **kwargs)
200 def assert_any_call(*args, **kwargs):
201 return mock.assert_any_call(*args, **kwargs)
202 def reset_mock():
203 funcopy.method_calls = _CallList()
204 funcopy.mock_calls = _CallList()
205 mock.reset_mock()
206 ret = funcopy.return_value
207 if _is_instance_mock(ret) and not ret is mock:
208 ret.reset_mock()
209
210 funcopy.called = False
211 funcopy.call_count = 0
212 funcopy.call_args = None
213 funcopy.call_args_list = _CallList()
214 funcopy.method_calls = _CallList()
215 funcopy.mock_calls = _CallList()
216
217 funcopy.return_value = mock.return_value
218 funcopy.side_effect = mock.side_effect
219 funcopy._mock_children = mock._mock_children
220
221 funcopy.assert_called_with = assert_called_with
222 funcopy.assert_called_once_with = assert_called_once_with
223 funcopy.assert_has_calls = assert_has_calls
224 funcopy.assert_any_call = assert_any_call
225 funcopy.reset_mock = reset_mock
226
227 mock._mock_delegate = funcopy
228
229
230def _is_magic(name):
231 return '__%s__' % name[2:-2] == name
232
233
234class _SentinelObject(object):
235 "A unique, named, sentinel object."
236 def __init__(self, name):
237 self.name = name
238
239 def __repr__(self):
240 return 'sentinel.%s' % self.name
241
242
243class _Sentinel(object):
244 """Access attributes to return a named object, usable as a sentinel."""
245 def __init__(self):
246 self._sentinels = {}
247
248 def __getattr__(self, name):
249 if name == '__bases__':
250 # Without this help(unittest.mock) raises an exception
251 raise AttributeError
252 return self._sentinels.setdefault(name, _SentinelObject(name))
253
254
255sentinel = _Sentinel()
256
257DEFAULT = sentinel.DEFAULT
258_missing = sentinel.MISSING
259_deleted = sentinel.DELETED
260
261
Michael Foord345266a2012-03-14 12:24:34 -0700262def _copy(value):
263 if type(value) in (dict, list, tuple, set):
264 return type(value)(value)
265 return value
266
267
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200268_allowed_names = {
269 'return_value', '_mock_return_value', 'side_effect',
270 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
271 '_mock_name', '_mock_new_name'
272}
Michael Foord345266a2012-03-14 12:24:34 -0700273
274
275def _delegating_property(name):
276 _allowed_names.add(name)
277 _the_name = '_mock_' + name
278 def _get(self, name=name, _the_name=_the_name):
279 sig = self._mock_delegate
280 if sig is None:
281 return getattr(self, _the_name)
282 return getattr(sig, name)
283 def _set(self, value, name=name, _the_name=_the_name):
284 sig = self._mock_delegate
285 if sig is None:
286 self.__dict__[_the_name] = value
287 else:
288 setattr(sig, name, value)
289
290 return property(_get, _set)
291
292
293
294class _CallList(list):
295
296 def __contains__(self, value):
297 if not isinstance(value, list):
298 return list.__contains__(self, value)
299 len_value = len(value)
300 len_self = len(self)
301 if len_value > len_self:
302 return False
303
304 for i in range(0, len_self - len_value + 1):
305 sub_list = self[i:i+len_value]
306 if sub_list == value:
307 return True
308 return False
309
310 def __repr__(self):
311 return pprint.pformat(list(self))
312
313
314def _check_and_set_parent(parent, value, name, new_name):
315 if not _is_instance_mock(value):
316 return False
317 if ((value._mock_name or value._mock_new_name) or
318 (value._mock_parent is not None) or
319 (value._mock_new_parent is not None)):
320 return False
321
322 _parent = parent
323 while _parent is not None:
324 # setting a mock (value) as a child or return value of itself
325 # should not modify the mock
326 if _parent is value:
327 return False
328 _parent = _parent._mock_new_parent
329
330 if new_name:
331 value._mock_new_parent = parent
332 value._mock_new_name = new_name
333 if name:
334 value._mock_parent = parent
335 value._mock_name = name
336 return True
337
Michael Foord01bafdc2014-04-14 16:09:42 -0400338# Internal class to identify if we wrapped an iterator object or not.
339class _MockIter(object):
340 def __init__(self, obj):
341 self.obj = iter(obj)
342 def __iter__(self):
343 return self
344 def __next__(self):
345 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700346
347class Base(object):
348 _mock_return_value = DEFAULT
349 _mock_side_effect = None
350 def __init__(self, *args, **kwargs):
351 pass
352
353
354
355class NonCallableMock(Base):
356 """A non-callable version of `Mock`"""
357
358 def __new__(cls, *args, **kw):
359 # every instance has its own class
360 # so we can create magic methods on the
361 # class without stomping on other mocks
362 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
363 instance = object.__new__(new)
364 return instance
365
366
367 def __init__(
368 self, spec=None, wraps=None, name=None, spec_set=None,
369 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530370 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700371 ):
372 if _new_parent is None:
373 _new_parent = parent
374
375 __dict__ = self.__dict__
376 __dict__['_mock_parent'] = parent
377 __dict__['_mock_name'] = name
378 __dict__['_mock_new_name'] = _new_name
379 __dict__['_mock_new_parent'] = _new_parent
380
381 if spec_set is not None:
382 spec = spec_set
383 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100384 if _eat_self is None:
385 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700386
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100387 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700388
389 __dict__['_mock_children'] = {}
390 __dict__['_mock_wraps'] = wraps
391 __dict__['_mock_delegate'] = None
392
393 __dict__['_mock_called'] = False
394 __dict__['_mock_call_args'] = None
395 __dict__['_mock_call_count'] = 0
396 __dict__['_mock_call_args_list'] = _CallList()
397 __dict__['_mock_mock_calls'] = _CallList()
398
399 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530400 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700401
402 if kwargs:
403 self.configure_mock(**kwargs)
404
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000405 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700406 spec, wraps, name, spec_set, parent,
407 _spec_state
408 )
409
410
411 def attach_mock(self, mock, attribute):
412 """
413 Attach a mock as an attribute of this one, replacing its name and
414 parent. Calls to the attached mock will be recorded in the
415 `method_calls` and `mock_calls` attributes of this one."""
416 mock._mock_parent = None
417 mock._mock_new_parent = None
418 mock._mock_name = ''
419 mock._mock_new_name = None
420
421 setattr(self, attribute, mock)
422
423
424 def mock_add_spec(self, spec, spec_set=False):
425 """Add a spec to a mock. `spec` can either be an object or a
426 list of strings. Only attributes on the `spec` can be fetched as
427 attributes from the mock.
428
429 If `spec_set` is True then only attributes on the spec can be set."""
430 self._mock_add_spec(spec, spec_set)
431
432
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100433 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
434 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700435 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100436 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700437
438 if spec is not None and not _is_list(spec):
439 if isinstance(spec, type):
440 _spec_class = spec
441 else:
442 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100443 res = _get_signature_object(spec,
444 _spec_as_instance, _eat_self)
445 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700446
447 spec = dir(spec)
448
449 __dict__ = self.__dict__
450 __dict__['_spec_class'] = _spec_class
451 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100452 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700453 __dict__['_mock_methods'] = spec
454
455
456 def __get_return_value(self):
457 ret = self._mock_return_value
458 if self._mock_delegate is not None:
459 ret = self._mock_delegate.return_value
460
461 if ret is DEFAULT:
462 ret = self._get_child_mock(
463 _new_parent=self, _new_name='()'
464 )
465 self.return_value = ret
466 return ret
467
468
469 def __set_return_value(self, value):
470 if self._mock_delegate is not None:
471 self._mock_delegate.return_value = value
472 else:
473 self._mock_return_value = value
474 _check_and_set_parent(self, value, None, '()')
475
476 __return_value_doc = "The value to be returned when the mock is called."
477 return_value = property(__get_return_value, __set_return_value,
478 __return_value_doc)
479
480
481 @property
482 def __class__(self):
483 if self._spec_class is None:
484 return type(self)
485 return self._spec_class
486
487 called = _delegating_property('called')
488 call_count = _delegating_property('call_count')
489 call_args = _delegating_property('call_args')
490 call_args_list = _delegating_property('call_args_list')
491 mock_calls = _delegating_property('mock_calls')
492
493
494 def __get_side_effect(self):
495 delegated = self._mock_delegate
496 if delegated is None:
497 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400498 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200499 if (sf is not None and not callable(sf)
500 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400501 sf = _MockIter(sf)
502 delegated.side_effect = sf
503 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700504
505 def __set_side_effect(self, value):
506 value = _try_iter(value)
507 delegated = self._mock_delegate
508 if delegated is None:
509 self._mock_side_effect = value
510 else:
511 delegated.side_effect = value
512
513 side_effect = property(__get_side_effect, __set_side_effect)
514
515
Kushal Das9cd39a12016-06-02 10:20:16 -0700516 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700517 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200518 if visited is None:
519 visited = []
520 if id(self) in visited:
521 return
522 visited.append(id(self))
523
Michael Foord345266a2012-03-14 12:24:34 -0700524 self.called = False
525 self.call_args = None
526 self.call_count = 0
527 self.mock_calls = _CallList()
528 self.call_args_list = _CallList()
529 self.method_calls = _CallList()
530
Kushal Das9cd39a12016-06-02 10:20:16 -0700531 if return_value:
532 self._mock_return_value = DEFAULT
533 if side_effect:
534 self._mock_side_effect = None
535
Michael Foord345266a2012-03-14 12:24:34 -0700536 for child in self._mock_children.values():
Michael Foord75963642012-06-09 17:31:59 +0100537 if isinstance(child, _SpecState):
538 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200539 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700540
541 ret = self._mock_return_value
542 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200543 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700544
545
546 def configure_mock(self, **kwargs):
547 """Set attributes on the mock through keyword arguments.
548
549 Attributes plus return values and side effects can be set on child
550 mocks using standard dot notation and unpacking a dictionary in the
551 method call:
552
553 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
554 >>> mock.configure_mock(**attrs)"""
555 for arg, val in sorted(kwargs.items(),
556 # we sort on the number of dots so that
557 # attributes are set before we set attributes on
558 # attributes
559 key=lambda entry: entry[0].count('.')):
560 args = arg.split('.')
561 final = args.pop()
562 obj = self
563 for entry in args:
564 obj = getattr(obj, entry)
565 setattr(obj, final, val)
566
567
568 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530569 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700570 raise AttributeError(name)
571 elif self._mock_methods is not None:
572 if name not in self._mock_methods or name in _all_magics:
573 raise AttributeError("Mock object has no attribute %r" % name)
574 elif _is_magic(name):
575 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530576 if not self._mock_unsafe:
577 if name.startswith(('assert', 'assret')):
578 raise AttributeError(name)
Michael Foord345266a2012-03-14 12:24:34 -0700579
580 result = self._mock_children.get(name)
581 if result is _deleted:
582 raise AttributeError(name)
583 elif result is None:
584 wraps = None
585 if self._mock_wraps is not None:
586 # XXXX should we get the attribute without triggering code
587 # execution?
588 wraps = getattr(self._mock_wraps, name)
589
590 result = self._get_child_mock(
591 parent=self, name=name, wraps=wraps, _new_name=name,
592 _new_parent=self
593 )
594 self._mock_children[name] = result
595
596 elif isinstance(result, _SpecState):
597 result = create_autospec(
598 result.spec, result.spec_set, result.instance,
599 result.parent, result.name
600 )
601 self._mock_children[name] = result
602
603 return result
604
605
606 def __repr__(self):
607 _name_list = [self._mock_new_name]
608 _parent = self._mock_new_parent
609 last = self
610
611 dot = '.'
612 if _name_list == ['()']:
613 dot = ''
614 seen = set()
615 while _parent is not None:
616 last = _parent
617
618 _name_list.append(_parent._mock_new_name + dot)
619 dot = '.'
620 if _parent._mock_new_name == '()':
621 dot = ''
622
623 _parent = _parent._mock_new_parent
624
625 # use ids here so as not to call __hash__ on the mocks
626 if id(_parent) in seen:
627 break
628 seen.add(id(_parent))
629
630 _name_list = list(reversed(_name_list))
631 _first = last._mock_name or 'mock'
632 if len(_name_list) > 1:
633 if _name_list[1] not in ('()', '().'):
634 _first += '.'
635 _name_list[0] = _first
636 name = ''.join(_name_list)
637
638 name_string = ''
639 if name not in ('mock', 'mock.'):
640 name_string = ' name=%r' % name
641
642 spec_string = ''
643 if self._spec_class is not None:
644 spec_string = ' spec=%r'
645 if self._spec_set:
646 spec_string = ' spec_set=%r'
647 spec_string = spec_string % self._spec_class.__name__
648 return "<%s%s%s id='%s'>" % (
649 type(self).__name__,
650 name_string,
651 spec_string,
652 id(self)
653 )
654
655
656 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700657 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100658 if not FILTER_DIR:
659 return object.__dir__(self)
660
Michael Foord345266a2012-03-14 12:24:34 -0700661 extras = self._mock_methods or []
662 from_type = dir(type(self))
663 from_dict = list(self.__dict__)
664
Michael Foord313f85f2012-03-25 18:16:07 +0100665 from_type = [e for e in from_type if not e.startswith('_')]
666 from_dict = [e for e in from_dict if not e.startswith('_') or
667 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700668 return sorted(set(extras + from_type + from_dict +
669 list(self._mock_children)))
670
671
672 def __setattr__(self, name, value):
673 if name in _allowed_names:
674 # property setters go through here
675 return object.__setattr__(self, name, value)
676 elif (self._spec_set and self._mock_methods is not None and
677 name not in self._mock_methods and
678 name not in self.__dict__):
679 raise AttributeError("Mock object has no attribute '%s'" % name)
680 elif name in _unsupported_magics:
681 msg = 'Attempting to set unsupported magic method %r.' % name
682 raise AttributeError(msg)
683 elif name in _all_magics:
684 if self._mock_methods is not None and name not in self._mock_methods:
685 raise AttributeError("Mock object has no attribute '%s'" % name)
686
687 if not _is_instance_mock(value):
688 setattr(type(self), name, _get_method(name, value))
689 original = value
690 value = lambda *args, **kw: original(self, *args, **kw)
691 else:
692 # only set _new_name and not name so that mock_calls is tracked
693 # but not method calls
694 _check_and_set_parent(self, value, None, name)
695 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100696 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700697 elif name == '__class__':
698 self._spec_class = value
699 return
700 else:
701 if _check_and_set_parent(self, value, name, name):
702 self._mock_children[name] = value
703 return object.__setattr__(self, name, value)
704
705
706 def __delattr__(self, name):
707 if name in _all_magics and name in type(self).__dict__:
708 delattr(type(self), name)
709 if name not in self.__dict__:
710 # for magic methods that are still MagicProxy objects and
711 # not set on the instance itself
712 return
713
714 if name in self.__dict__:
715 object.__delattr__(self, name)
716
717 obj = self._mock_children.get(name, _missing)
718 if obj is _deleted:
719 raise AttributeError(name)
720 if obj is not _missing:
721 del self._mock_children[name]
722 self._mock_children[name] = _deleted
723
724
Michael Foord345266a2012-03-14 12:24:34 -0700725 def _format_mock_call_signature(self, args, kwargs):
726 name = self._mock_name or 'mock'
727 return _format_call_signature(name, args, kwargs)
728
729
730 def _format_mock_failure_message(self, args, kwargs):
731 message = 'Expected call: %s\nActual call: %s'
732 expected_string = self._format_mock_call_signature(args, kwargs)
733 call_args = self.call_args
734 if len(call_args) == 3:
735 call_args = call_args[1:]
736 actual_string = self._format_mock_call_signature(*call_args)
737 return message % (expected_string, actual_string)
738
739
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100740 def _call_matcher(self, _call):
741 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000742 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100743 comparison key suitable for matching with other calls.
744 This is a best effort method which relies on the spec's signature,
745 if available, or falls back on the arguments themselves.
746 """
747 sig = self._spec_signature
748 if sig is not None:
749 if len(_call) == 2:
750 name = ''
751 args, kwargs = _call
752 else:
753 name, args, kwargs = _call
754 try:
755 return name, sig.bind(*args, **kwargs)
756 except TypeError as e:
757 return e.with_traceback(None)
758 else:
759 return _call
760
Kushal Das68290f42014-04-17 01:54:07 +0530761 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530762 """assert that the mock was never called.
763 """
764 self = _mock_self
765 if self.call_count != 0:
766 msg = ("Expected '%s' to not have been called. Called %s times." %
767 (self._mock_name or 'mock', self.call_count))
768 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100769
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100770 def assert_called(_mock_self):
771 """assert that the mock was called at least once
772 """
773 self = _mock_self
774 if self.call_count == 0:
775 msg = ("Expected '%s' to have been called." %
776 self._mock_name or 'mock')
777 raise AssertionError(msg)
778
779 def assert_called_once(_mock_self):
780 """assert that the mock was called only once.
781 """
782 self = _mock_self
783 if not self.call_count == 1:
784 msg = ("Expected '%s' to have been called once. Called %s times." %
785 (self._mock_name or 'mock', self.call_count))
786 raise AssertionError(msg)
787
Michael Foord345266a2012-03-14 12:24:34 -0700788 def assert_called_with(_mock_self, *args, **kwargs):
789 """assert that the mock was called with the specified arguments.
790
791 Raises an AssertionError if the args and keyword args passed in are
792 different to the last call to the mock."""
793 self = _mock_self
794 if self.call_args is None:
795 expected = self._format_mock_call_signature(args, kwargs)
796 raise AssertionError('Expected call: %s\nNot called' % (expected,))
797
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100798 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700799 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100800 return msg
801 expected = self._call_matcher((args, kwargs))
802 actual = self._call_matcher(self.call_args)
803 if expected != actual:
804 cause = expected if isinstance(expected, Exception) else None
805 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700806
807
808 def assert_called_once_with(_mock_self, *args, **kwargs):
809 """assert that the mock was called exactly once and with the specified
810 arguments."""
811 self = _mock_self
812 if not self.call_count == 1:
Michael Foord28d591c2012-09-28 16:15:22 +0100813 msg = ("Expected '%s' to be called once. Called %s times." %
814 (self._mock_name or 'mock', self.call_count))
Michael Foord345266a2012-03-14 12:24:34 -0700815 raise AssertionError(msg)
816 return self.assert_called_with(*args, **kwargs)
817
818
819 def assert_has_calls(self, calls, any_order=False):
820 """assert the mock has been called with the specified calls.
821 The `mock_calls` list is checked for the calls.
822
823 If `any_order` is False (the default) then the calls must be
824 sequential. There can be extra calls before or after the
825 specified calls.
826
827 If `any_order` is True then the calls can be in any order, but
828 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100829 expected = [self._call_matcher(c) for c in calls]
830 cause = expected if isinstance(expected, Exception) else None
831 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700832 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100833 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700834 raise AssertionError(
835 'Calls not found.\nExpected: %r\n'
Senthil Kumaran121edbf2016-01-12 06:18:32 -0800836 'Actual: %r' % (_CallList(calls), self.mock_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100837 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700838 return
839
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100840 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700841
842 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100843 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700844 try:
845 all_calls.remove(kall)
846 except ValueError:
847 not_found.append(kall)
848 if not_found:
849 raise AssertionError(
850 '%r not all found in call list' % (tuple(not_found),)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100851 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700852
853
854 def assert_any_call(self, *args, **kwargs):
855 """assert the mock has been called with the specified arguments.
856
857 The assert passes if the mock has *ever* been called, unlike
858 `assert_called_with` and `assert_called_once_with` that only pass if
859 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100860 expected = self._call_matcher((args, kwargs))
861 actual = [self._call_matcher(c) for c in self.call_args_list]
862 if expected not in actual:
863 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700864 expected_string = self._format_mock_call_signature(args, kwargs)
865 raise AssertionError(
866 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100867 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700868
869
870 def _get_child_mock(self, **kw):
871 """Create the child mocks for attributes and return value.
872 By default child mocks will be the same type as the parent.
873 Subclasses of Mock may want to override this to customize the way
874 child mocks are made.
875
876 For non-callable mocks the callable variant will be used (rather than
877 any custom subclass)."""
878 _type = type(self)
879 if not issubclass(_type, CallableMixin):
880 if issubclass(_type, NonCallableMagicMock):
881 klass = MagicMock
882 elif issubclass(_type, NonCallableMock) :
883 klass = Mock
884 else:
885 klass = _type.__mro__[1]
886 return klass(**kw)
887
888
889
890def _try_iter(obj):
891 if obj is None:
892 return obj
893 if _is_exception(obj):
894 return obj
895 if _callable(obj):
896 return obj
897 try:
898 return iter(obj)
899 except TypeError:
900 # XXXX backwards compatibility
901 # but this will blow up on first call - so maybe we should fail early?
902 return obj
903
904
905
906class CallableMixin(Base):
907
908 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
909 wraps=None, name=None, spec_set=None, parent=None,
910 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
911 self.__dict__['_mock_return_value'] = return_value
912
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000913 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700914 spec, wraps, name, spec_set, parent,
915 _spec_state, _new_name, _new_parent, **kwargs
916 )
917
918 self.side_effect = side_effect
919
920
921 def _mock_check_sig(self, *args, **kwargs):
922 # stub method that can be replaced with one with a specific signature
923 pass
924
925
926 def __call__(_mock_self, *args, **kwargs):
927 # can't use self in-case a function / method we are mocking uses self
928 # in the signature
929 _mock_self._mock_check_sig(*args, **kwargs)
930 return _mock_self._mock_call(*args, **kwargs)
931
932
933 def _mock_call(_mock_self, *args, **kwargs):
934 self = _mock_self
935 self.called = True
936 self.call_count += 1
Michael Foord345266a2012-03-14 12:24:34 -0700937 _new_name = self._mock_new_name
938 _new_parent = self._mock_new_parent
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100939
940 _call = _Call((args, kwargs), two=True)
941 self.call_args = _call
942 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700943 self.mock_calls.append(_Call(('', args, kwargs)))
944
945 seen = set()
946 skip_next_dot = _new_name == '()'
947 do_method_calls = self._mock_parent is not None
948 name = self._mock_name
949 while _new_parent is not None:
950 this_mock_call = _Call((_new_name, args, kwargs))
951 if _new_parent._mock_new_name:
952 dot = '.'
953 if skip_next_dot:
954 dot = ''
955
956 skip_next_dot = False
957 if _new_parent._mock_new_name == '()':
958 skip_next_dot = True
959
960 _new_name = _new_parent._mock_new_name + dot + _new_name
961
962 if do_method_calls:
963 if _new_name == name:
964 this_method_call = this_mock_call
965 else:
966 this_method_call = _Call((name, args, kwargs))
967 _new_parent.method_calls.append(this_method_call)
968
969 do_method_calls = _new_parent._mock_parent is not None
970 if do_method_calls:
971 name = _new_parent._mock_name + '.' + name
972
973 _new_parent.mock_calls.append(this_mock_call)
974 _new_parent = _new_parent._mock_new_parent
975
976 # use ids here so as not to call __hash__ on the mocks
977 _new_parent_id = id(_new_parent)
978 if _new_parent_id in seen:
979 break
980 seen.add(_new_parent_id)
981
982 ret_val = DEFAULT
983 effect = self.side_effect
984 if effect is not None:
985 if _is_exception(effect):
986 raise effect
987
988 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +0100989 result = next(effect)
990 if _is_exception(result):
991 raise result
Andrew Svetlov8b2cd752013-04-07 16:42:24 +0300992 if result is DEFAULT:
993 result = self.return_value
Michael Foord2cd48732012-04-21 15:52:11 +0100994 return result
Michael Foord345266a2012-03-14 12:24:34 -0700995
996 ret_val = effect(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700997
998 if (self._mock_wraps is not None and
999 self._mock_return_value is DEFAULT):
1000 return self._mock_wraps(*args, **kwargs)
1001 if ret_val is DEFAULT:
1002 ret_val = self.return_value
1003 return ret_val
1004
1005
1006
1007class Mock(CallableMixin, NonCallableMock):
1008 """
1009 Create a new `Mock` object. `Mock` takes several optional arguments
1010 that specify the behaviour of the Mock object:
1011
1012 * `spec`: This can be either a list of strings or an existing object (a
1013 class or instance) that acts as the specification for the mock object. If
1014 you pass in an object then a list of strings is formed by calling dir on
1015 the object (excluding unsupported magic attributes and methods). Accessing
1016 any attribute not in this list will raise an `AttributeError`.
1017
1018 If `spec` is an object (rather than a list of strings) then
1019 `mock.__class__` returns the class of the spec object. This allows mocks
1020 to pass `isinstance` tests.
1021
1022 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1023 or get an attribute on the mock that isn't on the object passed as
1024 `spec_set` will raise an `AttributeError`.
1025
1026 * `side_effect`: A function to be called whenever the Mock is called. See
1027 the `side_effect` attribute. Useful for raising exceptions or
1028 dynamically changing return values. The function is called with the same
1029 arguments as the mock, and unless it returns `DEFAULT`, the return
1030 value of this function is used as the return value.
1031
Michael Foord2cd48732012-04-21 15:52:11 +01001032 If `side_effect` is an iterable then each call to the mock will return
1033 the next value from the iterable. If any of the members of the iterable
1034 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001035
Michael Foord345266a2012-03-14 12:24:34 -07001036 * `return_value`: The value returned when the mock is called. By default
1037 this is a new Mock (created on first access). See the
1038 `return_value` attribute.
1039
Michael Foord0682a0c2012-04-13 20:51:20 +01001040 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1041 calling the Mock will pass the call through to the wrapped object
1042 (returning the real result). Attribute access on the mock will return a
1043 Mock object that wraps the corresponding attribute of the wrapped object
1044 (so attempting to access an attribute that doesn't exist will raise an
1045 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001046
1047 If the mock has an explicit `return_value` set then calls are not passed
1048 to the wrapped object and the `return_value` is returned instead.
1049
1050 * `name`: If the mock has a name then it will be used in the repr of the
1051 mock. This can be useful for debugging. The name is propagated to child
1052 mocks.
1053
1054 Mocks can also be called with arbitrary keyword arguments. These will be
1055 used to set attributes on the mock after it is created.
1056 """
1057
1058
1059
1060def _dot_lookup(thing, comp, import_path):
1061 try:
1062 return getattr(thing, comp)
1063 except AttributeError:
1064 __import__(import_path)
1065 return getattr(thing, comp)
1066
1067
1068def _importer(target):
1069 components = target.split('.')
1070 import_path = components.pop(0)
1071 thing = __import__(import_path)
1072
1073 for comp in components:
1074 import_path += ".%s" % comp
1075 thing = _dot_lookup(thing, comp, import_path)
1076 return thing
1077
1078
1079def _is_started(patcher):
1080 # XXXX horrible
1081 return hasattr(patcher, 'is_local')
1082
1083
1084class _patch(object):
1085
1086 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001087 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001088
1089 def __init__(
1090 self, getter, attribute, new, spec, create,
1091 spec_set, autospec, new_callable, kwargs
1092 ):
1093 if new_callable is not None:
1094 if new is not DEFAULT:
1095 raise ValueError(
1096 "Cannot use 'new' and 'new_callable' together"
1097 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001098 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001099 raise ValueError(
1100 "Cannot use 'autospec' and 'new_callable' together"
1101 )
1102
1103 self.getter = getter
1104 self.attribute = attribute
1105 self.new = new
1106 self.new_callable = new_callable
1107 self.spec = spec
1108 self.create = create
1109 self.has_local = False
1110 self.spec_set = spec_set
1111 self.autospec = autospec
1112 self.kwargs = kwargs
1113 self.additional_patchers = []
1114
1115
1116 def copy(self):
1117 patcher = _patch(
1118 self.getter, self.attribute, self.new, self.spec,
1119 self.create, self.spec_set,
1120 self.autospec, self.new_callable, self.kwargs
1121 )
1122 patcher.attribute_name = self.attribute_name
1123 patcher.additional_patchers = [
1124 p.copy() for p in self.additional_patchers
1125 ]
1126 return patcher
1127
1128
1129 def __call__(self, func):
1130 if isinstance(func, type):
1131 return self.decorate_class(func)
1132 return self.decorate_callable(func)
1133
1134
1135 def decorate_class(self, klass):
1136 for attr in dir(klass):
1137 if not attr.startswith(patch.TEST_PREFIX):
1138 continue
1139
1140 attr_value = getattr(klass, attr)
1141 if not hasattr(attr_value, "__call__"):
1142 continue
1143
1144 patcher = self.copy()
1145 setattr(klass, attr, patcher(attr_value))
1146 return klass
1147
1148
1149 def decorate_callable(self, func):
1150 if hasattr(func, 'patchings'):
1151 func.patchings.append(self)
1152 return func
1153
1154 @wraps(func)
1155 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001156 extra_args = []
1157 entered_patchers = []
1158
Michael Foord50a8c0e2012-03-25 18:57:58 +01001159 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001160 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001161 for patching in patched.patchings:
1162 arg = patching.__enter__()
1163 entered_patchers.append(patching)
1164 if patching.attribute_name is not None:
1165 keywargs.update(arg)
1166 elif patching.new is DEFAULT:
1167 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001168
Michael Foordd7c65e22012-03-14 14:56:54 -07001169 args += tuple(extra_args)
1170 return func(*args, **keywargs)
1171 except:
1172 if (patching not in entered_patchers and
1173 _is_started(patching)):
1174 # the patcher may have been started, but an exception
1175 # raised whilst entering one of its additional_patchers
1176 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001177 # Pass the exception to __exit__
1178 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001179 # re-raise the exception
1180 raise
Michael Foord345266a2012-03-14 12:24:34 -07001181 finally:
1182 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001183 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001184
1185 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001186 return patched
1187
1188
1189 def get_original(self):
1190 target = self.getter()
1191 name = self.attribute
1192
1193 original = DEFAULT
1194 local = False
1195
1196 try:
1197 original = target.__dict__[name]
1198 except (AttributeError, KeyError):
1199 original = getattr(target, name, DEFAULT)
1200 else:
1201 local = True
1202
Michael Foordfddcfa22014-04-14 16:25:20 -04001203 if name in _builtins and isinstance(target, ModuleType):
1204 self.create = True
1205
Michael Foord345266a2012-03-14 12:24:34 -07001206 if not self.create and original is DEFAULT:
1207 raise AttributeError(
1208 "%s does not have the attribute %r" % (target, name)
1209 )
1210 return original, local
1211
1212
1213 def __enter__(self):
1214 """Perform the patch."""
1215 new, spec, spec_set = self.new, self.spec, self.spec_set
1216 autospec, kwargs = self.autospec, self.kwargs
1217 new_callable = self.new_callable
1218 self.target = self.getter()
1219
Michael Foord50a8c0e2012-03-25 18:57:58 +01001220 # normalise False to None
1221 if spec is False:
1222 spec = None
1223 if spec_set is False:
1224 spec_set = None
1225 if autospec is False:
1226 autospec = None
1227
1228 if spec is not None and autospec is not None:
1229 raise TypeError("Can't specify spec and autospec")
1230 if ((spec is not None or autospec is not None) and
1231 spec_set not in (True, None)):
1232 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1233
Michael Foord345266a2012-03-14 12:24:34 -07001234 original, local = self.get_original()
1235
Michael Foord50a8c0e2012-03-25 18:57:58 +01001236 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001237 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001238 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001239 # set spec to the object we are replacing
1240 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001241 if spec_set is True:
1242 spec_set = original
1243 spec = None
1244 elif spec is not None:
1245 if spec_set is True:
1246 spec_set = spec
1247 spec = None
1248 elif spec_set is True:
1249 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001250
Michael Foord50a8c0e2012-03-25 18:57:58 +01001251 if spec is not None or spec_set is not None:
1252 if original is DEFAULT:
1253 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001254 if isinstance(original, type):
1255 # If we're patching out a class and there is a spec
1256 inherit = True
1257
1258 Klass = MagicMock
1259 _kwargs = {}
1260 if new_callable is not None:
1261 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001262 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001263 this_spec = spec
1264 if spec_set is not None:
1265 this_spec = spec_set
1266 if _is_list(this_spec):
1267 not_callable = '__call__' not in this_spec
1268 else:
1269 not_callable = not callable(this_spec)
1270 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001271 Klass = NonCallableMagicMock
1272
1273 if spec is not None:
1274 _kwargs['spec'] = spec
1275 if spec_set is not None:
1276 _kwargs['spec_set'] = spec_set
1277
1278 # add a name to mocks
1279 if (isinstance(Klass, type) and
1280 issubclass(Klass, NonCallableMock) and self.attribute):
1281 _kwargs['name'] = self.attribute
1282
1283 _kwargs.update(kwargs)
1284 new = Klass(**_kwargs)
1285
1286 if inherit and _is_instance_mock(new):
1287 # we can only tell if the instance should be callable if the
1288 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001289 this_spec = spec
1290 if spec_set is not None:
1291 this_spec = spec_set
1292 if (not _is_list(this_spec) and not
1293 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001294 Klass = NonCallableMagicMock
1295
1296 _kwargs.pop('name')
1297 new.return_value = Klass(_new_parent=new, _new_name='()',
1298 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001299 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001300 # spec is ignored, new *must* be default, spec_set is treated
1301 # as a boolean. Should we check spec is not None and that spec_set
1302 # is a bool?
1303 if new is not DEFAULT:
1304 raise TypeError(
1305 "autospec creates the mock for you. Can't specify "
1306 "autospec and new."
1307 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001308 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001309 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001310 spec_set = bool(spec_set)
1311 if autospec is True:
1312 autospec = original
1313
1314 new = create_autospec(autospec, spec_set=spec_set,
1315 _name=self.attribute, **kwargs)
1316 elif kwargs:
1317 # can't set keyword args when we aren't creating the mock
1318 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1319 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1320
1321 new_attr = new
1322
1323 self.temp_original = original
1324 self.is_local = local
1325 setattr(self.target, self.attribute, new_attr)
1326 if self.attribute_name is not None:
1327 extra_args = {}
1328 if self.new is DEFAULT:
1329 extra_args[self.attribute_name] = new
1330 for patching in self.additional_patchers:
1331 arg = patching.__enter__()
1332 if patching.new is DEFAULT:
1333 extra_args.update(arg)
1334 return extra_args
1335
1336 return new
1337
1338
Michael Foord50a8c0e2012-03-25 18:57:58 +01001339 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001340 """Undo the patch."""
1341 if not _is_started(self):
1342 raise RuntimeError('stop called on unstarted patcher')
1343
1344 if self.is_local and self.temp_original is not DEFAULT:
1345 setattr(self.target, self.attribute, self.temp_original)
1346 else:
1347 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001348 if not self.create and (not hasattr(self.target, self.attribute) or
1349 self.attribute in ('__doc__', '__module__',
1350 '__defaults__', '__annotations__',
1351 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001352 # needed for proxy objects like django settings
1353 setattr(self.target, self.attribute, self.temp_original)
1354
1355 del self.temp_original
1356 del self.is_local
1357 del self.target
1358 for patcher in reversed(self.additional_patchers):
1359 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001360 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001361
Michael Foordf7c41582012-06-10 20:36:32 +01001362
1363 def start(self):
1364 """Activate a patch, returning any created mock."""
1365 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001366 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001367 return result
1368
1369
1370 def stop(self):
1371 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001372 try:
1373 self._active_patches.remove(self)
1374 except ValueError:
1375 # If the patch hasn't been started this will fail
1376 pass
1377
Michael Foordf7c41582012-06-10 20:36:32 +01001378 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001379
1380
1381
1382def _get_target(target):
1383 try:
1384 target, attribute = target.rsplit('.', 1)
1385 except (TypeError, ValueError):
1386 raise TypeError("Need a valid target to patch. You supplied: %r" %
1387 (target,))
1388 getter = lambda: _importer(target)
1389 return getter, attribute
1390
1391
1392def _patch_object(
1393 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001394 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001395 new_callable=None, **kwargs
1396 ):
1397 """
Michael Foord345266a2012-03-14 12:24:34 -07001398 patch the named member (`attribute`) on an object (`target`) with a mock
1399 object.
1400
1401 `patch.object` can be used as a decorator, class decorator or a context
1402 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1403 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1404 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1405 the mock object it creates.
1406
1407 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1408 for choosing which methods to wrap.
1409 """
1410 getter = lambda: target
1411 return _patch(
1412 getter, attribute, new, spec, create,
1413 spec_set, autospec, new_callable, kwargs
1414 )
1415
1416
Michael Foord50a8c0e2012-03-25 18:57:58 +01001417def _patch_multiple(target, spec=None, create=False, spec_set=None,
1418 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001419 """Perform multiple patches in a single call. It takes the object to be
1420 patched (either as an object or a string to fetch the object by importing)
1421 and keyword arguments for the patches::
1422
1423 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1424 ...
1425
1426 Use `DEFAULT` as the value if you want `patch.multiple` to create
1427 mocks for you. In this case the created mocks are passed into a decorated
1428 function by keyword, and a dictionary is returned when `patch.multiple` is
1429 used as a context manager.
1430
1431 `patch.multiple` can be used as a decorator, class decorator or a context
1432 manager. The arguments `spec`, `spec_set`, `create`,
1433 `autospec` and `new_callable` have the same meaning as for `patch`. These
1434 arguments will be applied to *all* patches done by `patch.multiple`.
1435
1436 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1437 for choosing which methods to wrap.
1438 """
1439 if type(target) is str:
1440 getter = lambda: _importer(target)
1441 else:
1442 getter = lambda: target
1443
1444 if not kwargs:
1445 raise ValueError(
1446 'Must supply at least one keyword argument with patch.multiple'
1447 )
1448 # need to wrap in a list for python 3, where items is a view
1449 items = list(kwargs.items())
1450 attribute, new = items[0]
1451 patcher = _patch(
1452 getter, attribute, new, spec, create, spec_set,
1453 autospec, new_callable, {}
1454 )
1455 patcher.attribute_name = attribute
1456 for attribute, new in items[1:]:
1457 this_patcher = _patch(
1458 getter, attribute, new, spec, create, spec_set,
1459 autospec, new_callable, {}
1460 )
1461 this_patcher.attribute_name = attribute
1462 patcher.additional_patchers.append(this_patcher)
1463 return patcher
1464
1465
1466def patch(
1467 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001468 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001469 ):
1470 """
1471 `patch` acts as a function decorator, class decorator or a context
1472 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001473 is patched with a `new` object. When the function/with statement exits
1474 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001475
Michael Foord54b3db82012-03-28 15:08:08 +01001476 If `new` is omitted, then the target is replaced with a
1477 `MagicMock`. If `patch` is used as a decorator and `new` is
1478 omitted, the created mock is passed in as an extra argument to the
1479 decorated function. If `patch` is used as a context manager the created
1480 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001481
Michael Foord54b3db82012-03-28 15:08:08 +01001482 `target` should be a string in the form `'package.module.ClassName'`. The
1483 `target` is imported and the specified object replaced with the `new`
1484 object, so the `target` must be importable from the environment you are
1485 calling `patch` from. The target is imported when the decorated function
1486 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001487
1488 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1489 if patch is creating one for you.
1490
1491 In addition you can pass `spec=True` or `spec_set=True`, which causes
1492 patch to pass in the object being mocked as the spec/spec_set object.
1493
1494 `new_callable` allows you to specify a different class, or callable object,
1495 that will be called to create the `new` object. By default `MagicMock` is
1496 used.
1497
1498 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001499 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001500 All attributes of the mock will also have the spec of the corresponding
1501 attribute of the object being replaced. Methods and functions being
1502 mocked will have their arguments checked and will raise a `TypeError` if
1503 they are called with the wrong signature. For mocks replacing a class,
1504 their return value (the 'instance') will have the same spec as the class.
1505
1506 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1507 arbitrary object as the spec instead of the one being replaced.
1508
1509 By default `patch` will fail to replace attributes that don't exist. If
1510 you pass in `create=True`, and the attribute doesn't exist, patch will
1511 create the attribute for you when the patched function is called, and
1512 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001513 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001514 default because it can be dangerous. With it switched on you can write
1515 passing tests against APIs that don't actually exist!
1516
1517 Patch can be used as a `TestCase` class decorator. It works by
1518 decorating each test method in the class. This reduces the boilerplate
1519 code when your test methods share a common patchings set. `patch` finds
1520 tests by looking for method names that start with `patch.TEST_PREFIX`.
1521 By default this is `test`, which matches the way `unittest` finds tests.
1522 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1523
1524 Patch can be used as a context manager, with the with statement. Here the
1525 patching applies to the indented block after the with statement. If you
1526 use "as" then the patched object will be bound to the name after the
1527 "as"; very useful if `patch` is creating a mock object for you.
1528
1529 `patch` takes arbitrary keyword arguments. These will be passed to
1530 the `Mock` (or `new_callable`) on construction.
1531
1532 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1533 available for alternate use-cases.
1534 """
1535 getter, attribute = _get_target(target)
1536 return _patch(
1537 getter, attribute, new, spec, create,
1538 spec_set, autospec, new_callable, kwargs
1539 )
1540
1541
1542class _patch_dict(object):
1543 """
1544 Patch a dictionary, or dictionary like object, and restore the dictionary
1545 to its original state after the test.
1546
1547 `in_dict` can be a dictionary or a mapping like container. If it is a
1548 mapping then it must at least support getting, setting and deleting items
1549 plus iterating over keys.
1550
1551 `in_dict` can also be a string specifying the name of the dictionary, which
1552 will then be fetched by importing it.
1553
1554 `values` can be a dictionary of values to set in the dictionary. `values`
1555 can also be an iterable of `(key, value)` pairs.
1556
1557 If `clear` is True then the dictionary will be cleared before the new
1558 values are set.
1559
1560 `patch.dict` can also be called with arbitrary keyword arguments to set
1561 values in the dictionary::
1562
1563 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1564 ...
1565
1566 `patch.dict` can be used as a context manager, decorator or class
1567 decorator. When used as a class decorator `patch.dict` honours
1568 `patch.TEST_PREFIX` for choosing which methods to wrap.
1569 """
1570
1571 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1572 if isinstance(in_dict, str):
1573 in_dict = _importer(in_dict)
1574 self.in_dict = in_dict
1575 # support any argument supported by dict(...) constructor
1576 self.values = dict(values)
1577 self.values.update(kwargs)
1578 self.clear = clear
1579 self._original = None
1580
1581
1582 def __call__(self, f):
1583 if isinstance(f, type):
1584 return self.decorate_class(f)
1585 @wraps(f)
1586 def _inner(*args, **kw):
1587 self._patch_dict()
1588 try:
1589 return f(*args, **kw)
1590 finally:
1591 self._unpatch_dict()
1592
1593 return _inner
1594
1595
1596 def decorate_class(self, klass):
1597 for attr in dir(klass):
1598 attr_value = getattr(klass, attr)
1599 if (attr.startswith(patch.TEST_PREFIX) and
1600 hasattr(attr_value, "__call__")):
1601 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1602 decorated = decorator(attr_value)
1603 setattr(klass, attr, decorated)
1604 return klass
1605
1606
1607 def __enter__(self):
1608 """Patch the dict."""
1609 self._patch_dict()
1610
1611
1612 def _patch_dict(self):
1613 values = self.values
1614 in_dict = self.in_dict
1615 clear = self.clear
1616
1617 try:
1618 original = in_dict.copy()
1619 except AttributeError:
1620 # dict like object with no copy method
1621 # must support iteration over keys
1622 original = {}
1623 for key in in_dict:
1624 original[key] = in_dict[key]
1625 self._original = original
1626
1627 if clear:
1628 _clear_dict(in_dict)
1629
1630 try:
1631 in_dict.update(values)
1632 except AttributeError:
1633 # dict like object with no update method
1634 for key in values:
1635 in_dict[key] = values[key]
1636
1637
1638 def _unpatch_dict(self):
1639 in_dict = self.in_dict
1640 original = self._original
1641
1642 _clear_dict(in_dict)
1643
1644 try:
1645 in_dict.update(original)
1646 except AttributeError:
1647 for key in original:
1648 in_dict[key] = original[key]
1649
1650
1651 def __exit__(self, *args):
1652 """Unpatch the dict."""
1653 self._unpatch_dict()
1654 return False
1655
1656 start = __enter__
1657 stop = __exit__
1658
1659
1660def _clear_dict(in_dict):
1661 try:
1662 in_dict.clear()
1663 except AttributeError:
1664 keys = list(in_dict)
1665 for key in keys:
1666 del in_dict[key]
1667
1668
Michael Foordf7c41582012-06-10 20:36:32 +01001669def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001670 """Stop all active patches. LIFO to unroll nested patches."""
1671 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001672 patch.stop()
1673
1674
Michael Foord345266a2012-03-14 12:24:34 -07001675patch.object = _patch_object
1676patch.dict = _patch_dict
1677patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001678patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001679patch.TEST_PREFIX = 'test'
1680
1681magic_methods = (
1682 "lt le gt ge eq ne "
1683 "getitem setitem delitem "
1684 "len contains iter "
1685 "hash str sizeof "
1686 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001687 # we added divmod and rdivmod here instead of numerics
1688 # because there is no idivmod
1689 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001690 "complex int float index "
1691 "trunc floor ceil "
1692 "bool next "
1693)
1694
Michael Foordd2623d72014-04-14 11:23:48 -04001695numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001696 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001697)
Michael Foord345266a2012-03-14 12:24:34 -07001698inplace = ' '.join('i%s' % n for n in numerics.split())
1699right = ' '.join('r%s' % n for n in numerics.split())
1700
1701# not including __prepare__, __instancecheck__, __subclasscheck__
1702# (as they are metaclass methods)
1703# __del__ is not supported at all as it causes problems if it exists
1704
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001705_non_defaults = {
1706 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1707 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1708 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1709 '__repr__', '__dir__', '__subclasses__', '__format__',
Serhiy Storchaka5943ea72016-06-19 18:30:43 +03001710 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001711}
Michael Foord345266a2012-03-14 12:24:34 -07001712
1713
1714def _get_method(name, func):
1715 "Turns a callable object (like a mock) into a real function"
1716 def method(self, *args, **kw):
1717 return func(self, *args, **kw)
1718 method.__name__ = name
1719 return method
1720
1721
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001722_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001723 '__%s__' % method for method in
1724 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001725}
Michael Foord345266a2012-03-14 12:24:34 -07001726
1727_all_magics = _magics | _non_defaults
1728
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001729_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001730 '__getattr__', '__setattr__',
1731 '__init__', '__new__', '__prepare__'
1732 '__instancecheck__', '__subclasscheck__',
1733 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001734}
Michael Foord345266a2012-03-14 12:24:34 -07001735
1736_calculate_return_value = {
1737 '__hash__': lambda self: object.__hash__(self),
1738 '__str__': lambda self: object.__str__(self),
1739 '__sizeof__': lambda self: object.__sizeof__(self),
1740}
1741
1742_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001743 '__lt__': NotImplemented,
1744 '__gt__': NotImplemented,
1745 '__le__': NotImplemented,
1746 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001747 '__int__': 1,
1748 '__contains__': False,
1749 '__len__': 0,
1750 '__exit__': False,
1751 '__complex__': 1j,
1752 '__float__': 1.0,
1753 '__bool__': True,
1754 '__index__': 1,
1755}
1756
1757
1758def _get_eq(self):
1759 def __eq__(other):
1760 ret_val = self.__eq__._mock_return_value
1761 if ret_val is not DEFAULT:
1762 return ret_val
1763 return self is other
1764 return __eq__
1765
1766def _get_ne(self):
1767 def __ne__(other):
1768 if self.__ne__._mock_return_value is not DEFAULT:
1769 return DEFAULT
1770 return self is not other
1771 return __ne__
1772
1773def _get_iter(self):
1774 def __iter__():
1775 ret_val = self.__iter__._mock_return_value
1776 if ret_val is DEFAULT:
1777 return iter([])
1778 # if ret_val was already an iterator, then calling iter on it should
1779 # return the iterator unchanged
1780 return iter(ret_val)
1781 return __iter__
1782
1783_side_effect_methods = {
1784 '__eq__': _get_eq,
1785 '__ne__': _get_ne,
1786 '__iter__': _get_iter,
1787}
1788
1789
1790
1791def _set_return_value(mock, method, name):
1792 fixed = _return_values.get(name, DEFAULT)
1793 if fixed is not DEFAULT:
1794 method.return_value = fixed
1795 return
1796
1797 return_calulator = _calculate_return_value.get(name)
1798 if return_calulator is not None:
1799 try:
1800 return_value = return_calulator(mock)
1801 except AttributeError:
1802 # XXXX why do we return AttributeError here?
1803 # set it as a side_effect instead?
1804 return_value = AttributeError(name)
1805 method.return_value = return_value
1806 return
1807
1808 side_effector = _side_effect_methods.get(name)
1809 if side_effector is not None:
1810 method.side_effect = side_effector(mock)
1811
1812
1813
1814class MagicMixin(object):
1815 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001816 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001817 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001818 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001819
1820
1821 def _mock_set_magics(self):
1822 these_magics = _magics
1823
Łukasz Langaa468db92015-04-13 23:12:42 -07001824 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001825 these_magics = _magics.intersection(self._mock_methods)
1826
1827 remove_magics = set()
1828 remove_magics = _magics - these_magics
1829
1830 for entry in remove_magics:
1831 if entry in type(self).__dict__:
1832 # remove unneeded magic methods
1833 delattr(self, entry)
1834
1835 # don't overwrite existing attributes if called a second time
1836 these_magics = these_magics - set(type(self).__dict__)
1837
1838 _type = type(self)
1839 for entry in these_magics:
1840 setattr(_type, entry, MagicProxy(entry, self))
1841
1842
1843
1844class NonCallableMagicMock(MagicMixin, NonCallableMock):
1845 """A version of `MagicMock` that isn't callable."""
1846 def mock_add_spec(self, spec, spec_set=False):
1847 """Add a spec to a mock. `spec` can either be an object or a
1848 list of strings. Only attributes on the `spec` can be fetched as
1849 attributes from the mock.
1850
1851 If `spec_set` is True then only attributes on the spec can be set."""
1852 self._mock_add_spec(spec, spec_set)
1853 self._mock_set_magics()
1854
1855
1856
1857class MagicMock(MagicMixin, Mock):
1858 """
1859 MagicMock is a subclass of Mock with default implementations
1860 of most of the magic methods. You can use MagicMock without having to
1861 configure the magic methods yourself.
1862
1863 If you use the `spec` or `spec_set` arguments then *only* magic
1864 methods that exist in the spec will be created.
1865
1866 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1867 """
1868 def mock_add_spec(self, spec, spec_set=False):
1869 """Add a spec to a mock. `spec` can either be an object or a
1870 list of strings. Only attributes on the `spec` can be fetched as
1871 attributes from the mock.
1872
1873 If `spec_set` is True then only attributes on the spec can be set."""
1874 self._mock_add_spec(spec, spec_set)
1875 self._mock_set_magics()
1876
1877
1878
1879class MagicProxy(object):
1880 def __init__(self, name, parent):
1881 self.name = name
1882 self.parent = parent
1883
1884 def __call__(self, *args, **kwargs):
1885 m = self.create_mock()
1886 return m(*args, **kwargs)
1887
1888 def create_mock(self):
1889 entry = self.name
1890 parent = self.parent
1891 m = parent._get_child_mock(name=entry, _new_name=entry,
1892 _new_parent=parent)
1893 setattr(parent, entry, m)
1894 _set_return_value(parent, m, entry)
1895 return m
1896
1897 def __get__(self, obj, _type=None):
1898 return self.create_mock()
1899
1900
1901
1902class _ANY(object):
1903 "A helper object that compares equal to everything."
1904
1905 def __eq__(self, other):
1906 return True
1907
1908 def __ne__(self, other):
1909 return False
1910
1911 def __repr__(self):
1912 return '<ANY>'
1913
1914ANY = _ANY()
1915
1916
1917
1918def _format_call_signature(name, args, kwargs):
1919 message = '%s(%%s)' % name
1920 formatted_args = ''
1921 args_string = ', '.join([repr(arg) for arg in args])
1922 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301923 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001924 ])
1925 if args_string:
1926 formatted_args = args_string
1927 if kwargs_string:
1928 if formatted_args:
1929 formatted_args += ', '
1930 formatted_args += kwargs_string
1931
1932 return message % formatted_args
1933
1934
1935
1936class _Call(tuple):
1937 """
1938 A tuple for holding the results of a call to a mock, either in the form
1939 `(args, kwargs)` or `(name, args, kwargs)`.
1940
1941 If args or kwargs are empty then a call tuple will compare equal to
1942 a tuple without those values. This makes comparisons less verbose::
1943
1944 _Call(('name', (), {})) == ('name',)
1945 _Call(('name', (1,), {})) == ('name', (1,))
1946 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1947
1948 The `_Call` object provides a useful shortcut for comparing with call::
1949
1950 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1951 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1952
1953 If the _Call has no name then it will match any name.
1954 """
1955 def __new__(cls, value=(), name=None, parent=None, two=False,
1956 from_kall=True):
1957 name = ''
1958 args = ()
1959 kwargs = {}
1960 _len = len(value)
1961 if _len == 3:
1962 name, args, kwargs = value
1963 elif _len == 2:
1964 first, second = value
1965 if isinstance(first, str):
1966 name = first
1967 if isinstance(second, tuple):
1968 args = second
1969 else:
1970 kwargs = second
1971 else:
1972 args, kwargs = first, second
1973 elif _len == 1:
1974 value, = value
1975 if isinstance(value, str):
1976 name = value
1977 elif isinstance(value, tuple):
1978 args = value
1979 else:
1980 kwargs = value
1981
1982 if two:
1983 return tuple.__new__(cls, (args, kwargs))
1984
1985 return tuple.__new__(cls, (name, args, kwargs))
1986
1987
1988 def __init__(self, value=(), name=None, parent=None, two=False,
1989 from_kall=True):
1990 self.name = name
1991 self.parent = parent
1992 self.from_kall = from_kall
1993
1994
1995 def __eq__(self, other):
1996 if other is ANY:
1997 return True
1998 try:
1999 len_other = len(other)
2000 except TypeError:
2001 return False
2002
2003 self_name = ''
2004 if len(self) == 2:
2005 self_args, self_kwargs = self
2006 else:
2007 self_name, self_args, self_kwargs = self
2008
2009 other_name = ''
2010 if len_other == 0:
2011 other_args, other_kwargs = (), {}
2012 elif len_other == 3:
2013 other_name, other_args, other_kwargs = other
2014 elif len_other == 1:
2015 value, = other
2016 if isinstance(value, tuple):
2017 other_args = value
2018 other_kwargs = {}
2019 elif isinstance(value, str):
2020 other_name = value
2021 other_args, other_kwargs = (), {}
2022 else:
2023 other_args = ()
2024 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002025 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002026 # could be (name, args) or (name, kwargs) or (args, kwargs)
2027 first, second = other
2028 if isinstance(first, str):
2029 other_name = first
2030 if isinstance(second, tuple):
2031 other_args, other_kwargs = second, {}
2032 else:
2033 other_args, other_kwargs = (), second
2034 else:
2035 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002036 else:
2037 return False
Michael Foord345266a2012-03-14 12:24:34 -07002038
2039 if self_name and other_name != self_name:
2040 return False
2041
2042 # this order is important for ANY to work!
2043 return (other_args, other_kwargs) == (self_args, self_kwargs)
2044
2045
Berker Peksagce913872016-03-28 00:30:02 +03002046 __ne__ = object.__ne__
2047
2048
Michael Foord345266a2012-03-14 12:24:34 -07002049 def __call__(self, *args, **kwargs):
2050 if self.name is None:
2051 return _Call(('', args, kwargs), name='()')
2052
2053 name = self.name + '()'
2054 return _Call((self.name, args, kwargs), name=name, parent=self)
2055
2056
2057 def __getattr__(self, attr):
2058 if self.name is None:
2059 return _Call(name=attr, from_kall=False)
2060 name = '%s.%s' % (self.name, attr)
2061 return _Call(name=name, parent=self, from_kall=False)
2062
2063
Kushal Dasa37b9582014-09-16 18:33:37 +05302064 def count(self, *args, **kwargs):
2065 return self.__getattr__('count')(*args, **kwargs)
2066
2067 def index(self, *args, **kwargs):
2068 return self.__getattr__('index')(*args, **kwargs)
2069
Michael Foord345266a2012-03-14 12:24:34 -07002070 def __repr__(self):
2071 if not self.from_kall:
2072 name = self.name or 'call'
2073 if name.startswith('()'):
2074 name = 'call%s' % name
2075 return name
2076
2077 if len(self) == 2:
2078 name = 'call'
2079 args, kwargs = self
2080 else:
2081 name, args, kwargs = self
2082 if not name:
2083 name = 'call'
2084 elif not name.startswith('()'):
2085 name = 'call.%s' % name
2086 else:
2087 name = 'call%s' % name
2088 return _format_call_signature(name, args, kwargs)
2089
2090
2091 def call_list(self):
2092 """For a call object that represents multiple calls, `call_list`
2093 returns a list of all the intermediate calls as well as the
2094 final call."""
2095 vals = []
2096 thing = self
2097 while thing is not None:
2098 if thing.from_kall:
2099 vals.append(thing)
2100 thing = thing.parent
2101 return _CallList(reversed(vals))
2102
2103
2104call = _Call(from_kall=False)
2105
2106
2107
2108def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2109 _name=None, **kwargs):
2110 """Create a mock object using another object as a spec. Attributes on the
2111 mock will use the corresponding attribute on the `spec` object as their
2112 spec.
2113
2114 Functions or methods being mocked will have their arguments checked
2115 to check that they are called with the correct signature.
2116
2117 If `spec_set` is True then attempting to set attributes that don't exist
2118 on the spec object will raise an `AttributeError`.
2119
2120 If a class is used as a spec then the return value of the mock (the
2121 instance of the class) will have the same spec. You can use a class as the
2122 spec for an instance object by passing `instance=True`. The returned mock
2123 will only be callable if instances of the mock are callable.
2124
2125 `create_autospec` also takes arbitrary keyword arguments that are passed to
2126 the constructor of the created mock."""
2127 if _is_list(spec):
2128 # can't pass a list instance to the mock constructor as it will be
2129 # interpreted as a list of strings
2130 spec = type(spec)
2131
2132 is_type = isinstance(spec, type)
2133
2134 _kwargs = {'spec': spec}
2135 if spec_set:
2136 _kwargs = {'spec_set': spec}
2137 elif spec is None:
2138 # None we mock with a normal mock without a spec
2139 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002140 if _kwargs and instance:
2141 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002142
2143 _kwargs.update(kwargs)
2144
2145 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002146 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002147 # descriptors don't have a spec
2148 # because we don't know what type they return
2149 _kwargs = {}
2150 elif not _callable(spec):
2151 Klass = NonCallableMagicMock
2152 elif is_type and instance and not _instance_callable(spec):
2153 Klass = NonCallableMagicMock
2154
Kushal Das484f8a82014-04-16 01:05:50 +05302155 _name = _kwargs.pop('name', _name)
2156
Michael Foord345266a2012-03-14 12:24:34 -07002157 _new_name = _name
2158 if _parent is None:
2159 # for a top level object no _new_name should be set
2160 _new_name = ''
2161
2162 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2163 name=_name, **_kwargs)
2164
2165 if isinstance(spec, FunctionTypes):
2166 # should only happen at the top level because we don't
2167 # recurse for functions
2168 mock = _set_signature(mock, spec)
2169 else:
2170 _check_signature(spec, mock, is_type, instance)
2171
2172 if _parent is not None and not instance:
2173 _parent._mock_children[_name] = mock
2174
2175 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002176 mock.return_value = create_autospec(spec, spec_set, instance=True,
2177 _name='()', _parent=mock)
2178
2179 for entry in dir(spec):
2180 if _is_magic(entry):
2181 # MagicMock already does the useful magic methods for us
2182 continue
2183
Michael Foord345266a2012-03-14 12:24:34 -07002184 # XXXX do we need a better way of getting attributes without
2185 # triggering code execution (?) Probably not - we need the actual
2186 # object to mock it so we would rather trigger a property than mock
2187 # the property descriptor. Likewise we want to mock out dynamically
2188 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002189 # XXXX what about attributes that raise exceptions other than
2190 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002191 # we could be resilient against it, or catch and propagate the
2192 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002193 try:
2194 original = getattr(spec, entry)
2195 except AttributeError:
2196 continue
Michael Foord345266a2012-03-14 12:24:34 -07002197
2198 kwargs = {'spec': original}
2199 if spec_set:
2200 kwargs = {'spec_set': original}
2201
2202 if not isinstance(original, FunctionTypes):
2203 new = _SpecState(original, spec_set, mock, entry, instance)
2204 mock._mock_children[entry] = new
2205 else:
2206 parent = mock
2207 if isinstance(spec, FunctionTypes):
2208 parent = mock.mock
2209
Michael Foord345266a2012-03-14 12:24:34 -07002210 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002211 kwargs['_eat_self'] = skipfirst
2212 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2213 _new_parent=parent,
2214 **kwargs)
2215 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002216 _check_signature(original, new, skipfirst=skipfirst)
2217
2218 # so functions created with _set_signature become instance attributes,
2219 # *plus* their underlying mock exists in _mock_children of the parent
2220 # mock. Adding to _mock_children may be unnecessary where we are also
2221 # setting as an instance attribute?
2222 if isinstance(new, FunctionTypes):
2223 setattr(mock, entry, new)
2224
2225 return mock
2226
2227
2228def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002229 """
2230 Return whether we should skip the first argument on spec's `entry`
2231 attribute.
2232 """
Michael Foord345266a2012-03-14 12:24:34 -07002233 if not isinstance(spec, type):
2234 if entry in getattr(spec, '__dict__', {}):
2235 # instance attribute - shouldn't skip
2236 return False
Michael Foord345266a2012-03-14 12:24:34 -07002237 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002238
2239 for klass in spec.__mro__:
2240 result = klass.__dict__.get(entry, DEFAULT)
2241 if result is DEFAULT:
2242 continue
2243 if isinstance(result, (staticmethod, classmethod)):
2244 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002245 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2246 # Normal method => skip if looked up on type
2247 # (if looked up on instance, self is already skipped)
2248 return is_type
2249 else:
2250 return False
Michael Foord345266a2012-03-14 12:24:34 -07002251
2252 # shouldn't get here unless function is a dynamically provided attribute
2253 # XXXX untested behaviour
2254 return is_type
2255
2256
2257def _get_class(obj):
2258 try:
2259 return obj.__class__
2260 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002261 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002262 return type(obj)
2263
2264
2265class _SpecState(object):
2266
2267 def __init__(self, spec, spec_set=False, parent=None,
2268 name=None, ids=None, instance=False):
2269 self.spec = spec
2270 self.ids = ids
2271 self.spec_set = spec_set
2272 self.parent = parent
2273 self.instance = instance
2274 self.name = name
2275
2276
2277FunctionTypes = (
2278 # python function
2279 type(create_autospec),
2280 # instance method
2281 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002282)
2283
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002284MethodWrapperTypes = (
2285 type(ANY.__eq__.__get__),
2286)
2287
Michael Foord345266a2012-03-14 12:24:34 -07002288
Michael Foorda74561a2012-03-25 19:03:13 +01002289file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002290
Michael Foord04cbe0c2013-03-19 17:22:51 -07002291def _iterate_read_data(read_data):
2292 # Helper for mock_open:
2293 # Retrieve lines from read_data via a generator so that separate calls to
2294 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002295 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2296 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002297
Berker Peksag86b34da2015-08-06 13:15:51 +03002298 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002299 # If the last line ended in a newline, the list comprehension will have an
2300 # extra entry that's just a newline. Remove this.
2301 data_as_list = data_as_list[:-1]
2302 else:
2303 # If there wasn't an extra newline by itself, then the file being
2304 # emulated doesn't have a newline to end the last line remove the
2305 # newline that our naive format() added
2306 data_as_list[-1] = data_as_list[-1][:-1]
2307
2308 for line in data_as_list:
2309 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002310
Robert Collins5329aaa2015-07-17 20:08:45 +12002311
Michael Foord0dccf652012-03-25 19:11:50 +01002312def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002313 """
2314 A helper function to create a mock to replace the use of `open`. It works
2315 for `open` called directly or used as a context manager.
2316
2317 The `mock` argument is the mock object to configure. If `None` (the
2318 default) then a `MagicMock` will be created for you, with the API limited
2319 to methods or attributes available on standard file handles.
2320
Michael Foord04cbe0c2013-03-19 17:22:51 -07002321 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2322 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002323 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002324 def _readlines_side_effect(*args, **kwargs):
2325 if handle.readlines.return_value is not None:
2326 return handle.readlines.return_value
2327 return list(_state[0])
2328
2329 def _read_side_effect(*args, **kwargs):
2330 if handle.read.return_value is not None:
2331 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002332 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002333
2334 def _readline_side_effect():
2335 if handle.readline.return_value is not None:
2336 while True:
2337 yield handle.readline.return_value
2338 for line in _state[0]:
2339 yield line
Robert Collins9549a3e2016-05-16 15:22:01 +12002340 while True:
2341 yield type(read_data)()
Robert Collinsca647ef2015-07-24 03:48:20 +12002342
2343
Michael Foorda74561a2012-03-25 19:03:13 +01002344 global file_spec
2345 if file_spec is None:
2346 import _io
2347 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2348
Michael Foord345266a2012-03-14 12:24:34 -07002349 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002350 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002351
Robert Collinsca647ef2015-07-24 03:48:20 +12002352 handle = MagicMock(spec=file_spec)
2353 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002354
Robert Collinsca647ef2015-07-24 03:48:20 +12002355 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002356
Robert Collinsca647ef2015-07-24 03:48:20 +12002357 handle.write.return_value = None
2358 handle.read.return_value = None
2359 handle.readline.return_value = None
2360 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002361
Robert Collinsca647ef2015-07-24 03:48:20 +12002362 handle.read.side_effect = _read_side_effect
2363 _state[1] = _readline_side_effect()
2364 handle.readline.side_effect = _state[1]
2365 handle.readlines.side_effect = _readlines_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002366
Robert Collinsca647ef2015-07-24 03:48:20 +12002367 def reset_data(*args, **kwargs):
2368 _state[0] = _iterate_read_data(read_data)
2369 if handle.readline.side_effect == _state[1]:
2370 # Only reset the side effect if the user hasn't overridden it.
2371 _state[1] = _readline_side_effect()
2372 handle.readline.side_effect = _state[1]
2373 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002374
Robert Collinsca647ef2015-07-24 03:48:20 +12002375 mock.side_effect = reset_data
2376 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002377 return mock
2378
2379
2380class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002381 """
2382 A mock intended to be used as a property, or other descriptor, on a class.
2383 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2384 a return value when it is fetched.
2385
2386 Fetching a `PropertyMock` instance from an object calls the mock, with
2387 no args. Setting it calls the mock with the value being set.
2388 """
Michael Foordc2870622012-04-13 16:57:22 +01002389 def _get_child_mock(self, **kwargs):
2390 return MagicMock(**kwargs)
2391
Michael Foord345266a2012-03-14 12:24:34 -07002392 def __get__(self, obj, obj_type):
2393 return self()
2394 def __set__(self, obj, val):
2395 self(val)