blob: 976f663c0a958ab301af1bbc38dd8ebcf3f1e97b [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
Robert Collinsb37f43f2015-07-15 11:42:28 +1200526 def reset_mock(self, visited=None):
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
541 for child in self._mock_children.values():
Michael Foord75963642012-06-09 17:31:59 +0100542 if isinstance(child, _SpecState):
543 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200544 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700545
546 ret = self._mock_return_value
547 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200548 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700549
550
551 def configure_mock(self, **kwargs):
552 """Set attributes on the mock through keyword arguments.
553
554 Attributes plus return values and side effects can be set on child
555 mocks using standard dot notation and unpacking a dictionary in the
556 method call:
557
558 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
559 >>> mock.configure_mock(**attrs)"""
560 for arg, val in sorted(kwargs.items(),
561 # we sort on the number of dots so that
562 # attributes are set before we set attributes on
563 # attributes
564 key=lambda entry: entry[0].count('.')):
565 args = arg.split('.')
566 final = args.pop()
567 obj = self
568 for entry in args:
569 obj = getattr(obj, entry)
570 setattr(obj, final, val)
571
572
573 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530574 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700575 raise AttributeError(name)
576 elif self._mock_methods is not None:
577 if name not in self._mock_methods or name in _all_magics:
578 raise AttributeError("Mock object has no attribute %r" % name)
579 elif _is_magic(name):
580 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530581 if not self._mock_unsafe:
582 if name.startswith(('assert', 'assret')):
583 raise AttributeError(name)
Michael Foord345266a2012-03-14 12:24:34 -0700584
585 result = self._mock_children.get(name)
586 if result is _deleted:
587 raise AttributeError(name)
588 elif result is None:
589 wraps = None
590 if self._mock_wraps is not None:
591 # XXXX should we get the attribute without triggering code
592 # execution?
593 wraps = getattr(self._mock_wraps, name)
594
595 result = self._get_child_mock(
596 parent=self, name=name, wraps=wraps, _new_name=name,
597 _new_parent=self
598 )
599 self._mock_children[name] = result
600
601 elif isinstance(result, _SpecState):
602 result = create_autospec(
603 result.spec, result.spec_set, result.instance,
604 result.parent, result.name
605 )
606 self._mock_children[name] = result
607
608 return result
609
610
611 def __repr__(self):
612 _name_list = [self._mock_new_name]
613 _parent = self._mock_new_parent
614 last = self
615
616 dot = '.'
617 if _name_list == ['()']:
618 dot = ''
619 seen = set()
620 while _parent is not None:
621 last = _parent
622
623 _name_list.append(_parent._mock_new_name + dot)
624 dot = '.'
625 if _parent._mock_new_name == '()':
626 dot = ''
627
628 _parent = _parent._mock_new_parent
629
630 # use ids here so as not to call __hash__ on the mocks
631 if id(_parent) in seen:
632 break
633 seen.add(id(_parent))
634
635 _name_list = list(reversed(_name_list))
636 _first = last._mock_name or 'mock'
637 if len(_name_list) > 1:
638 if _name_list[1] not in ('()', '().'):
639 _first += '.'
640 _name_list[0] = _first
641 name = ''.join(_name_list)
642
643 name_string = ''
644 if name not in ('mock', 'mock.'):
645 name_string = ' name=%r' % name
646
647 spec_string = ''
648 if self._spec_class is not None:
649 spec_string = ' spec=%r'
650 if self._spec_set:
651 spec_string = ' spec_set=%r'
652 spec_string = spec_string % self._spec_class.__name__
653 return "<%s%s%s id='%s'>" % (
654 type(self).__name__,
655 name_string,
656 spec_string,
657 id(self)
658 )
659
660
661 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700662 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100663 if not FILTER_DIR:
664 return object.__dir__(self)
665
Michael Foord345266a2012-03-14 12:24:34 -0700666 extras = self._mock_methods or []
667 from_type = dir(type(self))
668 from_dict = list(self.__dict__)
669
Michael Foord313f85f2012-03-25 18:16:07 +0100670 from_type = [e for e in from_type if not e.startswith('_')]
671 from_dict = [e for e in from_dict if not e.startswith('_') or
672 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700673 return sorted(set(extras + from_type + from_dict +
674 list(self._mock_children)))
675
676
677 def __setattr__(self, name, value):
678 if name in _allowed_names:
679 # property setters go through here
680 return object.__setattr__(self, name, value)
681 elif (self._spec_set and self._mock_methods is not None and
682 name not in self._mock_methods and
683 name not in self.__dict__):
684 raise AttributeError("Mock object has no attribute '%s'" % name)
685 elif name in _unsupported_magics:
686 msg = 'Attempting to set unsupported magic method %r.' % name
687 raise AttributeError(msg)
688 elif name in _all_magics:
689 if self._mock_methods is not None and name not in self._mock_methods:
690 raise AttributeError("Mock object has no attribute '%s'" % name)
691
692 if not _is_instance_mock(value):
693 setattr(type(self), name, _get_method(name, value))
694 original = value
695 value = lambda *args, **kw: original(self, *args, **kw)
696 else:
697 # only set _new_name and not name so that mock_calls is tracked
698 # but not method calls
699 _check_and_set_parent(self, value, None, name)
700 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100701 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700702 elif name == '__class__':
703 self._spec_class = value
704 return
705 else:
706 if _check_and_set_parent(self, value, name, name):
707 self._mock_children[name] = value
708 return object.__setattr__(self, name, value)
709
710
711 def __delattr__(self, name):
712 if name in _all_magics and name in type(self).__dict__:
713 delattr(type(self), name)
714 if name not in self.__dict__:
715 # for magic methods that are still MagicProxy objects and
716 # not set on the instance itself
717 return
718
719 if name in self.__dict__:
720 object.__delattr__(self, name)
721
722 obj = self._mock_children.get(name, _missing)
723 if obj is _deleted:
724 raise AttributeError(name)
725 if obj is not _missing:
726 del self._mock_children[name]
727 self._mock_children[name] = _deleted
728
729
Michael Foord345266a2012-03-14 12:24:34 -0700730 def _format_mock_call_signature(self, args, kwargs):
731 name = self._mock_name or 'mock'
732 return _format_call_signature(name, args, kwargs)
733
734
735 def _format_mock_failure_message(self, args, kwargs):
736 message = 'Expected call: %s\nActual call: %s'
737 expected_string = self._format_mock_call_signature(args, kwargs)
738 call_args = self.call_args
739 if len(call_args) == 3:
740 call_args = call_args[1:]
741 actual_string = self._format_mock_call_signature(*call_args)
742 return message % (expected_string, actual_string)
743
744
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100745 def _call_matcher(self, _call):
746 """
747 Given a call (or simply a (args, kwargs) tuple), return a
748 comparison key suitable for matching with other calls.
749 This is a best effort method which relies on the spec's signature,
750 if available, or falls back on the arguments themselves.
751 """
752 sig = self._spec_signature
753 if sig is not None:
754 if len(_call) == 2:
755 name = ''
756 args, kwargs = _call
757 else:
758 name, args, kwargs = _call
759 try:
760 return name, sig.bind(*args, **kwargs)
761 except TypeError as e:
762 return e.with_traceback(None)
763 else:
764 return _call
765
Kushal Das68290f42014-04-17 01:54:07 +0530766 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530767 """assert that the mock was never called.
768 """
769 self = _mock_self
770 if self.call_count != 0:
771 msg = ("Expected '%s' to not have been called. Called %s times." %
772 (self._mock_name or 'mock', self.call_count))
773 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100774
Michael Foord345266a2012-03-14 12:24:34 -0700775 def assert_called_with(_mock_self, *args, **kwargs):
776 """assert that the mock was called with the specified arguments.
777
778 Raises an AssertionError if the args and keyword args passed in are
779 different to the last call to the mock."""
780 self = _mock_self
781 if self.call_args is None:
782 expected = self._format_mock_call_signature(args, kwargs)
783 raise AssertionError('Expected call: %s\nNot called' % (expected,))
784
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100785 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700786 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100787 return msg
788 expected = self._call_matcher((args, kwargs))
789 actual = self._call_matcher(self.call_args)
790 if expected != actual:
791 cause = expected if isinstance(expected, Exception) else None
792 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700793
794
795 def assert_called_once_with(_mock_self, *args, **kwargs):
796 """assert that the mock was called exactly once and with the specified
797 arguments."""
798 self = _mock_self
799 if not self.call_count == 1:
Michael Foord28d591c2012-09-28 16:15:22 +0100800 msg = ("Expected '%s' to be called once. Called %s times." %
801 (self._mock_name or 'mock', self.call_count))
Michael Foord345266a2012-03-14 12:24:34 -0700802 raise AssertionError(msg)
803 return self.assert_called_with(*args, **kwargs)
804
805
806 def assert_has_calls(self, calls, any_order=False):
807 """assert the mock has been called with the specified calls.
808 The `mock_calls` list is checked for the calls.
809
810 If `any_order` is False (the default) then the calls must be
811 sequential. There can be extra calls before or after the
812 specified calls.
813
814 If `any_order` is True then the calls can be in any order, but
815 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100816 expected = [self._call_matcher(c) for c in calls]
817 cause = expected if isinstance(expected, Exception) else None
818 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700819 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100820 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700821 raise AssertionError(
822 'Calls not found.\nExpected: %r\n'
823 'Actual: %r' % (calls, self.mock_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100824 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700825 return
826
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100827 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700828
829 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100830 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700831 try:
832 all_calls.remove(kall)
833 except ValueError:
834 not_found.append(kall)
835 if not_found:
836 raise AssertionError(
837 '%r not all found in call list' % (tuple(not_found),)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100838 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700839
840
841 def assert_any_call(self, *args, **kwargs):
842 """assert the mock has been called with the specified arguments.
843
844 The assert passes if the mock has *ever* been called, unlike
845 `assert_called_with` and `assert_called_once_with` that only pass if
846 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100847 expected = self._call_matcher((args, kwargs))
848 actual = [self._call_matcher(c) for c in self.call_args_list]
849 if expected not in actual:
850 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700851 expected_string = self._format_mock_call_signature(args, kwargs)
852 raise AssertionError(
853 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100854 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700855
856
857 def _get_child_mock(self, **kw):
858 """Create the child mocks for attributes and return value.
859 By default child mocks will be the same type as the parent.
860 Subclasses of Mock may want to override this to customize the way
861 child mocks are made.
862
863 For non-callable mocks the callable variant will be used (rather than
864 any custom subclass)."""
865 _type = type(self)
866 if not issubclass(_type, CallableMixin):
867 if issubclass(_type, NonCallableMagicMock):
868 klass = MagicMock
869 elif issubclass(_type, NonCallableMock) :
870 klass = Mock
871 else:
872 klass = _type.__mro__[1]
873 return klass(**kw)
874
875
876
877def _try_iter(obj):
878 if obj is None:
879 return obj
880 if _is_exception(obj):
881 return obj
882 if _callable(obj):
883 return obj
884 try:
885 return iter(obj)
886 except TypeError:
887 # XXXX backwards compatibility
888 # but this will blow up on first call - so maybe we should fail early?
889 return obj
890
891
892
893class CallableMixin(Base):
894
895 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
896 wraps=None, name=None, spec_set=None, parent=None,
897 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
898 self.__dict__['_mock_return_value'] = return_value
899
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000900 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700901 spec, wraps, name, spec_set, parent,
902 _spec_state, _new_name, _new_parent, **kwargs
903 )
904
905 self.side_effect = side_effect
906
907
908 def _mock_check_sig(self, *args, **kwargs):
909 # stub method that can be replaced with one with a specific signature
910 pass
911
912
913 def __call__(_mock_self, *args, **kwargs):
914 # can't use self in-case a function / method we are mocking uses self
915 # in the signature
916 _mock_self._mock_check_sig(*args, **kwargs)
917 return _mock_self._mock_call(*args, **kwargs)
918
919
920 def _mock_call(_mock_self, *args, **kwargs):
921 self = _mock_self
922 self.called = True
923 self.call_count += 1
Michael Foord345266a2012-03-14 12:24:34 -0700924 _new_name = self._mock_new_name
925 _new_parent = self._mock_new_parent
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100926
927 _call = _Call((args, kwargs), two=True)
928 self.call_args = _call
929 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700930 self.mock_calls.append(_Call(('', args, kwargs)))
931
932 seen = set()
933 skip_next_dot = _new_name == '()'
934 do_method_calls = self._mock_parent is not None
935 name = self._mock_name
936 while _new_parent is not None:
937 this_mock_call = _Call((_new_name, args, kwargs))
938 if _new_parent._mock_new_name:
939 dot = '.'
940 if skip_next_dot:
941 dot = ''
942
943 skip_next_dot = False
944 if _new_parent._mock_new_name == '()':
945 skip_next_dot = True
946
947 _new_name = _new_parent._mock_new_name + dot + _new_name
948
949 if do_method_calls:
950 if _new_name == name:
951 this_method_call = this_mock_call
952 else:
953 this_method_call = _Call((name, args, kwargs))
954 _new_parent.method_calls.append(this_method_call)
955
956 do_method_calls = _new_parent._mock_parent is not None
957 if do_method_calls:
958 name = _new_parent._mock_name + '.' + name
959
960 _new_parent.mock_calls.append(this_mock_call)
961 _new_parent = _new_parent._mock_new_parent
962
963 # use ids here so as not to call __hash__ on the mocks
964 _new_parent_id = id(_new_parent)
965 if _new_parent_id in seen:
966 break
967 seen.add(_new_parent_id)
968
969 ret_val = DEFAULT
970 effect = self.side_effect
971 if effect is not None:
972 if _is_exception(effect):
973 raise effect
974
975 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +0100976 result = next(effect)
977 if _is_exception(result):
978 raise result
Andrew Svetlov8b2cd752013-04-07 16:42:24 +0300979 if result is DEFAULT:
980 result = self.return_value
Michael Foord2cd48732012-04-21 15:52:11 +0100981 return result
Michael Foord345266a2012-03-14 12:24:34 -0700982
983 ret_val = effect(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700984
985 if (self._mock_wraps is not None and
986 self._mock_return_value is DEFAULT):
987 return self._mock_wraps(*args, **kwargs)
988 if ret_val is DEFAULT:
989 ret_val = self.return_value
990 return ret_val
991
992
993
994class Mock(CallableMixin, NonCallableMock):
995 """
996 Create a new `Mock` object. `Mock` takes several optional arguments
997 that specify the behaviour of the Mock object:
998
999 * `spec`: This can be either a list of strings or an existing object (a
1000 class or instance) that acts as the specification for the mock object. If
1001 you pass in an object then a list of strings is formed by calling dir on
1002 the object (excluding unsupported magic attributes and methods). Accessing
1003 any attribute not in this list will raise an `AttributeError`.
1004
1005 If `spec` is an object (rather than a list of strings) then
1006 `mock.__class__` returns the class of the spec object. This allows mocks
1007 to pass `isinstance` tests.
1008
1009 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1010 or get an attribute on the mock that isn't on the object passed as
1011 `spec_set` will raise an `AttributeError`.
1012
1013 * `side_effect`: A function to be called whenever the Mock is called. See
1014 the `side_effect` attribute. Useful for raising exceptions or
1015 dynamically changing return values. The function is called with the same
1016 arguments as the mock, and unless it returns `DEFAULT`, the return
1017 value of this function is used as the return value.
1018
Michael Foord2cd48732012-04-21 15:52:11 +01001019 If `side_effect` is an iterable then each call to the mock will return
1020 the next value from the iterable. If any of the members of the iterable
1021 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001022
Michael Foord345266a2012-03-14 12:24:34 -07001023 * `return_value`: The value returned when the mock is called. By default
1024 this is a new Mock (created on first access). See the
1025 `return_value` attribute.
1026
Michael Foord0682a0c2012-04-13 20:51:20 +01001027 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1028 calling the Mock will pass the call through to the wrapped object
1029 (returning the real result). Attribute access on the mock will return a
1030 Mock object that wraps the corresponding attribute of the wrapped object
1031 (so attempting to access an attribute that doesn't exist will raise an
1032 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001033
1034 If the mock has an explicit `return_value` set then calls are not passed
1035 to the wrapped object and the `return_value` is returned instead.
1036
1037 * `name`: If the mock has a name then it will be used in the repr of the
1038 mock. This can be useful for debugging. The name is propagated to child
1039 mocks.
1040
1041 Mocks can also be called with arbitrary keyword arguments. These will be
1042 used to set attributes on the mock after it is created.
1043 """
1044
1045
1046
1047def _dot_lookup(thing, comp, import_path):
1048 try:
1049 return getattr(thing, comp)
1050 except AttributeError:
1051 __import__(import_path)
1052 return getattr(thing, comp)
1053
1054
1055def _importer(target):
1056 components = target.split('.')
1057 import_path = components.pop(0)
1058 thing = __import__(import_path)
1059
1060 for comp in components:
1061 import_path += ".%s" % comp
1062 thing = _dot_lookup(thing, comp, import_path)
1063 return thing
1064
1065
1066def _is_started(patcher):
1067 # XXXX horrible
1068 return hasattr(patcher, 'is_local')
1069
1070
1071class _patch(object):
1072
1073 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001074 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001075
1076 def __init__(
1077 self, getter, attribute, new, spec, create,
1078 spec_set, autospec, new_callable, kwargs
1079 ):
1080 if new_callable is not None:
1081 if new is not DEFAULT:
1082 raise ValueError(
1083 "Cannot use 'new' and 'new_callable' together"
1084 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001085 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001086 raise ValueError(
1087 "Cannot use 'autospec' and 'new_callable' together"
1088 )
1089
1090 self.getter = getter
1091 self.attribute = attribute
1092 self.new = new
1093 self.new_callable = new_callable
1094 self.spec = spec
1095 self.create = create
1096 self.has_local = False
1097 self.spec_set = spec_set
1098 self.autospec = autospec
1099 self.kwargs = kwargs
1100 self.additional_patchers = []
1101
1102
1103 def copy(self):
1104 patcher = _patch(
1105 self.getter, self.attribute, self.new, self.spec,
1106 self.create, self.spec_set,
1107 self.autospec, self.new_callable, self.kwargs
1108 )
1109 patcher.attribute_name = self.attribute_name
1110 patcher.additional_patchers = [
1111 p.copy() for p in self.additional_patchers
1112 ]
1113 return patcher
1114
1115
1116 def __call__(self, func):
1117 if isinstance(func, type):
1118 return self.decorate_class(func)
1119 return self.decorate_callable(func)
1120
1121
1122 def decorate_class(self, klass):
1123 for attr in dir(klass):
1124 if not attr.startswith(patch.TEST_PREFIX):
1125 continue
1126
1127 attr_value = getattr(klass, attr)
1128 if not hasattr(attr_value, "__call__"):
1129 continue
1130
1131 patcher = self.copy()
1132 setattr(klass, attr, patcher(attr_value))
1133 return klass
1134
1135
1136 def decorate_callable(self, func):
1137 if hasattr(func, 'patchings'):
1138 func.patchings.append(self)
1139 return func
1140
1141 @wraps(func)
1142 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001143 extra_args = []
1144 entered_patchers = []
1145
Michael Foord50a8c0e2012-03-25 18:57:58 +01001146 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001147 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001148 for patching in patched.patchings:
1149 arg = patching.__enter__()
1150 entered_patchers.append(patching)
1151 if patching.attribute_name is not None:
1152 keywargs.update(arg)
1153 elif patching.new is DEFAULT:
1154 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001155
Michael Foordd7c65e22012-03-14 14:56:54 -07001156 args += tuple(extra_args)
1157 return func(*args, **keywargs)
1158 except:
1159 if (patching not in entered_patchers and
1160 _is_started(patching)):
1161 # the patcher may have been started, but an exception
1162 # raised whilst entering one of its additional_patchers
1163 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001164 # Pass the exception to __exit__
1165 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001166 # re-raise the exception
1167 raise
Michael Foord345266a2012-03-14 12:24:34 -07001168 finally:
1169 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001170 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001171
1172 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001173 return patched
1174
1175
1176 def get_original(self):
1177 target = self.getter()
1178 name = self.attribute
1179
1180 original = DEFAULT
1181 local = False
1182
1183 try:
1184 original = target.__dict__[name]
1185 except (AttributeError, KeyError):
1186 original = getattr(target, name, DEFAULT)
1187 else:
1188 local = True
1189
Michael Foordfddcfa22014-04-14 16:25:20 -04001190 if name in _builtins and isinstance(target, ModuleType):
1191 self.create = True
1192
Michael Foord345266a2012-03-14 12:24:34 -07001193 if not self.create and original is DEFAULT:
1194 raise AttributeError(
1195 "%s does not have the attribute %r" % (target, name)
1196 )
1197 return original, local
1198
1199
1200 def __enter__(self):
1201 """Perform the patch."""
1202 new, spec, spec_set = self.new, self.spec, self.spec_set
1203 autospec, kwargs = self.autospec, self.kwargs
1204 new_callable = self.new_callable
1205 self.target = self.getter()
1206
Michael Foord50a8c0e2012-03-25 18:57:58 +01001207 # normalise False to None
1208 if spec is False:
1209 spec = None
1210 if spec_set is False:
1211 spec_set = None
1212 if autospec is False:
1213 autospec = None
1214
1215 if spec is not None and autospec is not None:
1216 raise TypeError("Can't specify spec and autospec")
1217 if ((spec is not None or autospec is not None) and
1218 spec_set not in (True, None)):
1219 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1220
Michael Foord345266a2012-03-14 12:24:34 -07001221 original, local = self.get_original()
1222
Michael Foord50a8c0e2012-03-25 18:57:58 +01001223 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001224 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001225 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001226 # set spec to the object we are replacing
1227 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001228 if spec_set is True:
1229 spec_set = original
1230 spec = None
1231 elif spec is not None:
1232 if spec_set is True:
1233 spec_set = spec
1234 spec = None
1235 elif spec_set is True:
1236 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001237
Michael Foord50a8c0e2012-03-25 18:57:58 +01001238 if spec is not None or spec_set is not None:
1239 if original is DEFAULT:
1240 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001241 if isinstance(original, type):
1242 # If we're patching out a class and there is a spec
1243 inherit = True
1244
1245 Klass = MagicMock
1246 _kwargs = {}
1247 if new_callable is not None:
1248 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001249 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001250 this_spec = spec
1251 if spec_set is not None:
1252 this_spec = spec_set
1253 if _is_list(this_spec):
1254 not_callable = '__call__' not in this_spec
1255 else:
1256 not_callable = not callable(this_spec)
1257 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001258 Klass = NonCallableMagicMock
1259
1260 if spec is not None:
1261 _kwargs['spec'] = spec
1262 if spec_set is not None:
1263 _kwargs['spec_set'] = spec_set
1264
1265 # add a name to mocks
1266 if (isinstance(Klass, type) and
1267 issubclass(Klass, NonCallableMock) and self.attribute):
1268 _kwargs['name'] = self.attribute
1269
1270 _kwargs.update(kwargs)
1271 new = Klass(**_kwargs)
1272
1273 if inherit and _is_instance_mock(new):
1274 # we can only tell if the instance should be callable if the
1275 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001276 this_spec = spec
1277 if spec_set is not None:
1278 this_spec = spec_set
1279 if (not _is_list(this_spec) and not
1280 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001281 Klass = NonCallableMagicMock
1282
1283 _kwargs.pop('name')
1284 new.return_value = Klass(_new_parent=new, _new_name='()',
1285 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001286 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001287 # spec is ignored, new *must* be default, spec_set is treated
1288 # as a boolean. Should we check spec is not None and that spec_set
1289 # is a bool?
1290 if new is not DEFAULT:
1291 raise TypeError(
1292 "autospec creates the mock for you. Can't specify "
1293 "autospec and new."
1294 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001295 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001296 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001297 spec_set = bool(spec_set)
1298 if autospec is True:
1299 autospec = original
1300
1301 new = create_autospec(autospec, spec_set=spec_set,
1302 _name=self.attribute, **kwargs)
1303 elif kwargs:
1304 # can't set keyword args when we aren't creating the mock
1305 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1306 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1307
1308 new_attr = new
1309
1310 self.temp_original = original
1311 self.is_local = local
1312 setattr(self.target, self.attribute, new_attr)
1313 if self.attribute_name is not None:
1314 extra_args = {}
1315 if self.new is DEFAULT:
1316 extra_args[self.attribute_name] = new
1317 for patching in self.additional_patchers:
1318 arg = patching.__enter__()
1319 if patching.new is DEFAULT:
1320 extra_args.update(arg)
1321 return extra_args
1322
1323 return new
1324
1325
Michael Foord50a8c0e2012-03-25 18:57:58 +01001326 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001327 """Undo the patch."""
1328 if not _is_started(self):
1329 raise RuntimeError('stop called on unstarted patcher')
1330
1331 if self.is_local and self.temp_original is not DEFAULT:
1332 setattr(self.target, self.attribute, self.temp_original)
1333 else:
1334 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001335 if not self.create and (not hasattr(self.target, self.attribute) or
1336 self.attribute in ('__doc__', '__module__',
1337 '__defaults__', '__annotations__',
1338 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001339 # needed for proxy objects like django settings
1340 setattr(self.target, self.attribute, self.temp_original)
1341
1342 del self.temp_original
1343 del self.is_local
1344 del self.target
1345 for patcher in reversed(self.additional_patchers):
1346 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001347 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001348
Michael Foordf7c41582012-06-10 20:36:32 +01001349
1350 def start(self):
1351 """Activate a patch, returning any created mock."""
1352 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001353 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001354 return result
1355
1356
1357 def stop(self):
1358 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001359 try:
1360 self._active_patches.remove(self)
1361 except ValueError:
1362 # If the patch hasn't been started this will fail
1363 pass
1364
Michael Foordf7c41582012-06-10 20:36:32 +01001365 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001366
1367
1368
1369def _get_target(target):
1370 try:
1371 target, attribute = target.rsplit('.', 1)
1372 except (TypeError, ValueError):
1373 raise TypeError("Need a valid target to patch. You supplied: %r" %
1374 (target,))
1375 getter = lambda: _importer(target)
1376 return getter, attribute
1377
1378
1379def _patch_object(
1380 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001381 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001382 new_callable=None, **kwargs
1383 ):
1384 """
Michael Foord345266a2012-03-14 12:24:34 -07001385 patch the named member (`attribute`) on an object (`target`) with a mock
1386 object.
1387
1388 `patch.object` can be used as a decorator, class decorator or a context
1389 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1390 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1391 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1392 the mock object it creates.
1393
1394 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1395 for choosing which methods to wrap.
1396 """
1397 getter = lambda: target
1398 return _patch(
1399 getter, attribute, new, spec, create,
1400 spec_set, autospec, new_callable, kwargs
1401 )
1402
1403
Michael Foord50a8c0e2012-03-25 18:57:58 +01001404def _patch_multiple(target, spec=None, create=False, spec_set=None,
1405 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001406 """Perform multiple patches in a single call. It takes the object to be
1407 patched (either as an object or a string to fetch the object by importing)
1408 and keyword arguments for the patches::
1409
1410 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1411 ...
1412
1413 Use `DEFAULT` as the value if you want `patch.multiple` to create
1414 mocks for you. In this case the created mocks are passed into a decorated
1415 function by keyword, and a dictionary is returned when `patch.multiple` is
1416 used as a context manager.
1417
1418 `patch.multiple` can be used as a decorator, class decorator or a context
1419 manager. The arguments `spec`, `spec_set`, `create`,
1420 `autospec` and `new_callable` have the same meaning as for `patch`. These
1421 arguments will be applied to *all* patches done by `patch.multiple`.
1422
1423 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1424 for choosing which methods to wrap.
1425 """
1426 if type(target) is str:
1427 getter = lambda: _importer(target)
1428 else:
1429 getter = lambda: target
1430
1431 if not kwargs:
1432 raise ValueError(
1433 'Must supply at least one keyword argument with patch.multiple'
1434 )
1435 # need to wrap in a list for python 3, where items is a view
1436 items = list(kwargs.items())
1437 attribute, new = items[0]
1438 patcher = _patch(
1439 getter, attribute, new, spec, create, spec_set,
1440 autospec, new_callable, {}
1441 )
1442 patcher.attribute_name = attribute
1443 for attribute, new in items[1:]:
1444 this_patcher = _patch(
1445 getter, attribute, new, spec, create, spec_set,
1446 autospec, new_callable, {}
1447 )
1448 this_patcher.attribute_name = attribute
1449 patcher.additional_patchers.append(this_patcher)
1450 return patcher
1451
1452
1453def patch(
1454 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001455 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001456 ):
1457 """
1458 `patch` acts as a function decorator, class decorator or a context
1459 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001460 is patched with a `new` object. When the function/with statement exits
1461 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001462
Michael Foord54b3db82012-03-28 15:08:08 +01001463 If `new` is omitted, then the target is replaced with a
1464 `MagicMock`. If `patch` is used as a decorator and `new` is
1465 omitted, the created mock is passed in as an extra argument to the
1466 decorated function. If `patch` is used as a context manager the created
1467 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001468
Michael Foord54b3db82012-03-28 15:08:08 +01001469 `target` should be a string in the form `'package.module.ClassName'`. The
1470 `target` is imported and the specified object replaced with the `new`
1471 object, so the `target` must be importable from the environment you are
1472 calling `patch` from. The target is imported when the decorated function
1473 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001474
1475 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1476 if patch is creating one for you.
1477
1478 In addition you can pass `spec=True` or `spec_set=True`, which causes
1479 patch to pass in the object being mocked as the spec/spec_set object.
1480
1481 `new_callable` allows you to specify a different class, or callable object,
1482 that will be called to create the `new` object. By default `MagicMock` is
1483 used.
1484
1485 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001486 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001487 All attributes of the mock will also have the spec of the corresponding
1488 attribute of the object being replaced. Methods and functions being
1489 mocked will have their arguments checked and will raise a `TypeError` if
1490 they are called with the wrong signature. For mocks replacing a class,
1491 their return value (the 'instance') will have the same spec as the class.
1492
1493 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1494 arbitrary object as the spec instead of the one being replaced.
1495
1496 By default `patch` will fail to replace attributes that don't exist. If
1497 you pass in `create=True`, and the attribute doesn't exist, patch will
1498 create the attribute for you when the patched function is called, and
1499 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001500 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001501 default because it can be dangerous. With it switched on you can write
1502 passing tests against APIs that don't actually exist!
1503
1504 Patch can be used as a `TestCase` class decorator. It works by
1505 decorating each test method in the class. This reduces the boilerplate
1506 code when your test methods share a common patchings set. `patch` finds
1507 tests by looking for method names that start with `patch.TEST_PREFIX`.
1508 By default this is `test`, which matches the way `unittest` finds tests.
1509 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1510
1511 Patch can be used as a context manager, with the with statement. Here the
1512 patching applies to the indented block after the with statement. If you
1513 use "as" then the patched object will be bound to the name after the
1514 "as"; very useful if `patch` is creating a mock object for you.
1515
1516 `patch` takes arbitrary keyword arguments. These will be passed to
1517 the `Mock` (or `new_callable`) on construction.
1518
1519 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1520 available for alternate use-cases.
1521 """
1522 getter, attribute = _get_target(target)
1523 return _patch(
1524 getter, attribute, new, spec, create,
1525 spec_set, autospec, new_callable, kwargs
1526 )
1527
1528
1529class _patch_dict(object):
1530 """
1531 Patch a dictionary, or dictionary like object, and restore the dictionary
1532 to its original state after the test.
1533
1534 `in_dict` can be a dictionary or a mapping like container. If it is a
1535 mapping then it must at least support getting, setting and deleting items
1536 plus iterating over keys.
1537
1538 `in_dict` can also be a string specifying the name of the dictionary, which
1539 will then be fetched by importing it.
1540
1541 `values` can be a dictionary of values to set in the dictionary. `values`
1542 can also be an iterable of `(key, value)` pairs.
1543
1544 If `clear` is True then the dictionary will be cleared before the new
1545 values are set.
1546
1547 `patch.dict` can also be called with arbitrary keyword arguments to set
1548 values in the dictionary::
1549
1550 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1551 ...
1552
1553 `patch.dict` can be used as a context manager, decorator or class
1554 decorator. When used as a class decorator `patch.dict` honours
1555 `patch.TEST_PREFIX` for choosing which methods to wrap.
1556 """
1557
1558 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1559 if isinstance(in_dict, str):
1560 in_dict = _importer(in_dict)
1561 self.in_dict = in_dict
1562 # support any argument supported by dict(...) constructor
1563 self.values = dict(values)
1564 self.values.update(kwargs)
1565 self.clear = clear
1566 self._original = None
1567
1568
1569 def __call__(self, f):
1570 if isinstance(f, type):
1571 return self.decorate_class(f)
1572 @wraps(f)
1573 def _inner(*args, **kw):
1574 self._patch_dict()
1575 try:
1576 return f(*args, **kw)
1577 finally:
1578 self._unpatch_dict()
1579
1580 return _inner
1581
1582
1583 def decorate_class(self, klass):
1584 for attr in dir(klass):
1585 attr_value = getattr(klass, attr)
1586 if (attr.startswith(patch.TEST_PREFIX) and
1587 hasattr(attr_value, "__call__")):
1588 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1589 decorated = decorator(attr_value)
1590 setattr(klass, attr, decorated)
1591 return klass
1592
1593
1594 def __enter__(self):
1595 """Patch the dict."""
1596 self._patch_dict()
1597
1598
1599 def _patch_dict(self):
1600 values = self.values
1601 in_dict = self.in_dict
1602 clear = self.clear
1603
1604 try:
1605 original = in_dict.copy()
1606 except AttributeError:
1607 # dict like object with no copy method
1608 # must support iteration over keys
1609 original = {}
1610 for key in in_dict:
1611 original[key] = in_dict[key]
1612 self._original = original
1613
1614 if clear:
1615 _clear_dict(in_dict)
1616
1617 try:
1618 in_dict.update(values)
1619 except AttributeError:
1620 # dict like object with no update method
1621 for key in values:
1622 in_dict[key] = values[key]
1623
1624
1625 def _unpatch_dict(self):
1626 in_dict = self.in_dict
1627 original = self._original
1628
1629 _clear_dict(in_dict)
1630
1631 try:
1632 in_dict.update(original)
1633 except AttributeError:
1634 for key in original:
1635 in_dict[key] = original[key]
1636
1637
1638 def __exit__(self, *args):
1639 """Unpatch the dict."""
1640 self._unpatch_dict()
1641 return False
1642
1643 start = __enter__
1644 stop = __exit__
1645
1646
1647def _clear_dict(in_dict):
1648 try:
1649 in_dict.clear()
1650 except AttributeError:
1651 keys = list(in_dict)
1652 for key in keys:
1653 del in_dict[key]
1654
1655
Michael Foordf7c41582012-06-10 20:36:32 +01001656def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001657 """Stop all active patches. LIFO to unroll nested patches."""
1658 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001659 patch.stop()
1660
1661
Michael Foord345266a2012-03-14 12:24:34 -07001662patch.object = _patch_object
1663patch.dict = _patch_dict
1664patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001665patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001666patch.TEST_PREFIX = 'test'
1667
1668magic_methods = (
1669 "lt le gt ge eq ne "
1670 "getitem setitem delitem "
1671 "len contains iter "
1672 "hash str sizeof "
1673 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001674 # we added divmod and rdivmod here instead of numerics
1675 # because there is no idivmod
1676 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001677 "complex int float index "
1678 "trunc floor ceil "
1679 "bool next "
1680)
1681
Michael Foordd2623d72014-04-14 11:23:48 -04001682numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001683 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001684)
Michael Foord345266a2012-03-14 12:24:34 -07001685inplace = ' '.join('i%s' % n for n in numerics.split())
1686right = ' '.join('r%s' % n for n in numerics.split())
1687
1688# not including __prepare__, __instancecheck__, __subclasscheck__
1689# (as they are metaclass methods)
1690# __del__ is not supported at all as it causes problems if it exists
1691
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001692_non_defaults = {
1693 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1694 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1695 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1696 '__repr__', '__dir__', '__subclasses__', '__format__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001697}
Michael Foord345266a2012-03-14 12:24:34 -07001698
1699
1700def _get_method(name, func):
1701 "Turns a callable object (like a mock) into a real function"
1702 def method(self, *args, **kw):
1703 return func(self, *args, **kw)
1704 method.__name__ = name
1705 return method
1706
1707
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001708_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001709 '__%s__' % method for method in
1710 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001711}
Michael Foord345266a2012-03-14 12:24:34 -07001712
1713_all_magics = _magics | _non_defaults
1714
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001715_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001716 '__getattr__', '__setattr__',
1717 '__init__', '__new__', '__prepare__'
1718 '__instancecheck__', '__subclasscheck__',
1719 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001720}
Michael Foord345266a2012-03-14 12:24:34 -07001721
1722_calculate_return_value = {
1723 '__hash__': lambda self: object.__hash__(self),
1724 '__str__': lambda self: object.__str__(self),
1725 '__sizeof__': lambda self: object.__sizeof__(self),
1726}
1727
1728_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001729 '__lt__': NotImplemented,
1730 '__gt__': NotImplemented,
1731 '__le__': NotImplemented,
1732 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001733 '__int__': 1,
1734 '__contains__': False,
1735 '__len__': 0,
1736 '__exit__': False,
1737 '__complex__': 1j,
1738 '__float__': 1.0,
1739 '__bool__': True,
1740 '__index__': 1,
1741}
1742
1743
1744def _get_eq(self):
1745 def __eq__(other):
1746 ret_val = self.__eq__._mock_return_value
1747 if ret_val is not DEFAULT:
1748 return ret_val
1749 return self is other
1750 return __eq__
1751
1752def _get_ne(self):
1753 def __ne__(other):
1754 if self.__ne__._mock_return_value is not DEFAULT:
1755 return DEFAULT
1756 return self is not other
1757 return __ne__
1758
1759def _get_iter(self):
1760 def __iter__():
1761 ret_val = self.__iter__._mock_return_value
1762 if ret_val is DEFAULT:
1763 return iter([])
1764 # if ret_val was already an iterator, then calling iter on it should
1765 # return the iterator unchanged
1766 return iter(ret_val)
1767 return __iter__
1768
1769_side_effect_methods = {
1770 '__eq__': _get_eq,
1771 '__ne__': _get_ne,
1772 '__iter__': _get_iter,
1773}
1774
1775
1776
1777def _set_return_value(mock, method, name):
1778 fixed = _return_values.get(name, DEFAULT)
1779 if fixed is not DEFAULT:
1780 method.return_value = fixed
1781 return
1782
1783 return_calulator = _calculate_return_value.get(name)
1784 if return_calulator is not None:
1785 try:
1786 return_value = return_calulator(mock)
1787 except AttributeError:
1788 # XXXX why do we return AttributeError here?
1789 # set it as a side_effect instead?
1790 return_value = AttributeError(name)
1791 method.return_value = return_value
1792 return
1793
1794 side_effector = _side_effect_methods.get(name)
1795 if side_effector is not None:
1796 method.side_effect = side_effector(mock)
1797
1798
1799
1800class MagicMixin(object):
1801 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001802 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001803 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001804 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001805
1806
1807 def _mock_set_magics(self):
1808 these_magics = _magics
1809
Łukasz Langaa468db92015-04-13 23:12:42 -07001810 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001811 these_magics = _magics.intersection(self._mock_methods)
1812
1813 remove_magics = set()
1814 remove_magics = _magics - these_magics
1815
1816 for entry in remove_magics:
1817 if entry in type(self).__dict__:
1818 # remove unneeded magic methods
1819 delattr(self, entry)
1820
1821 # don't overwrite existing attributes if called a second time
1822 these_magics = these_magics - set(type(self).__dict__)
1823
1824 _type = type(self)
1825 for entry in these_magics:
1826 setattr(_type, entry, MagicProxy(entry, self))
1827
1828
1829
1830class NonCallableMagicMock(MagicMixin, NonCallableMock):
1831 """A version of `MagicMock` that isn't callable."""
1832 def mock_add_spec(self, spec, spec_set=False):
1833 """Add a spec to a mock. `spec` can either be an object or a
1834 list of strings. Only attributes on the `spec` can be fetched as
1835 attributes from the mock.
1836
1837 If `spec_set` is True then only attributes on the spec can be set."""
1838 self._mock_add_spec(spec, spec_set)
1839 self._mock_set_magics()
1840
1841
1842
1843class MagicMock(MagicMixin, Mock):
1844 """
1845 MagicMock is a subclass of Mock with default implementations
1846 of most of the magic methods. You can use MagicMock without having to
1847 configure the magic methods yourself.
1848
1849 If you use the `spec` or `spec_set` arguments then *only* magic
1850 methods that exist in the spec will be created.
1851
1852 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1853 """
1854 def mock_add_spec(self, spec, spec_set=False):
1855 """Add a spec to a mock. `spec` can either be an object or a
1856 list of strings. Only attributes on the `spec` can be fetched as
1857 attributes from the mock.
1858
1859 If `spec_set` is True then only attributes on the spec can be set."""
1860 self._mock_add_spec(spec, spec_set)
1861 self._mock_set_magics()
1862
1863
1864
1865class MagicProxy(object):
1866 def __init__(self, name, parent):
1867 self.name = name
1868 self.parent = parent
1869
1870 def __call__(self, *args, **kwargs):
1871 m = self.create_mock()
1872 return m(*args, **kwargs)
1873
1874 def create_mock(self):
1875 entry = self.name
1876 parent = self.parent
1877 m = parent._get_child_mock(name=entry, _new_name=entry,
1878 _new_parent=parent)
1879 setattr(parent, entry, m)
1880 _set_return_value(parent, m, entry)
1881 return m
1882
1883 def __get__(self, obj, _type=None):
1884 return self.create_mock()
1885
1886
1887
1888class _ANY(object):
1889 "A helper object that compares equal to everything."
1890
1891 def __eq__(self, other):
1892 return True
1893
1894 def __ne__(self, other):
1895 return False
1896
1897 def __repr__(self):
1898 return '<ANY>'
1899
1900ANY = _ANY()
1901
1902
1903
1904def _format_call_signature(name, args, kwargs):
1905 message = '%s(%%s)' % name
1906 formatted_args = ''
1907 args_string = ', '.join([repr(arg) for arg in args])
1908 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301909 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001910 ])
1911 if args_string:
1912 formatted_args = args_string
1913 if kwargs_string:
1914 if formatted_args:
1915 formatted_args += ', '
1916 formatted_args += kwargs_string
1917
1918 return message % formatted_args
1919
1920
1921
1922class _Call(tuple):
1923 """
1924 A tuple for holding the results of a call to a mock, either in the form
1925 `(args, kwargs)` or `(name, args, kwargs)`.
1926
1927 If args or kwargs are empty then a call tuple will compare equal to
1928 a tuple without those values. This makes comparisons less verbose::
1929
1930 _Call(('name', (), {})) == ('name',)
1931 _Call(('name', (1,), {})) == ('name', (1,))
1932 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1933
1934 The `_Call` object provides a useful shortcut for comparing with call::
1935
1936 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1937 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1938
1939 If the _Call has no name then it will match any name.
1940 """
1941 def __new__(cls, value=(), name=None, parent=None, two=False,
1942 from_kall=True):
1943 name = ''
1944 args = ()
1945 kwargs = {}
1946 _len = len(value)
1947 if _len == 3:
1948 name, args, kwargs = value
1949 elif _len == 2:
1950 first, second = value
1951 if isinstance(first, str):
1952 name = first
1953 if isinstance(second, tuple):
1954 args = second
1955 else:
1956 kwargs = second
1957 else:
1958 args, kwargs = first, second
1959 elif _len == 1:
1960 value, = value
1961 if isinstance(value, str):
1962 name = value
1963 elif isinstance(value, tuple):
1964 args = value
1965 else:
1966 kwargs = value
1967
1968 if two:
1969 return tuple.__new__(cls, (args, kwargs))
1970
1971 return tuple.__new__(cls, (name, args, kwargs))
1972
1973
1974 def __init__(self, value=(), name=None, parent=None, two=False,
1975 from_kall=True):
1976 self.name = name
1977 self.parent = parent
1978 self.from_kall = from_kall
1979
1980
1981 def __eq__(self, other):
1982 if other is ANY:
1983 return True
1984 try:
1985 len_other = len(other)
1986 except TypeError:
1987 return False
1988
1989 self_name = ''
1990 if len(self) == 2:
1991 self_args, self_kwargs = self
1992 else:
1993 self_name, self_args, self_kwargs = self
1994
1995 other_name = ''
1996 if len_other == 0:
1997 other_args, other_kwargs = (), {}
1998 elif len_other == 3:
1999 other_name, other_args, other_kwargs = other
2000 elif len_other == 1:
2001 value, = other
2002 if isinstance(value, tuple):
2003 other_args = value
2004 other_kwargs = {}
2005 elif isinstance(value, str):
2006 other_name = value
2007 other_args, other_kwargs = (), {}
2008 else:
2009 other_args = ()
2010 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002011 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002012 # could be (name, args) or (name, kwargs) or (args, kwargs)
2013 first, second = other
2014 if isinstance(first, str):
2015 other_name = first
2016 if isinstance(second, tuple):
2017 other_args, other_kwargs = second, {}
2018 else:
2019 other_args, other_kwargs = (), second
2020 else:
2021 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002022 else:
2023 return False
Michael Foord345266a2012-03-14 12:24:34 -07002024
2025 if self_name and other_name != self_name:
2026 return False
2027
2028 # this order is important for ANY to work!
2029 return (other_args, other_kwargs) == (self_args, self_kwargs)
2030
2031
Michael Foord345266a2012-03-14 12:24:34 -07002032 def __call__(self, *args, **kwargs):
2033 if self.name is None:
2034 return _Call(('', args, kwargs), name='()')
2035
2036 name = self.name + '()'
2037 return _Call((self.name, args, kwargs), name=name, parent=self)
2038
2039
2040 def __getattr__(self, attr):
2041 if self.name is None:
2042 return _Call(name=attr, from_kall=False)
2043 name = '%s.%s' % (self.name, attr)
2044 return _Call(name=name, parent=self, from_kall=False)
2045
2046
Kushal Dasa37b9582014-09-16 18:33:37 +05302047 def count(self, *args, **kwargs):
2048 return self.__getattr__('count')(*args, **kwargs)
2049
2050 def index(self, *args, **kwargs):
2051 return self.__getattr__('index')(*args, **kwargs)
2052
Michael Foord345266a2012-03-14 12:24:34 -07002053 def __repr__(self):
2054 if not self.from_kall:
2055 name = self.name or 'call'
2056 if name.startswith('()'):
2057 name = 'call%s' % name
2058 return name
2059
2060 if len(self) == 2:
2061 name = 'call'
2062 args, kwargs = self
2063 else:
2064 name, args, kwargs = self
2065 if not name:
2066 name = 'call'
2067 elif not name.startswith('()'):
2068 name = 'call.%s' % name
2069 else:
2070 name = 'call%s' % name
2071 return _format_call_signature(name, args, kwargs)
2072
2073
2074 def call_list(self):
2075 """For a call object that represents multiple calls, `call_list`
2076 returns a list of all the intermediate calls as well as the
2077 final call."""
2078 vals = []
2079 thing = self
2080 while thing is not None:
2081 if thing.from_kall:
2082 vals.append(thing)
2083 thing = thing.parent
2084 return _CallList(reversed(vals))
2085
2086
2087call = _Call(from_kall=False)
2088
2089
2090
2091def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2092 _name=None, **kwargs):
2093 """Create a mock object using another object as a spec. Attributes on the
2094 mock will use the corresponding attribute on the `spec` object as their
2095 spec.
2096
2097 Functions or methods being mocked will have their arguments checked
2098 to check that they are called with the correct signature.
2099
2100 If `spec_set` is True then attempting to set attributes that don't exist
2101 on the spec object will raise an `AttributeError`.
2102
2103 If a class is used as a spec then the return value of the mock (the
2104 instance of the class) will have the same spec. You can use a class as the
2105 spec for an instance object by passing `instance=True`. The returned mock
2106 will only be callable if instances of the mock are callable.
2107
2108 `create_autospec` also takes arbitrary keyword arguments that are passed to
2109 the constructor of the created mock."""
2110 if _is_list(spec):
2111 # can't pass a list instance to the mock constructor as it will be
2112 # interpreted as a list of strings
2113 spec = type(spec)
2114
2115 is_type = isinstance(spec, type)
2116
2117 _kwargs = {'spec': spec}
2118 if spec_set:
2119 _kwargs = {'spec_set': spec}
2120 elif spec is None:
2121 # None we mock with a normal mock without a spec
2122 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002123 if _kwargs and instance:
2124 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002125
2126 _kwargs.update(kwargs)
2127
2128 Klass = MagicMock
2129 if type(spec) in DescriptorTypes:
2130 # descriptors don't have a spec
2131 # because we don't know what type they return
2132 _kwargs = {}
2133 elif not _callable(spec):
2134 Klass = NonCallableMagicMock
2135 elif is_type and instance and not _instance_callable(spec):
2136 Klass = NonCallableMagicMock
2137
Kushal Das484f8a82014-04-16 01:05:50 +05302138 _name = _kwargs.pop('name', _name)
2139
Michael Foord345266a2012-03-14 12:24:34 -07002140 _new_name = _name
2141 if _parent is None:
2142 # for a top level object no _new_name should be set
2143 _new_name = ''
2144
2145 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2146 name=_name, **_kwargs)
2147
2148 if isinstance(spec, FunctionTypes):
2149 # should only happen at the top level because we don't
2150 # recurse for functions
2151 mock = _set_signature(mock, spec)
2152 else:
2153 _check_signature(spec, mock, is_type, instance)
2154
2155 if _parent is not None and not instance:
2156 _parent._mock_children[_name] = mock
2157
2158 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002159 mock.return_value = create_autospec(spec, spec_set, instance=True,
2160 _name='()', _parent=mock)
2161
2162 for entry in dir(spec):
2163 if _is_magic(entry):
2164 # MagicMock already does the useful magic methods for us
2165 continue
2166
Michael Foord345266a2012-03-14 12:24:34 -07002167 # XXXX do we need a better way of getting attributes without
2168 # triggering code execution (?) Probably not - we need the actual
2169 # object to mock it so we would rather trigger a property than mock
2170 # the property descriptor. Likewise we want to mock out dynamically
2171 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002172 # XXXX what about attributes that raise exceptions other than
2173 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002174 # we could be resilient against it, or catch and propagate the
2175 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002176 try:
2177 original = getattr(spec, entry)
2178 except AttributeError:
2179 continue
Michael Foord345266a2012-03-14 12:24:34 -07002180
2181 kwargs = {'spec': original}
2182 if spec_set:
2183 kwargs = {'spec_set': original}
2184
2185 if not isinstance(original, FunctionTypes):
2186 new = _SpecState(original, spec_set, mock, entry, instance)
2187 mock._mock_children[entry] = new
2188 else:
2189 parent = mock
2190 if isinstance(spec, FunctionTypes):
2191 parent = mock.mock
2192
Michael Foord345266a2012-03-14 12:24:34 -07002193 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002194 kwargs['_eat_self'] = skipfirst
2195 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2196 _new_parent=parent,
2197 **kwargs)
2198 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002199 _check_signature(original, new, skipfirst=skipfirst)
2200
2201 # so functions created with _set_signature become instance attributes,
2202 # *plus* their underlying mock exists in _mock_children of the parent
2203 # mock. Adding to _mock_children may be unnecessary where we are also
2204 # setting as an instance attribute?
2205 if isinstance(new, FunctionTypes):
2206 setattr(mock, entry, new)
2207
2208 return mock
2209
2210
2211def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002212 """
2213 Return whether we should skip the first argument on spec's `entry`
2214 attribute.
2215 """
Michael Foord345266a2012-03-14 12:24:34 -07002216 if not isinstance(spec, type):
2217 if entry in getattr(spec, '__dict__', {}):
2218 # instance attribute - shouldn't skip
2219 return False
Michael Foord345266a2012-03-14 12:24:34 -07002220 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002221
2222 for klass in spec.__mro__:
2223 result = klass.__dict__.get(entry, DEFAULT)
2224 if result is DEFAULT:
2225 continue
2226 if isinstance(result, (staticmethod, classmethod)):
2227 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002228 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2229 # Normal method => skip if looked up on type
2230 # (if looked up on instance, self is already skipped)
2231 return is_type
2232 else:
2233 return False
Michael Foord345266a2012-03-14 12:24:34 -07002234
2235 # shouldn't get here unless function is a dynamically provided attribute
2236 # XXXX untested behaviour
2237 return is_type
2238
2239
2240def _get_class(obj):
2241 try:
2242 return obj.__class__
2243 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002244 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002245 return type(obj)
2246
2247
2248class _SpecState(object):
2249
2250 def __init__(self, spec, spec_set=False, parent=None,
2251 name=None, ids=None, instance=False):
2252 self.spec = spec
2253 self.ids = ids
2254 self.spec_set = spec_set
2255 self.parent = parent
2256 self.instance = instance
2257 self.name = name
2258
2259
2260FunctionTypes = (
2261 # python function
2262 type(create_autospec),
2263 # instance method
2264 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002265)
2266
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002267MethodWrapperTypes = (
2268 type(ANY.__eq__.__get__),
2269)
2270
Michael Foord345266a2012-03-14 12:24:34 -07002271
Michael Foorda74561a2012-03-25 19:03:13 +01002272file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002273
Michael Foord04cbe0c2013-03-19 17:22:51 -07002274def _iterate_read_data(read_data):
2275 # Helper for mock_open:
2276 # Retrieve lines from read_data via a generator so that separate calls to
2277 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002278 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2279 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002280
Berker Peksag86b34da2015-08-06 13:15:51 +03002281 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002282 # If the last line ended in a newline, the list comprehension will have an
2283 # extra entry that's just a newline. Remove this.
2284 data_as_list = data_as_list[:-1]
2285 else:
2286 # If there wasn't an extra newline by itself, then the file being
2287 # emulated doesn't have a newline to end the last line remove the
2288 # newline that our naive format() added
2289 data_as_list[-1] = data_as_list[-1][:-1]
2290
2291 for line in data_as_list:
2292 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002293
Robert Collins5329aaa2015-07-17 20:08:45 +12002294
Michael Foord0dccf652012-03-25 19:11:50 +01002295def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002296 """
2297 A helper function to create a mock to replace the use of `open`. It works
2298 for `open` called directly or used as a context manager.
2299
2300 The `mock` argument is the mock object to configure. If `None` (the
2301 default) then a `MagicMock` will be created for you, with the API limited
2302 to methods or attributes available on standard file handles.
2303
Michael Foord04cbe0c2013-03-19 17:22:51 -07002304 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2305 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002306 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002307 def _readlines_side_effect(*args, **kwargs):
2308 if handle.readlines.return_value is not None:
2309 return handle.readlines.return_value
2310 return list(_state[0])
2311
2312 def _read_side_effect(*args, **kwargs):
2313 if handle.read.return_value is not None:
2314 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002315 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002316
2317 def _readline_side_effect():
2318 if handle.readline.return_value is not None:
2319 while True:
2320 yield handle.readline.return_value
2321 for line in _state[0]:
2322 yield line
2323
2324
Michael Foorda74561a2012-03-25 19:03:13 +01002325 global file_spec
2326 if file_spec is None:
2327 import _io
2328 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2329
Michael Foord345266a2012-03-14 12:24:34 -07002330 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002331 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002332
Robert Collinsca647ef2015-07-24 03:48:20 +12002333 handle = MagicMock(spec=file_spec)
2334 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002335
Robert Collinsca647ef2015-07-24 03:48:20 +12002336 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002337
Robert Collinsca647ef2015-07-24 03:48:20 +12002338 handle.write.return_value = None
2339 handle.read.return_value = None
2340 handle.readline.return_value = None
2341 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002342
Robert Collinsca647ef2015-07-24 03:48:20 +12002343 handle.read.side_effect = _read_side_effect
2344 _state[1] = _readline_side_effect()
2345 handle.readline.side_effect = _state[1]
2346 handle.readlines.side_effect = _readlines_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002347
Robert Collinsca647ef2015-07-24 03:48:20 +12002348 def reset_data(*args, **kwargs):
2349 _state[0] = _iterate_read_data(read_data)
2350 if handle.readline.side_effect == _state[1]:
2351 # Only reset the side effect if the user hasn't overridden it.
2352 _state[1] = _readline_side_effect()
2353 handle.readline.side_effect = _state[1]
2354 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002355
Robert Collinsca647ef2015-07-24 03:48:20 +12002356 mock.side_effect = reset_data
2357 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002358 return mock
2359
2360
2361class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002362 """
2363 A mock intended to be used as a property, or other descriptor, on a class.
2364 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2365 a return value when it is fetched.
2366
2367 Fetching a `PropertyMock` instance from an object calls the mock, with
2368 no args. Setting it calls the mock with the value being set.
2369 """
Michael Foordc2870622012-04-13 16:57:22 +01002370 def _get_child_mock(self, **kwargs):
2371 return MagicMock(**kwargs)
2372
Michael Foord345266a2012-03-14 12:24:34 -07002373 def __get__(self, obj, obj_type):
2374 return self()
2375 def __set__(self, obj, val):
2376 self(val)