blob: 99ce1e2bf45ce6ff0082eea5f9efbcb630e8b3f1 [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)
1335 if not self.create and not hasattr(self.target, self.attribute):
1336 # needed for proxy objects like django settings
1337 setattr(self.target, self.attribute, self.temp_original)
1338
1339 del self.temp_original
1340 del self.is_local
1341 del self.target
1342 for patcher in reversed(self.additional_patchers):
1343 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001344 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001345
Michael Foordf7c41582012-06-10 20:36:32 +01001346
1347 def start(self):
1348 """Activate a patch, returning any created mock."""
1349 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001350 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001351 return result
1352
1353
1354 def stop(self):
1355 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001356 try:
1357 self._active_patches.remove(self)
1358 except ValueError:
1359 # If the patch hasn't been started this will fail
1360 pass
1361
Michael Foordf7c41582012-06-10 20:36:32 +01001362 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001363
1364
1365
1366def _get_target(target):
1367 try:
1368 target, attribute = target.rsplit('.', 1)
1369 except (TypeError, ValueError):
1370 raise TypeError("Need a valid target to patch. You supplied: %r" %
1371 (target,))
1372 getter = lambda: _importer(target)
1373 return getter, attribute
1374
1375
1376def _patch_object(
1377 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001378 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001379 new_callable=None, **kwargs
1380 ):
1381 """
Michael Foord345266a2012-03-14 12:24:34 -07001382 patch the named member (`attribute`) on an object (`target`) with a mock
1383 object.
1384
1385 `patch.object` can be used as a decorator, class decorator or a context
1386 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1387 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1388 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1389 the mock object it creates.
1390
1391 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1392 for choosing which methods to wrap.
1393 """
1394 getter = lambda: target
1395 return _patch(
1396 getter, attribute, new, spec, create,
1397 spec_set, autospec, new_callable, kwargs
1398 )
1399
1400
Michael Foord50a8c0e2012-03-25 18:57:58 +01001401def _patch_multiple(target, spec=None, create=False, spec_set=None,
1402 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001403 """Perform multiple patches in a single call. It takes the object to be
1404 patched (either as an object or a string to fetch the object by importing)
1405 and keyword arguments for the patches::
1406
1407 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1408 ...
1409
1410 Use `DEFAULT` as the value if you want `patch.multiple` to create
1411 mocks for you. In this case the created mocks are passed into a decorated
1412 function by keyword, and a dictionary is returned when `patch.multiple` is
1413 used as a context manager.
1414
1415 `patch.multiple` can be used as a decorator, class decorator or a context
1416 manager. The arguments `spec`, `spec_set`, `create`,
1417 `autospec` and `new_callable` have the same meaning as for `patch`. These
1418 arguments will be applied to *all* patches done by `patch.multiple`.
1419
1420 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1421 for choosing which methods to wrap.
1422 """
1423 if type(target) is str:
1424 getter = lambda: _importer(target)
1425 else:
1426 getter = lambda: target
1427
1428 if not kwargs:
1429 raise ValueError(
1430 'Must supply at least one keyword argument with patch.multiple'
1431 )
1432 # need to wrap in a list for python 3, where items is a view
1433 items = list(kwargs.items())
1434 attribute, new = items[0]
1435 patcher = _patch(
1436 getter, attribute, new, spec, create, spec_set,
1437 autospec, new_callable, {}
1438 )
1439 patcher.attribute_name = attribute
1440 for attribute, new in items[1:]:
1441 this_patcher = _patch(
1442 getter, attribute, new, spec, create, spec_set,
1443 autospec, new_callable, {}
1444 )
1445 this_patcher.attribute_name = attribute
1446 patcher.additional_patchers.append(this_patcher)
1447 return patcher
1448
1449
1450def patch(
1451 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001452 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001453 ):
1454 """
1455 `patch` acts as a function decorator, class decorator or a context
1456 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001457 is patched with a `new` object. When the function/with statement exits
1458 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001459
Michael Foord54b3db82012-03-28 15:08:08 +01001460 If `new` is omitted, then the target is replaced with a
1461 `MagicMock`. If `patch` is used as a decorator and `new` is
1462 omitted, the created mock is passed in as an extra argument to the
1463 decorated function. If `patch` is used as a context manager the created
1464 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001465
Michael Foord54b3db82012-03-28 15:08:08 +01001466 `target` should be a string in the form `'package.module.ClassName'`. The
1467 `target` is imported and the specified object replaced with the `new`
1468 object, so the `target` must be importable from the environment you are
1469 calling `patch` from. The target is imported when the decorated function
1470 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001471
1472 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1473 if patch is creating one for you.
1474
1475 In addition you can pass `spec=True` or `spec_set=True`, which causes
1476 patch to pass in the object being mocked as the spec/spec_set object.
1477
1478 `new_callable` allows you to specify a different class, or callable object,
1479 that will be called to create the `new` object. By default `MagicMock` is
1480 used.
1481
1482 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001483 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001484 All attributes of the mock will also have the spec of the corresponding
1485 attribute of the object being replaced. Methods and functions being
1486 mocked will have their arguments checked and will raise a `TypeError` if
1487 they are called with the wrong signature. For mocks replacing a class,
1488 their return value (the 'instance') will have the same spec as the class.
1489
1490 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1491 arbitrary object as the spec instead of the one being replaced.
1492
1493 By default `patch` will fail to replace attributes that don't exist. If
1494 you pass in `create=True`, and the attribute doesn't exist, patch will
1495 create the attribute for you when the patched function is called, and
1496 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001497 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001498 default because it can be dangerous. With it switched on you can write
1499 passing tests against APIs that don't actually exist!
1500
1501 Patch can be used as a `TestCase` class decorator. It works by
1502 decorating each test method in the class. This reduces the boilerplate
1503 code when your test methods share a common patchings set. `patch` finds
1504 tests by looking for method names that start with `patch.TEST_PREFIX`.
1505 By default this is `test`, which matches the way `unittest` finds tests.
1506 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1507
1508 Patch can be used as a context manager, with the with statement. Here the
1509 patching applies to the indented block after the with statement. If you
1510 use "as" then the patched object will be bound to the name after the
1511 "as"; very useful if `patch` is creating a mock object for you.
1512
1513 `patch` takes arbitrary keyword arguments. These will be passed to
1514 the `Mock` (or `new_callable`) on construction.
1515
1516 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1517 available for alternate use-cases.
1518 """
1519 getter, attribute = _get_target(target)
1520 return _patch(
1521 getter, attribute, new, spec, create,
1522 spec_set, autospec, new_callable, kwargs
1523 )
1524
1525
1526class _patch_dict(object):
1527 """
1528 Patch a dictionary, or dictionary like object, and restore the dictionary
1529 to its original state after the test.
1530
1531 `in_dict` can be a dictionary or a mapping like container. If it is a
1532 mapping then it must at least support getting, setting and deleting items
1533 plus iterating over keys.
1534
1535 `in_dict` can also be a string specifying the name of the dictionary, which
1536 will then be fetched by importing it.
1537
1538 `values` can be a dictionary of values to set in the dictionary. `values`
1539 can also be an iterable of `(key, value)` pairs.
1540
1541 If `clear` is True then the dictionary will be cleared before the new
1542 values are set.
1543
1544 `patch.dict` can also be called with arbitrary keyword arguments to set
1545 values in the dictionary::
1546
1547 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1548 ...
1549
1550 `patch.dict` can be used as a context manager, decorator or class
1551 decorator. When used as a class decorator `patch.dict` honours
1552 `patch.TEST_PREFIX` for choosing which methods to wrap.
1553 """
1554
1555 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1556 if isinstance(in_dict, str):
1557 in_dict = _importer(in_dict)
1558 self.in_dict = in_dict
1559 # support any argument supported by dict(...) constructor
1560 self.values = dict(values)
1561 self.values.update(kwargs)
1562 self.clear = clear
1563 self._original = None
1564
1565
1566 def __call__(self, f):
1567 if isinstance(f, type):
1568 return self.decorate_class(f)
1569 @wraps(f)
1570 def _inner(*args, **kw):
1571 self._patch_dict()
1572 try:
1573 return f(*args, **kw)
1574 finally:
1575 self._unpatch_dict()
1576
1577 return _inner
1578
1579
1580 def decorate_class(self, klass):
1581 for attr in dir(klass):
1582 attr_value = getattr(klass, attr)
1583 if (attr.startswith(patch.TEST_PREFIX) and
1584 hasattr(attr_value, "__call__")):
1585 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1586 decorated = decorator(attr_value)
1587 setattr(klass, attr, decorated)
1588 return klass
1589
1590
1591 def __enter__(self):
1592 """Patch the dict."""
1593 self._patch_dict()
1594
1595
1596 def _patch_dict(self):
1597 values = self.values
1598 in_dict = self.in_dict
1599 clear = self.clear
1600
1601 try:
1602 original = in_dict.copy()
1603 except AttributeError:
1604 # dict like object with no copy method
1605 # must support iteration over keys
1606 original = {}
1607 for key in in_dict:
1608 original[key] = in_dict[key]
1609 self._original = original
1610
1611 if clear:
1612 _clear_dict(in_dict)
1613
1614 try:
1615 in_dict.update(values)
1616 except AttributeError:
1617 # dict like object with no update method
1618 for key in values:
1619 in_dict[key] = values[key]
1620
1621
1622 def _unpatch_dict(self):
1623 in_dict = self.in_dict
1624 original = self._original
1625
1626 _clear_dict(in_dict)
1627
1628 try:
1629 in_dict.update(original)
1630 except AttributeError:
1631 for key in original:
1632 in_dict[key] = original[key]
1633
1634
1635 def __exit__(self, *args):
1636 """Unpatch the dict."""
1637 self._unpatch_dict()
1638 return False
1639
1640 start = __enter__
1641 stop = __exit__
1642
1643
1644def _clear_dict(in_dict):
1645 try:
1646 in_dict.clear()
1647 except AttributeError:
1648 keys = list(in_dict)
1649 for key in keys:
1650 del in_dict[key]
1651
1652
Michael Foordf7c41582012-06-10 20:36:32 +01001653def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001654 """Stop all active patches. LIFO to unroll nested patches."""
1655 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001656 patch.stop()
1657
1658
Michael Foord345266a2012-03-14 12:24:34 -07001659patch.object = _patch_object
1660patch.dict = _patch_dict
1661patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001662patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001663patch.TEST_PREFIX = 'test'
1664
1665magic_methods = (
1666 "lt le gt ge eq ne "
1667 "getitem setitem delitem "
1668 "len contains iter "
1669 "hash str sizeof "
1670 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001671 # we added divmod and rdivmod here instead of numerics
1672 # because there is no idivmod
1673 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001674 "complex int float index "
1675 "trunc floor ceil "
1676 "bool next "
1677)
1678
Michael Foordd2623d72014-04-14 11:23:48 -04001679numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001680 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001681)
Michael Foord345266a2012-03-14 12:24:34 -07001682inplace = ' '.join('i%s' % n for n in numerics.split())
1683right = ' '.join('r%s' % n for n in numerics.split())
1684
1685# not including __prepare__, __instancecheck__, __subclasscheck__
1686# (as they are metaclass methods)
1687# __del__ is not supported at all as it causes problems if it exists
1688
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001689_non_defaults = {
1690 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1691 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1692 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1693 '__repr__', '__dir__', '__subclasses__', '__format__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001694}
Michael Foord345266a2012-03-14 12:24:34 -07001695
1696
1697def _get_method(name, func):
1698 "Turns a callable object (like a mock) into a real function"
1699 def method(self, *args, **kw):
1700 return func(self, *args, **kw)
1701 method.__name__ = name
1702 return method
1703
1704
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001705_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001706 '__%s__' % method for method in
1707 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001708}
Michael Foord345266a2012-03-14 12:24:34 -07001709
1710_all_magics = _magics | _non_defaults
1711
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001712_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001713 '__getattr__', '__setattr__',
1714 '__init__', '__new__', '__prepare__'
1715 '__instancecheck__', '__subclasscheck__',
1716 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001717}
Michael Foord345266a2012-03-14 12:24:34 -07001718
1719_calculate_return_value = {
1720 '__hash__': lambda self: object.__hash__(self),
1721 '__str__': lambda self: object.__str__(self),
1722 '__sizeof__': lambda self: object.__sizeof__(self),
1723}
1724
1725_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001726 '__lt__': NotImplemented,
1727 '__gt__': NotImplemented,
1728 '__le__': NotImplemented,
1729 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001730 '__int__': 1,
1731 '__contains__': False,
1732 '__len__': 0,
1733 '__exit__': False,
1734 '__complex__': 1j,
1735 '__float__': 1.0,
1736 '__bool__': True,
1737 '__index__': 1,
1738}
1739
1740
1741def _get_eq(self):
1742 def __eq__(other):
1743 ret_val = self.__eq__._mock_return_value
1744 if ret_val is not DEFAULT:
1745 return ret_val
1746 return self is other
1747 return __eq__
1748
1749def _get_ne(self):
1750 def __ne__(other):
1751 if self.__ne__._mock_return_value is not DEFAULT:
1752 return DEFAULT
1753 return self is not other
1754 return __ne__
1755
1756def _get_iter(self):
1757 def __iter__():
1758 ret_val = self.__iter__._mock_return_value
1759 if ret_val is DEFAULT:
1760 return iter([])
1761 # if ret_val was already an iterator, then calling iter on it should
1762 # return the iterator unchanged
1763 return iter(ret_val)
1764 return __iter__
1765
1766_side_effect_methods = {
1767 '__eq__': _get_eq,
1768 '__ne__': _get_ne,
1769 '__iter__': _get_iter,
1770}
1771
1772
1773
1774def _set_return_value(mock, method, name):
1775 fixed = _return_values.get(name, DEFAULT)
1776 if fixed is not DEFAULT:
1777 method.return_value = fixed
1778 return
1779
1780 return_calulator = _calculate_return_value.get(name)
1781 if return_calulator is not None:
1782 try:
1783 return_value = return_calulator(mock)
1784 except AttributeError:
1785 # XXXX why do we return AttributeError here?
1786 # set it as a side_effect instead?
1787 return_value = AttributeError(name)
1788 method.return_value = return_value
1789 return
1790
1791 side_effector = _side_effect_methods.get(name)
1792 if side_effector is not None:
1793 method.side_effect = side_effector(mock)
1794
1795
1796
1797class MagicMixin(object):
1798 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001799 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001800 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001801 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001802
1803
1804 def _mock_set_magics(self):
1805 these_magics = _magics
1806
Łukasz Langaa468db92015-04-13 23:12:42 -07001807 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001808 these_magics = _magics.intersection(self._mock_methods)
1809
1810 remove_magics = set()
1811 remove_magics = _magics - these_magics
1812
1813 for entry in remove_magics:
1814 if entry in type(self).__dict__:
1815 # remove unneeded magic methods
1816 delattr(self, entry)
1817
1818 # don't overwrite existing attributes if called a second time
1819 these_magics = these_magics - set(type(self).__dict__)
1820
1821 _type = type(self)
1822 for entry in these_magics:
1823 setattr(_type, entry, MagicProxy(entry, self))
1824
1825
1826
1827class NonCallableMagicMock(MagicMixin, NonCallableMock):
1828 """A version of `MagicMock` that isn't callable."""
1829 def mock_add_spec(self, spec, spec_set=False):
1830 """Add a spec to a mock. `spec` can either be an object or a
1831 list of strings. Only attributes on the `spec` can be fetched as
1832 attributes from the mock.
1833
1834 If `spec_set` is True then only attributes on the spec can be set."""
1835 self._mock_add_spec(spec, spec_set)
1836 self._mock_set_magics()
1837
1838
1839
1840class MagicMock(MagicMixin, Mock):
1841 """
1842 MagicMock is a subclass of Mock with default implementations
1843 of most of the magic methods. You can use MagicMock without having to
1844 configure the magic methods yourself.
1845
1846 If you use the `spec` or `spec_set` arguments then *only* magic
1847 methods that exist in the spec will be created.
1848
1849 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1850 """
1851 def mock_add_spec(self, spec, spec_set=False):
1852 """Add a spec to a mock. `spec` can either be an object or a
1853 list of strings. Only attributes on the `spec` can be fetched as
1854 attributes from the mock.
1855
1856 If `spec_set` is True then only attributes on the spec can be set."""
1857 self._mock_add_spec(spec, spec_set)
1858 self._mock_set_magics()
1859
1860
1861
1862class MagicProxy(object):
1863 def __init__(self, name, parent):
1864 self.name = name
1865 self.parent = parent
1866
1867 def __call__(self, *args, **kwargs):
1868 m = self.create_mock()
1869 return m(*args, **kwargs)
1870
1871 def create_mock(self):
1872 entry = self.name
1873 parent = self.parent
1874 m = parent._get_child_mock(name=entry, _new_name=entry,
1875 _new_parent=parent)
1876 setattr(parent, entry, m)
1877 _set_return_value(parent, m, entry)
1878 return m
1879
1880 def __get__(self, obj, _type=None):
1881 return self.create_mock()
1882
1883
1884
1885class _ANY(object):
1886 "A helper object that compares equal to everything."
1887
1888 def __eq__(self, other):
1889 return True
1890
1891 def __ne__(self, other):
1892 return False
1893
1894 def __repr__(self):
1895 return '<ANY>'
1896
1897ANY = _ANY()
1898
1899
1900
1901def _format_call_signature(name, args, kwargs):
1902 message = '%s(%%s)' % name
1903 formatted_args = ''
1904 args_string = ', '.join([repr(arg) for arg in args])
1905 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301906 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001907 ])
1908 if args_string:
1909 formatted_args = args_string
1910 if kwargs_string:
1911 if formatted_args:
1912 formatted_args += ', '
1913 formatted_args += kwargs_string
1914
1915 return message % formatted_args
1916
1917
1918
1919class _Call(tuple):
1920 """
1921 A tuple for holding the results of a call to a mock, either in the form
1922 `(args, kwargs)` or `(name, args, kwargs)`.
1923
1924 If args or kwargs are empty then a call tuple will compare equal to
1925 a tuple without those values. This makes comparisons less verbose::
1926
1927 _Call(('name', (), {})) == ('name',)
1928 _Call(('name', (1,), {})) == ('name', (1,))
1929 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1930
1931 The `_Call` object provides a useful shortcut for comparing with call::
1932
1933 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1934 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1935
1936 If the _Call has no name then it will match any name.
1937 """
1938 def __new__(cls, value=(), name=None, parent=None, two=False,
1939 from_kall=True):
1940 name = ''
1941 args = ()
1942 kwargs = {}
1943 _len = len(value)
1944 if _len == 3:
1945 name, args, kwargs = value
1946 elif _len == 2:
1947 first, second = value
1948 if isinstance(first, str):
1949 name = first
1950 if isinstance(second, tuple):
1951 args = second
1952 else:
1953 kwargs = second
1954 else:
1955 args, kwargs = first, second
1956 elif _len == 1:
1957 value, = value
1958 if isinstance(value, str):
1959 name = value
1960 elif isinstance(value, tuple):
1961 args = value
1962 else:
1963 kwargs = value
1964
1965 if two:
1966 return tuple.__new__(cls, (args, kwargs))
1967
1968 return tuple.__new__(cls, (name, args, kwargs))
1969
1970
1971 def __init__(self, value=(), name=None, parent=None, two=False,
1972 from_kall=True):
1973 self.name = name
1974 self.parent = parent
1975 self.from_kall = from_kall
1976
1977
1978 def __eq__(self, other):
1979 if other is ANY:
1980 return True
1981 try:
1982 len_other = len(other)
1983 except TypeError:
1984 return False
1985
1986 self_name = ''
1987 if len(self) == 2:
1988 self_args, self_kwargs = self
1989 else:
1990 self_name, self_args, self_kwargs = self
1991
1992 other_name = ''
1993 if len_other == 0:
1994 other_args, other_kwargs = (), {}
1995 elif len_other == 3:
1996 other_name, other_args, other_kwargs = other
1997 elif len_other == 1:
1998 value, = other
1999 if isinstance(value, tuple):
2000 other_args = value
2001 other_kwargs = {}
2002 elif isinstance(value, str):
2003 other_name = value
2004 other_args, other_kwargs = (), {}
2005 else:
2006 other_args = ()
2007 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002008 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002009 # could be (name, args) or (name, kwargs) or (args, kwargs)
2010 first, second = other
2011 if isinstance(first, str):
2012 other_name = first
2013 if isinstance(second, tuple):
2014 other_args, other_kwargs = second, {}
2015 else:
2016 other_args, other_kwargs = (), second
2017 else:
2018 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002019 else:
2020 return False
Michael Foord345266a2012-03-14 12:24:34 -07002021
2022 if self_name and other_name != self_name:
2023 return False
2024
2025 # this order is important for ANY to work!
2026 return (other_args, other_kwargs) == (self_args, self_kwargs)
2027
2028
Michael Foord345266a2012-03-14 12:24:34 -07002029 def __call__(self, *args, **kwargs):
2030 if self.name is None:
2031 return _Call(('', args, kwargs), name='()')
2032
2033 name = self.name + '()'
2034 return _Call((self.name, args, kwargs), name=name, parent=self)
2035
2036
2037 def __getattr__(self, attr):
2038 if self.name is None:
2039 return _Call(name=attr, from_kall=False)
2040 name = '%s.%s' % (self.name, attr)
2041 return _Call(name=name, parent=self, from_kall=False)
2042
2043
Kushal Dasa37b9582014-09-16 18:33:37 +05302044 def count(self, *args, **kwargs):
2045 return self.__getattr__('count')(*args, **kwargs)
2046
2047 def index(self, *args, **kwargs):
2048 return self.__getattr__('index')(*args, **kwargs)
2049
Michael Foord345266a2012-03-14 12:24:34 -07002050 def __repr__(self):
2051 if not self.from_kall:
2052 name = self.name or 'call'
2053 if name.startswith('()'):
2054 name = 'call%s' % name
2055 return name
2056
2057 if len(self) == 2:
2058 name = 'call'
2059 args, kwargs = self
2060 else:
2061 name, args, kwargs = self
2062 if not name:
2063 name = 'call'
2064 elif not name.startswith('()'):
2065 name = 'call.%s' % name
2066 else:
2067 name = 'call%s' % name
2068 return _format_call_signature(name, args, kwargs)
2069
2070
2071 def call_list(self):
2072 """For a call object that represents multiple calls, `call_list`
2073 returns a list of all the intermediate calls as well as the
2074 final call."""
2075 vals = []
2076 thing = self
2077 while thing is not None:
2078 if thing.from_kall:
2079 vals.append(thing)
2080 thing = thing.parent
2081 return _CallList(reversed(vals))
2082
2083
2084call = _Call(from_kall=False)
2085
2086
2087
2088def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2089 _name=None, **kwargs):
2090 """Create a mock object using another object as a spec. Attributes on the
2091 mock will use the corresponding attribute on the `spec` object as their
2092 spec.
2093
2094 Functions or methods being mocked will have their arguments checked
2095 to check that they are called with the correct signature.
2096
2097 If `spec_set` is True then attempting to set attributes that don't exist
2098 on the spec object will raise an `AttributeError`.
2099
2100 If a class is used as a spec then the return value of the mock (the
2101 instance of the class) will have the same spec. You can use a class as the
2102 spec for an instance object by passing `instance=True`. The returned mock
2103 will only be callable if instances of the mock are callable.
2104
2105 `create_autospec` also takes arbitrary keyword arguments that are passed to
2106 the constructor of the created mock."""
2107 if _is_list(spec):
2108 # can't pass a list instance to the mock constructor as it will be
2109 # interpreted as a list of strings
2110 spec = type(spec)
2111
2112 is_type = isinstance(spec, type)
2113
2114 _kwargs = {'spec': spec}
2115 if spec_set:
2116 _kwargs = {'spec_set': spec}
2117 elif spec is None:
2118 # None we mock with a normal mock without a spec
2119 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002120 if _kwargs and instance:
2121 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002122
2123 _kwargs.update(kwargs)
2124
2125 Klass = MagicMock
2126 if type(spec) in DescriptorTypes:
2127 # descriptors don't have a spec
2128 # because we don't know what type they return
2129 _kwargs = {}
2130 elif not _callable(spec):
2131 Klass = NonCallableMagicMock
2132 elif is_type and instance and not _instance_callable(spec):
2133 Klass = NonCallableMagicMock
2134
Kushal Das484f8a82014-04-16 01:05:50 +05302135 _name = _kwargs.pop('name', _name)
2136
Michael Foord345266a2012-03-14 12:24:34 -07002137 _new_name = _name
2138 if _parent is None:
2139 # for a top level object no _new_name should be set
2140 _new_name = ''
2141
2142 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2143 name=_name, **_kwargs)
2144
2145 if isinstance(spec, FunctionTypes):
2146 # should only happen at the top level because we don't
2147 # recurse for functions
2148 mock = _set_signature(mock, spec)
2149 else:
2150 _check_signature(spec, mock, is_type, instance)
2151
2152 if _parent is not None and not instance:
2153 _parent._mock_children[_name] = mock
2154
2155 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002156 mock.return_value = create_autospec(spec, spec_set, instance=True,
2157 _name='()', _parent=mock)
2158
2159 for entry in dir(spec):
2160 if _is_magic(entry):
2161 # MagicMock already does the useful magic methods for us
2162 continue
2163
Michael Foord345266a2012-03-14 12:24:34 -07002164 # XXXX do we need a better way of getting attributes without
2165 # triggering code execution (?) Probably not - we need the actual
2166 # object to mock it so we would rather trigger a property than mock
2167 # the property descriptor. Likewise we want to mock out dynamically
2168 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002169 # XXXX what about attributes that raise exceptions other than
2170 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002171 # we could be resilient against it, or catch and propagate the
2172 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002173 try:
2174 original = getattr(spec, entry)
2175 except AttributeError:
2176 continue
Michael Foord345266a2012-03-14 12:24:34 -07002177
2178 kwargs = {'spec': original}
2179 if spec_set:
2180 kwargs = {'spec_set': original}
2181
2182 if not isinstance(original, FunctionTypes):
2183 new = _SpecState(original, spec_set, mock, entry, instance)
2184 mock._mock_children[entry] = new
2185 else:
2186 parent = mock
2187 if isinstance(spec, FunctionTypes):
2188 parent = mock.mock
2189
Michael Foord345266a2012-03-14 12:24:34 -07002190 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002191 kwargs['_eat_self'] = skipfirst
2192 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2193 _new_parent=parent,
2194 **kwargs)
2195 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002196 _check_signature(original, new, skipfirst=skipfirst)
2197
2198 # so functions created with _set_signature become instance attributes,
2199 # *plus* their underlying mock exists in _mock_children of the parent
2200 # mock. Adding to _mock_children may be unnecessary where we are also
2201 # setting as an instance attribute?
2202 if isinstance(new, FunctionTypes):
2203 setattr(mock, entry, new)
2204
2205 return mock
2206
2207
2208def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002209 """
2210 Return whether we should skip the first argument on spec's `entry`
2211 attribute.
2212 """
Michael Foord345266a2012-03-14 12:24:34 -07002213 if not isinstance(spec, type):
2214 if entry in getattr(spec, '__dict__', {}):
2215 # instance attribute - shouldn't skip
2216 return False
Michael Foord345266a2012-03-14 12:24:34 -07002217 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002218
2219 for klass in spec.__mro__:
2220 result = klass.__dict__.get(entry, DEFAULT)
2221 if result is DEFAULT:
2222 continue
2223 if isinstance(result, (staticmethod, classmethod)):
2224 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002225 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2226 # Normal method => skip if looked up on type
2227 # (if looked up on instance, self is already skipped)
2228 return is_type
2229 else:
2230 return False
Michael Foord345266a2012-03-14 12:24:34 -07002231
2232 # shouldn't get here unless function is a dynamically provided attribute
2233 # XXXX untested behaviour
2234 return is_type
2235
2236
2237def _get_class(obj):
2238 try:
2239 return obj.__class__
2240 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002241 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002242 return type(obj)
2243
2244
2245class _SpecState(object):
2246
2247 def __init__(self, spec, spec_set=False, parent=None,
2248 name=None, ids=None, instance=False):
2249 self.spec = spec
2250 self.ids = ids
2251 self.spec_set = spec_set
2252 self.parent = parent
2253 self.instance = instance
2254 self.name = name
2255
2256
2257FunctionTypes = (
2258 # python function
2259 type(create_autospec),
2260 # instance method
2261 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002262)
2263
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002264MethodWrapperTypes = (
2265 type(ANY.__eq__.__get__),
2266)
2267
Michael Foord345266a2012-03-14 12:24:34 -07002268
Michael Foorda74561a2012-03-25 19:03:13 +01002269file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002270
Michael Foord04cbe0c2013-03-19 17:22:51 -07002271def _iterate_read_data(read_data):
2272 # Helper for mock_open:
2273 # Retrieve lines from read_data via a generator so that separate calls to
2274 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002275 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2276 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002277
Berker Peksag86b34da2015-08-06 13:15:51 +03002278 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002279 # If the last line ended in a newline, the list comprehension will have an
2280 # extra entry that's just a newline. Remove this.
2281 data_as_list = data_as_list[:-1]
2282 else:
2283 # If there wasn't an extra newline by itself, then the file being
2284 # emulated doesn't have a newline to end the last line remove the
2285 # newline that our naive format() added
2286 data_as_list[-1] = data_as_list[-1][:-1]
2287
2288 for line in data_as_list:
2289 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002290
Robert Collins5329aaa2015-07-17 20:08:45 +12002291
Michael Foord0dccf652012-03-25 19:11:50 +01002292def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002293 """
2294 A helper function to create a mock to replace the use of `open`. It works
2295 for `open` called directly or used as a context manager.
2296
2297 The `mock` argument is the mock object to configure. If `None` (the
2298 default) then a `MagicMock` will be created for you, with the API limited
2299 to methods or attributes available on standard file handles.
2300
Michael Foord04cbe0c2013-03-19 17:22:51 -07002301 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2302 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002303 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002304 def _readlines_side_effect(*args, **kwargs):
2305 if handle.readlines.return_value is not None:
2306 return handle.readlines.return_value
2307 return list(_state[0])
2308
2309 def _read_side_effect(*args, **kwargs):
2310 if handle.read.return_value is not None:
2311 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002312 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002313
2314 def _readline_side_effect():
2315 if handle.readline.return_value is not None:
2316 while True:
2317 yield handle.readline.return_value
2318 for line in _state[0]:
2319 yield line
2320
2321
Michael Foorda74561a2012-03-25 19:03:13 +01002322 global file_spec
2323 if file_spec is None:
2324 import _io
2325 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2326
Michael Foord345266a2012-03-14 12:24:34 -07002327 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002328 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002329
Robert Collinsca647ef2015-07-24 03:48:20 +12002330 handle = MagicMock(spec=file_spec)
2331 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002332
Robert Collinsca647ef2015-07-24 03:48:20 +12002333 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002334
Robert Collinsca647ef2015-07-24 03:48:20 +12002335 handle.write.return_value = None
2336 handle.read.return_value = None
2337 handle.readline.return_value = None
2338 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002339
Robert Collinsca647ef2015-07-24 03:48:20 +12002340 handle.read.side_effect = _read_side_effect
2341 _state[1] = _readline_side_effect()
2342 handle.readline.side_effect = _state[1]
2343 handle.readlines.side_effect = _readlines_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002344
Robert Collinsca647ef2015-07-24 03:48:20 +12002345 def reset_data(*args, **kwargs):
2346 _state[0] = _iterate_read_data(read_data)
2347 if handle.readline.side_effect == _state[1]:
2348 # Only reset the side effect if the user hasn't overridden it.
2349 _state[1] = _readline_side_effect()
2350 handle.readline.side_effect = _state[1]
2351 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002352
Robert Collinsca647ef2015-07-24 03:48:20 +12002353 mock.side_effect = reset_data
2354 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002355 return mock
2356
2357
2358class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002359 """
2360 A mock intended to be used as a property, or other descriptor, on a class.
2361 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2362 a return value when it is fetched.
2363
2364 Fetching a `PropertyMock` instance from an object calls the mock, with
2365 no args. Setting it calls the mock with the value being set.
2366 """
Michael Foordc2870622012-04-13 16:57:22 +01002367 def _get_child_mock(self, **kwargs):
2368 return MagicMock(**kwargs)
2369
Michael Foord345266a2012-03-14 12:24:34 -07002370 def __get__(self, obj, obj_type):
2371 return self()
2372 def __set__(self, obj, val):
2373 self(val)