blob: f1349198880c63c09769f13cb0e1a9be639a2682 [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001# mock.py
2# Test tools for mocking and patching.
Michael Foordc17adf42012-03-14 13:30:29 -07003# Maintained by Michael Foord
4# Backport for other versions of Python available from
5# http://pypi.python.org/pypi/mock
Michael Foord345266a2012-03-14 12:24:34 -07006
7__all__ = (
8 'Mock',
9 'MagicMock',
10 'patch',
11 'sentinel',
12 'DEFAULT',
13 'ANY',
14 'call',
15 'create_autospec',
16 'FILTER_DIR',
17 'NonCallableMock',
18 'NonCallableMagicMock',
19 'mock_open',
20 'PropertyMock',
21)
22
23
24__version__ = '1.0'
25
26
27import inspect
28import pprint
29import sys
Michael Foordfddcfa22014-04-14 16:25:20 -040030import builtins
31from types import ModuleType
Antoine Pitrou5c64df72013-02-03 00:23:58 +010032from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070033
34
Michael Foordfddcfa22014-04-14 16:25:20 -040035_builtins = {name for name in dir(builtins) if not name.startswith('_')}
36
Michael Foord345266a2012-03-14 12:24:34 -070037BaseExceptions = (BaseException,)
38if 'java' in sys.platform:
39 # jython
40 import java
41 BaseExceptions = (BaseException, java.lang.Throwable)
42
43
44FILTER_DIR = True
45
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100046# Workaround for issue #12370
47# Without this, the __class__ properties wouldn't be set correctly
48_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070049
50def _is_instance_mock(obj):
51 # can't use isinstance on Mock objects because they override __class__
52 # The base class for all mocks is NonCallableMock
53 return issubclass(type(obj), NonCallableMock)
54
55
56def _is_exception(obj):
57 return (
58 isinstance(obj, BaseExceptions) or
59 isinstance(obj, type) and issubclass(obj, BaseExceptions)
60 )
61
62
Antoine Pitrou5c64df72013-02-03 00:23:58 +010063def _get_signature_object(func, as_instance, eat_self):
64 """
65 Given an arbitrary, possibly callable object, try to create a suitable
66 signature object.
67 Return a (reduced func, signature) tuple, or None.
68 """
69 if isinstance(func, type) and not as_instance:
70 # If it's a type and should be modelled as a type, use __init__.
Michael Foord345266a2012-03-14 12:24:34 -070071 try:
72 func = func.__init__
73 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010074 return None
75 # Skip the `self` argument in __init__
76 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070077 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010078 # If we really want to model an instance of the passed type,
79 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070080 try:
81 func = func.__call__
82 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010083 return None
84 if eat_self:
85 sig_func = partial(func, None)
86 else:
87 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -070088 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010089 return func, inspect.signature(sig_func)
90 except ValueError:
91 # Certain callable types are not supported by inspect.signature()
92 return None
Michael Foord345266a2012-03-14 12:24:34 -070093
94
95def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010096 sig = _get_signature_object(func, instance, skipfirst)
97 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -070098 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +010099 func, sig = sig
100 def checksig(_mock_self, *args, **kwargs):
101 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700102 _copy_func_details(func, checksig)
103 type(mock)._mock_check_sig = checksig
104
105
106def _copy_func_details(func, funcopy):
107 funcopy.__name__ = func.__name__
108 funcopy.__doc__ = func.__doc__
Larry Hastings5c661892014-01-24 06:17:25 -0800109 try:
110 funcopy.__text_signature__ = func.__text_signature__
111 except AttributeError:
112 pass
Michael Foord345266a2012-03-14 12:24:34 -0700113 # we explicitly don't copy func.__dict__ into this copy as it would
114 # expose original attributes that should be mocked
Larry Hastings5c661892014-01-24 06:17:25 -0800115 try:
116 funcopy.__module__ = func.__module__
117 except AttributeError:
118 pass
119 try:
120 funcopy.__defaults__ = func.__defaults__
121 except AttributeError:
122 pass
123 try:
124 funcopy.__kwdefaults__ = func.__kwdefaults__
125 except AttributeError:
126 pass
Michael Foord345266a2012-03-14 12:24:34 -0700127
128
129def _callable(obj):
130 if isinstance(obj, type):
131 return True
132 if getattr(obj, '__call__', None) is not None:
133 return True
134 return False
135
136
137def _is_list(obj):
138 # checks for list or tuples
139 # XXXX badly named!
140 return type(obj) in (list, tuple)
141
142
143def _instance_callable(obj):
144 """Given an object, return True if the object is callable.
145 For classes, return True if instances would be callable."""
146 if not isinstance(obj, type):
147 # already an instance
148 return getattr(obj, '__call__', None) is not None
149
Michael Foorda74b3aa2012-03-14 14:40:22 -0700150 # *could* be broken by a class overriding __mro__ or __dict__ via
151 # a metaclass
152 for base in (obj,) + obj.__mro__:
153 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700154 return True
155 return False
156
157
158def _set_signature(mock, original, instance=False):
159 # creates a function with signature (*args, **kwargs) that delegates to a
160 # mock. It still does signature checking by calling a lambda with the same
161 # signature as the original.
162 if not _callable(original):
163 return
164
165 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100166 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700167 if result is None:
Michael Foord345266a2012-03-14 12:24:34 -0700168 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100169 func, sig = result
170 def checksig(*args, **kwargs):
171 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700172 _copy_func_details(func, checksig)
173
174 name = original.__name__
175 if not name.isidentifier():
176 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100177 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700178 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100179 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700180 return mock(*args, **kwargs)""" % name
181 exec (src, context)
182 funcopy = context[name]
183 _setup_func(funcopy, mock)
184 return funcopy
185
186
187def _setup_func(funcopy, mock):
188 funcopy.mock = mock
189
190 # can't use isinstance with mocks
191 if not _is_instance_mock(mock):
192 return
193
194 def assert_called_with(*args, **kwargs):
195 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700196 def assert_called(*args, **kwargs):
197 return mock.assert_called(*args, **kwargs)
198 def assert_not_called(*args, **kwargs):
199 return mock.assert_not_called(*args, **kwargs)
200 def assert_called_once(*args, **kwargs):
201 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700202 def assert_called_once_with(*args, **kwargs):
203 return mock.assert_called_once_with(*args, **kwargs)
204 def assert_has_calls(*args, **kwargs):
205 return mock.assert_has_calls(*args, **kwargs)
206 def assert_any_call(*args, **kwargs):
207 return mock.assert_any_call(*args, **kwargs)
208 def reset_mock():
209 funcopy.method_calls = _CallList()
210 funcopy.mock_calls = _CallList()
211 mock.reset_mock()
212 ret = funcopy.return_value
213 if _is_instance_mock(ret) and not ret is mock:
214 ret.reset_mock()
215
216 funcopy.called = False
217 funcopy.call_count = 0
218 funcopy.call_args = None
219 funcopy.call_args_list = _CallList()
220 funcopy.method_calls = _CallList()
221 funcopy.mock_calls = _CallList()
222
223 funcopy.return_value = mock.return_value
224 funcopy.side_effect = mock.side_effect
225 funcopy._mock_children = mock._mock_children
226
227 funcopy.assert_called_with = assert_called_with
228 funcopy.assert_called_once_with = assert_called_once_with
229 funcopy.assert_has_calls = assert_has_calls
230 funcopy.assert_any_call = assert_any_call
231 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700232 funcopy.assert_called = assert_called
233 funcopy.assert_not_called = assert_not_called
234 funcopy.assert_called_once = assert_called_once
Michael Foord345266a2012-03-14 12:24:34 -0700235
236 mock._mock_delegate = funcopy
237
238
239def _is_magic(name):
240 return '__%s__' % name[2:-2] == name
241
242
243class _SentinelObject(object):
244 "A unique, named, sentinel object."
245 def __init__(self, name):
246 self.name = name
247
248 def __repr__(self):
249 return 'sentinel.%s' % self.name
250
251
252class _Sentinel(object):
253 """Access attributes to return a named object, usable as a sentinel."""
254 def __init__(self):
255 self._sentinels = {}
256
257 def __getattr__(self, name):
258 if name == '__bases__':
259 # Without this help(unittest.mock) raises an exception
260 raise AttributeError
261 return self._sentinels.setdefault(name, _SentinelObject(name))
262
263
264sentinel = _Sentinel()
265
266DEFAULT = sentinel.DEFAULT
267_missing = sentinel.MISSING
268_deleted = sentinel.DELETED
269
270
Michael Foord345266a2012-03-14 12:24:34 -0700271def _copy(value):
272 if type(value) in (dict, list, tuple, set):
273 return type(value)(value)
274 return value
275
276
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200277_allowed_names = {
278 'return_value', '_mock_return_value', 'side_effect',
279 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
280 '_mock_name', '_mock_new_name'
281}
Michael Foord345266a2012-03-14 12:24:34 -0700282
283
284def _delegating_property(name):
285 _allowed_names.add(name)
286 _the_name = '_mock_' + name
287 def _get(self, name=name, _the_name=_the_name):
288 sig = self._mock_delegate
289 if sig is None:
290 return getattr(self, _the_name)
291 return getattr(sig, name)
292 def _set(self, value, name=name, _the_name=_the_name):
293 sig = self._mock_delegate
294 if sig is None:
295 self.__dict__[_the_name] = value
296 else:
297 setattr(sig, name, value)
298
299 return property(_get, _set)
300
301
302
303class _CallList(list):
304
305 def __contains__(self, value):
306 if not isinstance(value, list):
307 return list.__contains__(self, value)
308 len_value = len(value)
309 len_self = len(self)
310 if len_value > len_self:
311 return False
312
313 for i in range(0, len_self - len_value + 1):
314 sub_list = self[i:i+len_value]
315 if sub_list == value:
316 return True
317 return False
318
319 def __repr__(self):
320 return pprint.pformat(list(self))
321
322
323def _check_and_set_parent(parent, value, name, new_name):
324 if not _is_instance_mock(value):
325 return False
326 if ((value._mock_name or value._mock_new_name) or
327 (value._mock_parent is not None) or
328 (value._mock_new_parent is not None)):
329 return False
330
331 _parent = parent
332 while _parent is not None:
333 # setting a mock (value) as a child or return value of itself
334 # should not modify the mock
335 if _parent is value:
336 return False
337 _parent = _parent._mock_new_parent
338
339 if new_name:
340 value._mock_new_parent = parent
341 value._mock_new_name = new_name
342 if name:
343 value._mock_parent = parent
344 value._mock_name = name
345 return True
346
Michael Foord01bafdc2014-04-14 16:09:42 -0400347# Internal class to identify if we wrapped an iterator object or not.
348class _MockIter(object):
349 def __init__(self, obj):
350 self.obj = iter(obj)
351 def __iter__(self):
352 return self
353 def __next__(self):
354 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700355
356class Base(object):
357 _mock_return_value = DEFAULT
358 _mock_side_effect = None
359 def __init__(self, *args, **kwargs):
360 pass
361
362
363
364class NonCallableMock(Base):
365 """A non-callable version of `Mock`"""
366
367 def __new__(cls, *args, **kw):
368 # every instance has its own class
369 # so we can create magic methods on the
370 # class without stomping on other mocks
371 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
372 instance = object.__new__(new)
373 return instance
374
375
376 def __init__(
377 self, spec=None, wraps=None, name=None, spec_set=None,
378 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530379 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700380 ):
381 if _new_parent is None:
382 _new_parent = parent
383
384 __dict__ = self.__dict__
385 __dict__['_mock_parent'] = parent
386 __dict__['_mock_name'] = name
387 __dict__['_mock_new_name'] = _new_name
388 __dict__['_mock_new_parent'] = _new_parent
389
390 if spec_set is not None:
391 spec = spec_set
392 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100393 if _eat_self is None:
394 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700395
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100396 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700397
398 __dict__['_mock_children'] = {}
399 __dict__['_mock_wraps'] = wraps
400 __dict__['_mock_delegate'] = None
401
402 __dict__['_mock_called'] = False
403 __dict__['_mock_call_args'] = None
404 __dict__['_mock_call_count'] = 0
405 __dict__['_mock_call_args_list'] = _CallList()
406 __dict__['_mock_mock_calls'] = _CallList()
407
408 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530409 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700410
411 if kwargs:
412 self.configure_mock(**kwargs)
413
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000414 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700415 spec, wraps, name, spec_set, parent,
416 _spec_state
417 )
418
419
420 def attach_mock(self, mock, attribute):
421 """
422 Attach a mock as an attribute of this one, replacing its name and
423 parent. Calls to the attached mock will be recorded in the
424 `method_calls` and `mock_calls` attributes of this one."""
425 mock._mock_parent = None
426 mock._mock_new_parent = None
427 mock._mock_name = ''
428 mock._mock_new_name = None
429
430 setattr(self, attribute, mock)
431
432
433 def mock_add_spec(self, spec, spec_set=False):
434 """Add a spec to a mock. `spec` can either be an object or a
435 list of strings. Only attributes on the `spec` can be fetched as
436 attributes from the mock.
437
438 If `spec_set` is True then only attributes on the spec can be set."""
439 self._mock_add_spec(spec, spec_set)
440
441
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100442 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
443 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700444 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100445 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700446
447 if spec is not None and not _is_list(spec):
448 if isinstance(spec, type):
449 _spec_class = spec
450 else:
451 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100452 res = _get_signature_object(spec,
453 _spec_as_instance, _eat_self)
454 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700455
456 spec = dir(spec)
457
458 __dict__ = self.__dict__
459 __dict__['_spec_class'] = _spec_class
460 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100461 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700462 __dict__['_mock_methods'] = spec
463
464
465 def __get_return_value(self):
466 ret = self._mock_return_value
467 if self._mock_delegate is not None:
468 ret = self._mock_delegate.return_value
469
470 if ret is DEFAULT:
471 ret = self._get_child_mock(
472 _new_parent=self, _new_name='()'
473 )
474 self.return_value = ret
475 return ret
476
477
478 def __set_return_value(self, value):
479 if self._mock_delegate is not None:
480 self._mock_delegate.return_value = value
481 else:
482 self._mock_return_value = value
483 _check_and_set_parent(self, value, None, '()')
484
485 __return_value_doc = "The value to be returned when the mock is called."
486 return_value = property(__get_return_value, __set_return_value,
487 __return_value_doc)
488
489
490 @property
491 def __class__(self):
492 if self._spec_class is None:
493 return type(self)
494 return self._spec_class
495
496 called = _delegating_property('called')
497 call_count = _delegating_property('call_count')
498 call_args = _delegating_property('call_args')
499 call_args_list = _delegating_property('call_args_list')
500 mock_calls = _delegating_property('mock_calls')
501
502
503 def __get_side_effect(self):
504 delegated = self._mock_delegate
505 if delegated is None:
506 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400507 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200508 if (sf is not None and not callable(sf)
509 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400510 sf = _MockIter(sf)
511 delegated.side_effect = sf
512 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700513
514 def __set_side_effect(self, value):
515 value = _try_iter(value)
516 delegated = self._mock_delegate
517 if delegated is None:
518 self._mock_side_effect = value
519 else:
520 delegated.side_effect = value
521
522 side_effect = property(__get_side_effect, __set_side_effect)
523
524
Kushal Das9cd39a12016-06-02 10:20:16 -0700525 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700526 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200527 if visited is None:
528 visited = []
529 if id(self) in visited:
530 return
531 visited.append(id(self))
532
Michael Foord345266a2012-03-14 12:24:34 -0700533 self.called = False
534 self.call_args = None
535 self.call_count = 0
536 self.mock_calls = _CallList()
537 self.call_args_list = _CallList()
538 self.method_calls = _CallList()
539
Kushal Das9cd39a12016-06-02 10:20:16 -0700540 if return_value:
541 self._mock_return_value = DEFAULT
542 if side_effect:
543 self._mock_side_effect = None
544
Michael Foord345266a2012-03-14 12:24:34 -0700545 for child in self._mock_children.values():
Michael Foord75963642012-06-09 17:31:59 +0100546 if isinstance(child, _SpecState):
547 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200548 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700549
550 ret = self._mock_return_value
551 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200552 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700553
554
555 def configure_mock(self, **kwargs):
556 """Set attributes on the mock through keyword arguments.
557
558 Attributes plus return values and side effects can be set on child
559 mocks using standard dot notation and unpacking a dictionary in the
560 method call:
561
562 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
563 >>> mock.configure_mock(**attrs)"""
564 for arg, val in sorted(kwargs.items(),
565 # we sort on the number of dots so that
566 # attributes are set before we set attributes on
567 # attributes
568 key=lambda entry: entry[0].count('.')):
569 args = arg.split('.')
570 final = args.pop()
571 obj = self
572 for entry in args:
573 obj = getattr(obj, entry)
574 setattr(obj, final, val)
575
576
577 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530578 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700579 raise AttributeError(name)
580 elif self._mock_methods is not None:
581 if name not in self._mock_methods or name in _all_magics:
582 raise AttributeError("Mock object has no attribute %r" % name)
583 elif _is_magic(name):
584 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530585 if not self._mock_unsafe:
586 if name.startswith(('assert', 'assret')):
587 raise AttributeError(name)
Michael Foord345266a2012-03-14 12:24:34 -0700588
589 result = self._mock_children.get(name)
590 if result is _deleted:
591 raise AttributeError(name)
592 elif result is None:
593 wraps = None
594 if self._mock_wraps is not None:
595 # XXXX should we get the attribute without triggering code
596 # execution?
597 wraps = getattr(self._mock_wraps, name)
598
599 result = self._get_child_mock(
600 parent=self, name=name, wraps=wraps, _new_name=name,
601 _new_parent=self
602 )
603 self._mock_children[name] = result
604
605 elif isinstance(result, _SpecState):
606 result = create_autospec(
607 result.spec, result.spec_set, result.instance,
608 result.parent, result.name
609 )
610 self._mock_children[name] = result
611
612 return result
613
614
615 def __repr__(self):
616 _name_list = [self._mock_new_name]
617 _parent = self._mock_new_parent
618 last = self
619
620 dot = '.'
621 if _name_list == ['()']:
622 dot = ''
623 seen = set()
624 while _parent is not None:
625 last = _parent
626
627 _name_list.append(_parent._mock_new_name + dot)
628 dot = '.'
629 if _parent._mock_new_name == '()':
630 dot = ''
631
632 _parent = _parent._mock_new_parent
633
634 # use ids here so as not to call __hash__ on the mocks
635 if id(_parent) in seen:
636 break
637 seen.add(id(_parent))
638
639 _name_list = list(reversed(_name_list))
640 _first = last._mock_name or 'mock'
641 if len(_name_list) > 1:
642 if _name_list[1] not in ('()', '().'):
643 _first += '.'
644 _name_list[0] = _first
645 name = ''.join(_name_list)
646
647 name_string = ''
648 if name not in ('mock', 'mock.'):
649 name_string = ' name=%r' % name
650
651 spec_string = ''
652 if self._spec_class is not None:
653 spec_string = ' spec=%r'
654 if self._spec_set:
655 spec_string = ' spec_set=%r'
656 spec_string = spec_string % self._spec_class.__name__
657 return "<%s%s%s id='%s'>" % (
658 type(self).__name__,
659 name_string,
660 spec_string,
661 id(self)
662 )
663
664
665 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700666 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100667 if not FILTER_DIR:
668 return object.__dir__(self)
669
Michael Foord345266a2012-03-14 12:24:34 -0700670 extras = self._mock_methods or []
671 from_type = dir(type(self))
672 from_dict = list(self.__dict__)
673
Michael Foord313f85f2012-03-25 18:16:07 +0100674 from_type = [e for e in from_type if not e.startswith('_')]
675 from_dict = [e for e in from_dict if not e.startswith('_') or
676 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700677 return sorted(set(extras + from_type + from_dict +
678 list(self._mock_children)))
679
680
681 def __setattr__(self, name, value):
682 if name in _allowed_names:
683 # property setters go through here
684 return object.__setattr__(self, name, value)
685 elif (self._spec_set and self._mock_methods is not None and
686 name not in self._mock_methods and
687 name not in self.__dict__):
688 raise AttributeError("Mock object has no attribute '%s'" % name)
689 elif name in _unsupported_magics:
690 msg = 'Attempting to set unsupported magic method %r.' % name
691 raise AttributeError(msg)
692 elif name in _all_magics:
693 if self._mock_methods is not None and name not in self._mock_methods:
694 raise AttributeError("Mock object has no attribute '%s'" % name)
695
696 if not _is_instance_mock(value):
697 setattr(type(self), name, _get_method(name, value))
698 original = value
699 value = lambda *args, **kw: original(self, *args, **kw)
700 else:
701 # only set _new_name and not name so that mock_calls is tracked
702 # but not method calls
703 _check_and_set_parent(self, value, None, name)
704 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100705 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700706 elif name == '__class__':
707 self._spec_class = value
708 return
709 else:
710 if _check_and_set_parent(self, value, name, name):
711 self._mock_children[name] = value
712 return object.__setattr__(self, name, value)
713
714
715 def __delattr__(self, name):
716 if name in _all_magics and name in type(self).__dict__:
717 delattr(type(self), name)
718 if name not in self.__dict__:
719 # for magic methods that are still MagicProxy objects and
720 # not set on the instance itself
721 return
722
723 if name in self.__dict__:
724 object.__delattr__(self, name)
725
726 obj = self._mock_children.get(name, _missing)
727 if obj is _deleted:
728 raise AttributeError(name)
729 if obj is not _missing:
730 del self._mock_children[name]
731 self._mock_children[name] = _deleted
732
733
Michael Foord345266a2012-03-14 12:24:34 -0700734 def _format_mock_call_signature(self, args, kwargs):
735 name = self._mock_name or 'mock'
736 return _format_call_signature(name, args, kwargs)
737
738
739 def _format_mock_failure_message(self, args, kwargs):
740 message = 'Expected call: %s\nActual call: %s'
741 expected_string = self._format_mock_call_signature(args, kwargs)
742 call_args = self.call_args
743 if len(call_args) == 3:
744 call_args = call_args[1:]
745 actual_string = self._format_mock_call_signature(*call_args)
746 return message % (expected_string, actual_string)
747
748
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100749 def _call_matcher(self, _call):
750 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000751 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100752 comparison key suitable for matching with other calls.
753 This is a best effort method which relies on the spec's signature,
754 if available, or falls back on the arguments themselves.
755 """
756 sig = self._spec_signature
757 if sig is not None:
758 if len(_call) == 2:
759 name = ''
760 args, kwargs = _call
761 else:
762 name, args, kwargs = _call
763 try:
764 return name, sig.bind(*args, **kwargs)
765 except TypeError as e:
766 return e.with_traceback(None)
767 else:
768 return _call
769
Kushal Das68290f42014-04-17 01:54:07 +0530770 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530771 """assert that the mock was never called.
772 """
773 self = _mock_self
774 if self.call_count != 0:
775 msg = ("Expected '%s' to not have been called. Called %s times." %
776 (self._mock_name or 'mock', self.call_count))
777 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100778
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100779 def assert_called(_mock_self):
780 """assert that the mock was called at least once
781 """
782 self = _mock_self
783 if self.call_count == 0:
784 msg = ("Expected '%s' to have been called." %
785 self._mock_name or 'mock')
786 raise AssertionError(msg)
787
788 def assert_called_once(_mock_self):
789 """assert that the mock was called only once.
790 """
791 self = _mock_self
792 if not self.call_count == 1:
793 msg = ("Expected '%s' to have been called once. Called %s times." %
794 (self._mock_name or 'mock', self.call_count))
795 raise AssertionError(msg)
796
Michael Foord345266a2012-03-14 12:24:34 -0700797 def assert_called_with(_mock_self, *args, **kwargs):
798 """assert that the mock was called with the specified arguments.
799
800 Raises an AssertionError if the args and keyword args passed in are
801 different to the last call to the mock."""
802 self = _mock_self
803 if self.call_args is None:
804 expected = self._format_mock_call_signature(args, kwargs)
805 raise AssertionError('Expected call: %s\nNot called' % (expected,))
806
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100807 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700808 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100809 return msg
810 expected = self._call_matcher((args, kwargs))
811 actual = self._call_matcher(self.call_args)
812 if expected != actual:
813 cause = expected if isinstance(expected, Exception) else None
814 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700815
816
817 def assert_called_once_with(_mock_self, *args, **kwargs):
818 """assert that the mock was called exactly once and with the specified
819 arguments."""
820 self = _mock_self
821 if not self.call_count == 1:
Michael Foord28d591c2012-09-28 16:15:22 +0100822 msg = ("Expected '%s' to be called once. Called %s times." %
823 (self._mock_name or 'mock', self.call_count))
Michael Foord345266a2012-03-14 12:24:34 -0700824 raise AssertionError(msg)
825 return self.assert_called_with(*args, **kwargs)
826
827
828 def assert_has_calls(self, calls, any_order=False):
829 """assert the mock has been called with the specified calls.
830 The `mock_calls` list is checked for the calls.
831
832 If `any_order` is False (the default) then the calls must be
833 sequential. There can be extra calls before or after the
834 specified calls.
835
836 If `any_order` is True then the calls can be in any order, but
837 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100838 expected = [self._call_matcher(c) for c in calls]
839 cause = expected if isinstance(expected, Exception) else None
840 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700841 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100842 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700843 raise AssertionError(
844 'Calls not found.\nExpected: %r\n'
Senthil Kumaran121edbf2016-01-12 06:18:32 -0800845 'Actual: %r' % (_CallList(calls), self.mock_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100846 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700847 return
848
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100849 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700850
851 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100852 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700853 try:
854 all_calls.remove(kall)
855 except ValueError:
856 not_found.append(kall)
857 if not_found:
858 raise AssertionError(
859 '%r not all found in call list' % (tuple(not_found),)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100860 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700861
862
863 def assert_any_call(self, *args, **kwargs):
864 """assert the mock has been called with the specified arguments.
865
866 The assert passes if the mock has *ever* been called, unlike
867 `assert_called_with` and `assert_called_once_with` that only pass if
868 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100869 expected = self._call_matcher((args, kwargs))
870 actual = [self._call_matcher(c) for c in self.call_args_list]
871 if expected not in actual:
872 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700873 expected_string = self._format_mock_call_signature(args, kwargs)
874 raise AssertionError(
875 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100876 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700877
878
879 def _get_child_mock(self, **kw):
880 """Create the child mocks for attributes and return value.
881 By default child mocks will be the same type as the parent.
882 Subclasses of Mock may want to override this to customize the way
883 child mocks are made.
884
885 For non-callable mocks the callable variant will be used (rather than
886 any custom subclass)."""
887 _type = type(self)
888 if not issubclass(_type, CallableMixin):
889 if issubclass(_type, NonCallableMagicMock):
890 klass = MagicMock
891 elif issubclass(_type, NonCallableMock) :
892 klass = Mock
893 else:
894 klass = _type.__mro__[1]
895 return klass(**kw)
896
897
898
899def _try_iter(obj):
900 if obj is None:
901 return obj
902 if _is_exception(obj):
903 return obj
904 if _callable(obj):
905 return obj
906 try:
907 return iter(obj)
908 except TypeError:
909 # XXXX backwards compatibility
910 # but this will blow up on first call - so maybe we should fail early?
911 return obj
912
913
914
915class CallableMixin(Base):
916
917 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
918 wraps=None, name=None, spec_set=None, parent=None,
919 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
920 self.__dict__['_mock_return_value'] = return_value
921
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000922 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700923 spec, wraps, name, spec_set, parent,
924 _spec_state, _new_name, _new_parent, **kwargs
925 )
926
927 self.side_effect = side_effect
928
929
930 def _mock_check_sig(self, *args, **kwargs):
931 # stub method that can be replaced with one with a specific signature
932 pass
933
934
935 def __call__(_mock_self, *args, **kwargs):
936 # can't use self in-case a function / method we are mocking uses self
937 # in the signature
938 _mock_self._mock_check_sig(*args, **kwargs)
939 return _mock_self._mock_call(*args, **kwargs)
940
941
942 def _mock_call(_mock_self, *args, **kwargs):
943 self = _mock_self
944 self.called = True
945 self.call_count += 1
Michael Foord345266a2012-03-14 12:24:34 -0700946 _new_name = self._mock_new_name
947 _new_parent = self._mock_new_parent
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100948
949 _call = _Call((args, kwargs), two=True)
950 self.call_args = _call
951 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700952 self.mock_calls.append(_Call(('', args, kwargs)))
953
954 seen = set()
955 skip_next_dot = _new_name == '()'
956 do_method_calls = self._mock_parent is not None
957 name = self._mock_name
958 while _new_parent is not None:
959 this_mock_call = _Call((_new_name, args, kwargs))
960 if _new_parent._mock_new_name:
961 dot = '.'
962 if skip_next_dot:
963 dot = ''
964
965 skip_next_dot = False
966 if _new_parent._mock_new_name == '()':
967 skip_next_dot = True
968
969 _new_name = _new_parent._mock_new_name + dot + _new_name
970
971 if do_method_calls:
972 if _new_name == name:
973 this_method_call = this_mock_call
974 else:
975 this_method_call = _Call((name, args, kwargs))
976 _new_parent.method_calls.append(this_method_call)
977
978 do_method_calls = _new_parent._mock_parent is not None
979 if do_method_calls:
980 name = _new_parent._mock_name + '.' + name
981
982 _new_parent.mock_calls.append(this_mock_call)
983 _new_parent = _new_parent._mock_new_parent
984
985 # use ids here so as not to call __hash__ on the mocks
986 _new_parent_id = id(_new_parent)
987 if _new_parent_id in seen:
988 break
989 seen.add(_new_parent_id)
990
991 ret_val = DEFAULT
992 effect = self.side_effect
993 if effect is not None:
994 if _is_exception(effect):
995 raise effect
996
997 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +0100998 result = next(effect)
999 if _is_exception(result):
1000 raise result
Andrew Svetlov8b2cd752013-04-07 16:42:24 +03001001 if result is DEFAULT:
1002 result = self.return_value
Michael Foord2cd48732012-04-21 15:52:11 +01001003 return result
Michael Foord345266a2012-03-14 12:24:34 -07001004
1005 ret_val = effect(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001006
1007 if (self._mock_wraps is not None and
1008 self._mock_return_value is DEFAULT):
1009 return self._mock_wraps(*args, **kwargs)
1010 if ret_val is DEFAULT:
1011 ret_val = self.return_value
1012 return ret_val
1013
1014
1015
1016class Mock(CallableMixin, NonCallableMock):
1017 """
1018 Create a new `Mock` object. `Mock` takes several optional arguments
1019 that specify the behaviour of the Mock object:
1020
1021 * `spec`: This can be either a list of strings or an existing object (a
1022 class or instance) that acts as the specification for the mock object. If
1023 you pass in an object then a list of strings is formed by calling dir on
1024 the object (excluding unsupported magic attributes and methods). Accessing
1025 any attribute not in this list will raise an `AttributeError`.
1026
1027 If `spec` is an object (rather than a list of strings) then
1028 `mock.__class__` returns the class of the spec object. This allows mocks
1029 to pass `isinstance` tests.
1030
1031 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1032 or get an attribute on the mock that isn't on the object passed as
1033 `spec_set` will raise an `AttributeError`.
1034
1035 * `side_effect`: A function to be called whenever the Mock is called. See
1036 the `side_effect` attribute. Useful for raising exceptions or
1037 dynamically changing return values. The function is called with the same
1038 arguments as the mock, and unless it returns `DEFAULT`, the return
1039 value of this function is used as the return value.
1040
Michael Foord2cd48732012-04-21 15:52:11 +01001041 If `side_effect` is an iterable then each call to the mock will return
1042 the next value from the iterable. If any of the members of the iterable
1043 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001044
Michael Foord345266a2012-03-14 12:24:34 -07001045 * `return_value`: The value returned when the mock is called. By default
1046 this is a new Mock (created on first access). See the
1047 `return_value` attribute.
1048
Michael Foord0682a0c2012-04-13 20:51:20 +01001049 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1050 calling the Mock will pass the call through to the wrapped object
1051 (returning the real result). Attribute access on the mock will return a
1052 Mock object that wraps the corresponding attribute of the wrapped object
1053 (so attempting to access an attribute that doesn't exist will raise an
1054 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001055
1056 If the mock has an explicit `return_value` set then calls are not passed
1057 to the wrapped object and the `return_value` is returned instead.
1058
1059 * `name`: If the mock has a name then it will be used in the repr of the
1060 mock. This can be useful for debugging. The name is propagated to child
1061 mocks.
1062
1063 Mocks can also be called with arbitrary keyword arguments. These will be
1064 used to set attributes on the mock after it is created.
1065 """
1066
1067
1068
1069def _dot_lookup(thing, comp, import_path):
1070 try:
1071 return getattr(thing, comp)
1072 except AttributeError:
1073 __import__(import_path)
1074 return getattr(thing, comp)
1075
1076
1077def _importer(target):
1078 components = target.split('.')
1079 import_path = components.pop(0)
1080 thing = __import__(import_path)
1081
1082 for comp in components:
1083 import_path += ".%s" % comp
1084 thing = _dot_lookup(thing, comp, import_path)
1085 return thing
1086
1087
1088def _is_started(patcher):
1089 # XXXX horrible
1090 return hasattr(patcher, 'is_local')
1091
1092
1093class _patch(object):
1094
1095 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001096 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001097
1098 def __init__(
1099 self, getter, attribute, new, spec, create,
1100 spec_set, autospec, new_callable, kwargs
1101 ):
1102 if new_callable is not None:
1103 if new is not DEFAULT:
1104 raise ValueError(
1105 "Cannot use 'new' and 'new_callable' together"
1106 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001107 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001108 raise ValueError(
1109 "Cannot use 'autospec' and 'new_callable' together"
1110 )
1111
1112 self.getter = getter
1113 self.attribute = attribute
1114 self.new = new
1115 self.new_callable = new_callable
1116 self.spec = spec
1117 self.create = create
1118 self.has_local = False
1119 self.spec_set = spec_set
1120 self.autospec = autospec
1121 self.kwargs = kwargs
1122 self.additional_patchers = []
1123
1124
1125 def copy(self):
1126 patcher = _patch(
1127 self.getter, self.attribute, self.new, self.spec,
1128 self.create, self.spec_set,
1129 self.autospec, self.new_callable, self.kwargs
1130 )
1131 patcher.attribute_name = self.attribute_name
1132 patcher.additional_patchers = [
1133 p.copy() for p in self.additional_patchers
1134 ]
1135 return patcher
1136
1137
1138 def __call__(self, func):
1139 if isinstance(func, type):
1140 return self.decorate_class(func)
1141 return self.decorate_callable(func)
1142
1143
1144 def decorate_class(self, klass):
1145 for attr in dir(klass):
1146 if not attr.startswith(patch.TEST_PREFIX):
1147 continue
1148
1149 attr_value = getattr(klass, attr)
1150 if not hasattr(attr_value, "__call__"):
1151 continue
1152
1153 patcher = self.copy()
1154 setattr(klass, attr, patcher(attr_value))
1155 return klass
1156
1157
1158 def decorate_callable(self, func):
1159 if hasattr(func, 'patchings'):
1160 func.patchings.append(self)
1161 return func
1162
1163 @wraps(func)
1164 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001165 extra_args = []
1166 entered_patchers = []
1167
Michael Foord50a8c0e2012-03-25 18:57:58 +01001168 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001169 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001170 for patching in patched.patchings:
1171 arg = patching.__enter__()
1172 entered_patchers.append(patching)
1173 if patching.attribute_name is not None:
1174 keywargs.update(arg)
1175 elif patching.new is DEFAULT:
1176 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001177
Michael Foordd7c65e22012-03-14 14:56:54 -07001178 args += tuple(extra_args)
1179 return func(*args, **keywargs)
1180 except:
1181 if (patching not in entered_patchers and
1182 _is_started(patching)):
1183 # the patcher may have been started, but an exception
1184 # raised whilst entering one of its additional_patchers
1185 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001186 # Pass the exception to __exit__
1187 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001188 # re-raise the exception
1189 raise
Michael Foord345266a2012-03-14 12:24:34 -07001190 finally:
1191 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001192 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001193
1194 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001195 return patched
1196
1197
1198 def get_original(self):
1199 target = self.getter()
1200 name = self.attribute
1201
1202 original = DEFAULT
1203 local = False
1204
1205 try:
1206 original = target.__dict__[name]
1207 except (AttributeError, KeyError):
1208 original = getattr(target, name, DEFAULT)
1209 else:
1210 local = True
1211
Michael Foordfddcfa22014-04-14 16:25:20 -04001212 if name in _builtins and isinstance(target, ModuleType):
1213 self.create = True
1214
Michael Foord345266a2012-03-14 12:24:34 -07001215 if not self.create and original is DEFAULT:
1216 raise AttributeError(
1217 "%s does not have the attribute %r" % (target, name)
1218 )
1219 return original, local
1220
1221
1222 def __enter__(self):
1223 """Perform the patch."""
1224 new, spec, spec_set = self.new, self.spec, self.spec_set
1225 autospec, kwargs = self.autospec, self.kwargs
1226 new_callable = self.new_callable
1227 self.target = self.getter()
1228
Michael Foord50a8c0e2012-03-25 18:57:58 +01001229 # normalise False to None
1230 if spec is False:
1231 spec = None
1232 if spec_set is False:
1233 spec_set = None
1234 if autospec is False:
1235 autospec = None
1236
1237 if spec is not None and autospec is not None:
1238 raise TypeError("Can't specify spec and autospec")
1239 if ((spec is not None or autospec is not None) and
1240 spec_set not in (True, None)):
1241 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1242
Michael Foord345266a2012-03-14 12:24:34 -07001243 original, local = self.get_original()
1244
Michael Foord50a8c0e2012-03-25 18:57:58 +01001245 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001246 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001247 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001248 # set spec to the object we are replacing
1249 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001250 if spec_set is True:
1251 spec_set = original
1252 spec = None
1253 elif spec is not None:
1254 if spec_set is True:
1255 spec_set = spec
1256 spec = None
1257 elif spec_set is True:
1258 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001259
Michael Foord50a8c0e2012-03-25 18:57:58 +01001260 if spec is not None or spec_set is not None:
1261 if original is DEFAULT:
1262 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001263 if isinstance(original, type):
1264 # If we're patching out a class and there is a spec
1265 inherit = True
1266
1267 Klass = MagicMock
1268 _kwargs = {}
1269 if new_callable is not None:
1270 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001271 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001272 this_spec = spec
1273 if spec_set is not None:
1274 this_spec = spec_set
1275 if _is_list(this_spec):
1276 not_callable = '__call__' not in this_spec
1277 else:
1278 not_callable = not callable(this_spec)
1279 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001280 Klass = NonCallableMagicMock
1281
1282 if spec is not None:
1283 _kwargs['spec'] = spec
1284 if spec_set is not None:
1285 _kwargs['spec_set'] = spec_set
1286
1287 # add a name to mocks
1288 if (isinstance(Klass, type) and
1289 issubclass(Klass, NonCallableMock) and self.attribute):
1290 _kwargs['name'] = self.attribute
1291
1292 _kwargs.update(kwargs)
1293 new = Klass(**_kwargs)
1294
1295 if inherit and _is_instance_mock(new):
1296 # we can only tell if the instance should be callable if the
1297 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001298 this_spec = spec
1299 if spec_set is not None:
1300 this_spec = spec_set
1301 if (not _is_list(this_spec) and not
1302 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001303 Klass = NonCallableMagicMock
1304
1305 _kwargs.pop('name')
1306 new.return_value = Klass(_new_parent=new, _new_name='()',
1307 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001308 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001309 # spec is ignored, new *must* be default, spec_set is treated
1310 # as a boolean. Should we check spec is not None and that spec_set
1311 # is a bool?
1312 if new is not DEFAULT:
1313 raise TypeError(
1314 "autospec creates the mock for you. Can't specify "
1315 "autospec and new."
1316 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001317 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001318 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001319 spec_set = bool(spec_set)
1320 if autospec is True:
1321 autospec = original
1322
1323 new = create_autospec(autospec, spec_set=spec_set,
1324 _name=self.attribute, **kwargs)
1325 elif kwargs:
1326 # can't set keyword args when we aren't creating the mock
1327 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1328 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1329
1330 new_attr = new
1331
1332 self.temp_original = original
1333 self.is_local = local
1334 setattr(self.target, self.attribute, new_attr)
1335 if self.attribute_name is not None:
1336 extra_args = {}
1337 if self.new is DEFAULT:
1338 extra_args[self.attribute_name] = new
1339 for patching in self.additional_patchers:
1340 arg = patching.__enter__()
1341 if patching.new is DEFAULT:
1342 extra_args.update(arg)
1343 return extra_args
1344
1345 return new
1346
1347
Michael Foord50a8c0e2012-03-25 18:57:58 +01001348 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001349 """Undo the patch."""
1350 if not _is_started(self):
1351 raise RuntimeError('stop called on unstarted patcher')
1352
1353 if self.is_local and self.temp_original is not DEFAULT:
1354 setattr(self.target, self.attribute, self.temp_original)
1355 else:
1356 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001357 if not self.create and (not hasattr(self.target, self.attribute) or
1358 self.attribute in ('__doc__', '__module__',
1359 '__defaults__', '__annotations__',
1360 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001361 # needed for proxy objects like django settings
1362 setattr(self.target, self.attribute, self.temp_original)
1363
1364 del self.temp_original
1365 del self.is_local
1366 del self.target
1367 for patcher in reversed(self.additional_patchers):
1368 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001369 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001370
Michael Foordf7c41582012-06-10 20:36:32 +01001371
1372 def start(self):
1373 """Activate a patch, returning any created mock."""
1374 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001375 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001376 return result
1377
1378
1379 def stop(self):
1380 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001381 try:
1382 self._active_patches.remove(self)
1383 except ValueError:
1384 # If the patch hasn't been started this will fail
1385 pass
1386
Michael Foordf7c41582012-06-10 20:36:32 +01001387 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001388
1389
1390
1391def _get_target(target):
1392 try:
1393 target, attribute = target.rsplit('.', 1)
1394 except (TypeError, ValueError):
1395 raise TypeError("Need a valid target to patch. You supplied: %r" %
1396 (target,))
1397 getter = lambda: _importer(target)
1398 return getter, attribute
1399
1400
1401def _patch_object(
1402 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001403 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001404 new_callable=None, **kwargs
1405 ):
1406 """
Michael Foord345266a2012-03-14 12:24:34 -07001407 patch the named member (`attribute`) on an object (`target`) with a mock
1408 object.
1409
1410 `patch.object` can be used as a decorator, class decorator or a context
1411 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1412 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1413 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1414 the mock object it creates.
1415
1416 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1417 for choosing which methods to wrap.
1418 """
1419 getter = lambda: target
1420 return _patch(
1421 getter, attribute, new, spec, create,
1422 spec_set, autospec, new_callable, kwargs
1423 )
1424
1425
Michael Foord50a8c0e2012-03-25 18:57:58 +01001426def _patch_multiple(target, spec=None, create=False, spec_set=None,
1427 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001428 """Perform multiple patches in a single call. It takes the object to be
1429 patched (either as an object or a string to fetch the object by importing)
1430 and keyword arguments for the patches::
1431
1432 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1433 ...
1434
1435 Use `DEFAULT` as the value if you want `patch.multiple` to create
1436 mocks for you. In this case the created mocks are passed into a decorated
1437 function by keyword, and a dictionary is returned when `patch.multiple` is
1438 used as a context manager.
1439
1440 `patch.multiple` can be used as a decorator, class decorator or a context
1441 manager. The arguments `spec`, `spec_set`, `create`,
1442 `autospec` and `new_callable` have the same meaning as for `patch`. These
1443 arguments will be applied to *all* patches done by `patch.multiple`.
1444
1445 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1446 for choosing which methods to wrap.
1447 """
1448 if type(target) is str:
1449 getter = lambda: _importer(target)
1450 else:
1451 getter = lambda: target
1452
1453 if not kwargs:
1454 raise ValueError(
1455 'Must supply at least one keyword argument with patch.multiple'
1456 )
1457 # need to wrap in a list for python 3, where items is a view
1458 items = list(kwargs.items())
1459 attribute, new = items[0]
1460 patcher = _patch(
1461 getter, attribute, new, spec, create, spec_set,
1462 autospec, new_callable, {}
1463 )
1464 patcher.attribute_name = attribute
1465 for attribute, new in items[1:]:
1466 this_patcher = _patch(
1467 getter, attribute, new, spec, create, spec_set,
1468 autospec, new_callable, {}
1469 )
1470 this_patcher.attribute_name = attribute
1471 patcher.additional_patchers.append(this_patcher)
1472 return patcher
1473
1474
1475def patch(
1476 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001477 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001478 ):
1479 """
1480 `patch` acts as a function decorator, class decorator or a context
1481 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001482 is patched with a `new` object. When the function/with statement exits
1483 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001484
Michael Foord54b3db82012-03-28 15:08:08 +01001485 If `new` is omitted, then the target is replaced with a
1486 `MagicMock`. If `patch` is used as a decorator and `new` is
1487 omitted, the created mock is passed in as an extra argument to the
1488 decorated function. If `patch` is used as a context manager the created
1489 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001490
Michael Foord54b3db82012-03-28 15:08:08 +01001491 `target` should be a string in the form `'package.module.ClassName'`. The
1492 `target` is imported and the specified object replaced with the `new`
1493 object, so the `target` must be importable from the environment you are
1494 calling `patch` from. The target is imported when the decorated function
1495 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001496
1497 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1498 if patch is creating one for you.
1499
1500 In addition you can pass `spec=True` or `spec_set=True`, which causes
1501 patch to pass in the object being mocked as the spec/spec_set object.
1502
1503 `new_callable` allows you to specify a different class, or callable object,
1504 that will be called to create the `new` object. By default `MagicMock` is
1505 used.
1506
1507 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001508 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001509 All attributes of the mock will also have the spec of the corresponding
1510 attribute of the object being replaced. Methods and functions being
1511 mocked will have their arguments checked and will raise a `TypeError` if
1512 they are called with the wrong signature. For mocks replacing a class,
1513 their return value (the 'instance') will have the same spec as the class.
1514
1515 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1516 arbitrary object as the spec instead of the one being replaced.
1517
1518 By default `patch` will fail to replace attributes that don't exist. If
1519 you pass in `create=True`, and the attribute doesn't exist, patch will
1520 create the attribute for you when the patched function is called, and
1521 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001522 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001523 default because it can be dangerous. With it switched on you can write
1524 passing tests against APIs that don't actually exist!
1525
1526 Patch can be used as a `TestCase` class decorator. It works by
1527 decorating each test method in the class. This reduces the boilerplate
1528 code when your test methods share a common patchings set. `patch` finds
1529 tests by looking for method names that start with `patch.TEST_PREFIX`.
1530 By default this is `test`, which matches the way `unittest` finds tests.
1531 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1532
1533 Patch can be used as a context manager, with the with statement. Here the
1534 patching applies to the indented block after the with statement. If you
1535 use "as" then the patched object will be bound to the name after the
1536 "as"; very useful if `patch` is creating a mock object for you.
1537
1538 `patch` takes arbitrary keyword arguments. These will be passed to
1539 the `Mock` (or `new_callable`) on construction.
1540
1541 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1542 available for alternate use-cases.
1543 """
1544 getter, attribute = _get_target(target)
1545 return _patch(
1546 getter, attribute, new, spec, create,
1547 spec_set, autospec, new_callable, kwargs
1548 )
1549
1550
1551class _patch_dict(object):
1552 """
1553 Patch a dictionary, or dictionary like object, and restore the dictionary
1554 to its original state after the test.
1555
1556 `in_dict` can be a dictionary or a mapping like container. If it is a
1557 mapping then it must at least support getting, setting and deleting items
1558 plus iterating over keys.
1559
1560 `in_dict` can also be a string specifying the name of the dictionary, which
1561 will then be fetched by importing it.
1562
1563 `values` can be a dictionary of values to set in the dictionary. `values`
1564 can also be an iterable of `(key, value)` pairs.
1565
1566 If `clear` is True then the dictionary will be cleared before the new
1567 values are set.
1568
1569 `patch.dict` can also be called with arbitrary keyword arguments to set
1570 values in the dictionary::
1571
1572 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1573 ...
1574
1575 `patch.dict` can be used as a context manager, decorator or class
1576 decorator. When used as a class decorator `patch.dict` honours
1577 `patch.TEST_PREFIX` for choosing which methods to wrap.
1578 """
1579
1580 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1581 if isinstance(in_dict, str):
1582 in_dict = _importer(in_dict)
1583 self.in_dict = in_dict
1584 # support any argument supported by dict(...) constructor
1585 self.values = dict(values)
1586 self.values.update(kwargs)
1587 self.clear = clear
1588 self._original = None
1589
1590
1591 def __call__(self, f):
1592 if isinstance(f, type):
1593 return self.decorate_class(f)
1594 @wraps(f)
1595 def _inner(*args, **kw):
1596 self._patch_dict()
1597 try:
1598 return f(*args, **kw)
1599 finally:
1600 self._unpatch_dict()
1601
1602 return _inner
1603
1604
1605 def decorate_class(self, klass):
1606 for attr in dir(klass):
1607 attr_value = getattr(klass, attr)
1608 if (attr.startswith(patch.TEST_PREFIX) and
1609 hasattr(attr_value, "__call__")):
1610 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1611 decorated = decorator(attr_value)
1612 setattr(klass, attr, decorated)
1613 return klass
1614
1615
1616 def __enter__(self):
1617 """Patch the dict."""
1618 self._patch_dict()
1619
1620
1621 def _patch_dict(self):
1622 values = self.values
1623 in_dict = self.in_dict
1624 clear = self.clear
1625
1626 try:
1627 original = in_dict.copy()
1628 except AttributeError:
1629 # dict like object with no copy method
1630 # must support iteration over keys
1631 original = {}
1632 for key in in_dict:
1633 original[key] = in_dict[key]
1634 self._original = original
1635
1636 if clear:
1637 _clear_dict(in_dict)
1638
1639 try:
1640 in_dict.update(values)
1641 except AttributeError:
1642 # dict like object with no update method
1643 for key in values:
1644 in_dict[key] = values[key]
1645
1646
1647 def _unpatch_dict(self):
1648 in_dict = self.in_dict
1649 original = self._original
1650
1651 _clear_dict(in_dict)
1652
1653 try:
1654 in_dict.update(original)
1655 except AttributeError:
1656 for key in original:
1657 in_dict[key] = original[key]
1658
1659
1660 def __exit__(self, *args):
1661 """Unpatch the dict."""
1662 self._unpatch_dict()
1663 return False
1664
1665 start = __enter__
1666 stop = __exit__
1667
1668
1669def _clear_dict(in_dict):
1670 try:
1671 in_dict.clear()
1672 except AttributeError:
1673 keys = list(in_dict)
1674 for key in keys:
1675 del in_dict[key]
1676
1677
Michael Foordf7c41582012-06-10 20:36:32 +01001678def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001679 """Stop all active patches. LIFO to unroll nested patches."""
1680 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001681 patch.stop()
1682
1683
Michael Foord345266a2012-03-14 12:24:34 -07001684patch.object = _patch_object
1685patch.dict = _patch_dict
1686patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001687patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001688patch.TEST_PREFIX = 'test'
1689
1690magic_methods = (
1691 "lt le gt ge eq ne "
1692 "getitem setitem delitem "
1693 "len contains iter "
1694 "hash str sizeof "
1695 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001696 # we added divmod and rdivmod here instead of numerics
1697 # because there is no idivmod
1698 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001699 "complex int float index "
1700 "trunc floor ceil "
1701 "bool next "
1702)
1703
Michael Foordd2623d72014-04-14 11:23:48 -04001704numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001705 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001706)
Michael Foord345266a2012-03-14 12:24:34 -07001707inplace = ' '.join('i%s' % n for n in numerics.split())
1708right = ' '.join('r%s' % n for n in numerics.split())
1709
1710# not including __prepare__, __instancecheck__, __subclasscheck__
1711# (as they are metaclass methods)
1712# __del__ is not supported at all as it causes problems if it exists
1713
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001714_non_defaults = {
1715 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1716 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1717 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1718 '__repr__', '__dir__', '__subclasses__', '__format__',
Serhiy Storchaka5943ea72016-06-19 18:30:43 +03001719 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001720}
Michael Foord345266a2012-03-14 12:24:34 -07001721
1722
1723def _get_method(name, func):
1724 "Turns a callable object (like a mock) into a real function"
1725 def method(self, *args, **kw):
1726 return func(self, *args, **kw)
1727 method.__name__ = name
1728 return method
1729
1730
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001731_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001732 '__%s__' % method for method in
1733 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001734}
Michael Foord345266a2012-03-14 12:24:34 -07001735
1736_all_magics = _magics | _non_defaults
1737
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001738_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001739 '__getattr__', '__setattr__',
1740 '__init__', '__new__', '__prepare__'
1741 '__instancecheck__', '__subclasscheck__',
1742 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001743}
Michael Foord345266a2012-03-14 12:24:34 -07001744
1745_calculate_return_value = {
1746 '__hash__': lambda self: object.__hash__(self),
1747 '__str__': lambda self: object.__str__(self),
1748 '__sizeof__': lambda self: object.__sizeof__(self),
1749}
1750
1751_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001752 '__lt__': NotImplemented,
1753 '__gt__': NotImplemented,
1754 '__le__': NotImplemented,
1755 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001756 '__int__': 1,
1757 '__contains__': False,
1758 '__len__': 0,
1759 '__exit__': False,
1760 '__complex__': 1j,
1761 '__float__': 1.0,
1762 '__bool__': True,
1763 '__index__': 1,
1764}
1765
1766
1767def _get_eq(self):
1768 def __eq__(other):
1769 ret_val = self.__eq__._mock_return_value
1770 if ret_val is not DEFAULT:
1771 return ret_val
1772 return self is other
1773 return __eq__
1774
1775def _get_ne(self):
1776 def __ne__(other):
1777 if self.__ne__._mock_return_value is not DEFAULT:
1778 return DEFAULT
1779 return self is not other
1780 return __ne__
1781
1782def _get_iter(self):
1783 def __iter__():
1784 ret_val = self.__iter__._mock_return_value
1785 if ret_val is DEFAULT:
1786 return iter([])
1787 # if ret_val was already an iterator, then calling iter on it should
1788 # return the iterator unchanged
1789 return iter(ret_val)
1790 return __iter__
1791
1792_side_effect_methods = {
1793 '__eq__': _get_eq,
1794 '__ne__': _get_ne,
1795 '__iter__': _get_iter,
1796}
1797
1798
1799
1800def _set_return_value(mock, method, name):
1801 fixed = _return_values.get(name, DEFAULT)
1802 if fixed is not DEFAULT:
1803 method.return_value = fixed
1804 return
1805
1806 return_calulator = _calculate_return_value.get(name)
1807 if return_calulator is not None:
1808 try:
1809 return_value = return_calulator(mock)
1810 except AttributeError:
1811 # XXXX why do we return AttributeError here?
1812 # set it as a side_effect instead?
1813 return_value = AttributeError(name)
1814 method.return_value = return_value
1815 return
1816
1817 side_effector = _side_effect_methods.get(name)
1818 if side_effector is not None:
1819 method.side_effect = side_effector(mock)
1820
1821
1822
1823class MagicMixin(object):
1824 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001825 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001826 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001827 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001828
1829
1830 def _mock_set_magics(self):
1831 these_magics = _magics
1832
Łukasz Langaa468db92015-04-13 23:12:42 -07001833 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001834 these_magics = _magics.intersection(self._mock_methods)
1835
1836 remove_magics = set()
1837 remove_magics = _magics - these_magics
1838
1839 for entry in remove_magics:
1840 if entry in type(self).__dict__:
1841 # remove unneeded magic methods
1842 delattr(self, entry)
1843
1844 # don't overwrite existing attributes if called a second time
1845 these_magics = these_magics - set(type(self).__dict__)
1846
1847 _type = type(self)
1848 for entry in these_magics:
1849 setattr(_type, entry, MagicProxy(entry, self))
1850
1851
1852
1853class NonCallableMagicMock(MagicMixin, NonCallableMock):
1854 """A version of `MagicMock` that isn't callable."""
1855 def mock_add_spec(self, spec, spec_set=False):
1856 """Add a spec to a mock. `spec` can either be an object or a
1857 list of strings. Only attributes on the `spec` can be fetched as
1858 attributes from the mock.
1859
1860 If `spec_set` is True then only attributes on the spec can be set."""
1861 self._mock_add_spec(spec, spec_set)
1862 self._mock_set_magics()
1863
1864
1865
1866class MagicMock(MagicMixin, Mock):
1867 """
1868 MagicMock is a subclass of Mock with default implementations
1869 of most of the magic methods. You can use MagicMock without having to
1870 configure the magic methods yourself.
1871
1872 If you use the `spec` or `spec_set` arguments then *only* magic
1873 methods that exist in the spec will be created.
1874
1875 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1876 """
1877 def mock_add_spec(self, spec, spec_set=False):
1878 """Add a spec to a mock. `spec` can either be an object or a
1879 list of strings. Only attributes on the `spec` can be fetched as
1880 attributes from the mock.
1881
1882 If `spec_set` is True then only attributes on the spec can be set."""
1883 self._mock_add_spec(spec, spec_set)
1884 self._mock_set_magics()
1885
1886
1887
1888class MagicProxy(object):
1889 def __init__(self, name, parent):
1890 self.name = name
1891 self.parent = parent
1892
1893 def __call__(self, *args, **kwargs):
1894 m = self.create_mock()
1895 return m(*args, **kwargs)
1896
1897 def create_mock(self):
1898 entry = self.name
1899 parent = self.parent
1900 m = parent._get_child_mock(name=entry, _new_name=entry,
1901 _new_parent=parent)
1902 setattr(parent, entry, m)
1903 _set_return_value(parent, m, entry)
1904 return m
1905
1906 def __get__(self, obj, _type=None):
1907 return self.create_mock()
1908
1909
1910
1911class _ANY(object):
1912 "A helper object that compares equal to everything."
1913
1914 def __eq__(self, other):
1915 return True
1916
1917 def __ne__(self, other):
1918 return False
1919
1920 def __repr__(self):
1921 return '<ANY>'
1922
1923ANY = _ANY()
1924
1925
1926
1927def _format_call_signature(name, args, kwargs):
1928 message = '%s(%%s)' % name
1929 formatted_args = ''
1930 args_string = ', '.join([repr(arg) for arg in args])
1931 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301932 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001933 ])
1934 if args_string:
1935 formatted_args = args_string
1936 if kwargs_string:
1937 if formatted_args:
1938 formatted_args += ', '
1939 formatted_args += kwargs_string
1940
1941 return message % formatted_args
1942
1943
1944
1945class _Call(tuple):
1946 """
1947 A tuple for holding the results of a call to a mock, either in the form
1948 `(args, kwargs)` or `(name, args, kwargs)`.
1949
1950 If args or kwargs are empty then a call tuple will compare equal to
1951 a tuple without those values. This makes comparisons less verbose::
1952
1953 _Call(('name', (), {})) == ('name',)
1954 _Call(('name', (1,), {})) == ('name', (1,))
1955 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1956
1957 The `_Call` object provides a useful shortcut for comparing with call::
1958
1959 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1960 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1961
1962 If the _Call has no name then it will match any name.
1963 """
1964 def __new__(cls, value=(), name=None, parent=None, two=False,
1965 from_kall=True):
1966 name = ''
1967 args = ()
1968 kwargs = {}
1969 _len = len(value)
1970 if _len == 3:
1971 name, args, kwargs = value
1972 elif _len == 2:
1973 first, second = value
1974 if isinstance(first, str):
1975 name = first
1976 if isinstance(second, tuple):
1977 args = second
1978 else:
1979 kwargs = second
1980 else:
1981 args, kwargs = first, second
1982 elif _len == 1:
1983 value, = value
1984 if isinstance(value, str):
1985 name = value
1986 elif isinstance(value, tuple):
1987 args = value
1988 else:
1989 kwargs = value
1990
1991 if two:
1992 return tuple.__new__(cls, (args, kwargs))
1993
1994 return tuple.__new__(cls, (name, args, kwargs))
1995
1996
1997 def __init__(self, value=(), name=None, parent=None, two=False,
1998 from_kall=True):
1999 self.name = name
2000 self.parent = parent
2001 self.from_kall = from_kall
2002
2003
2004 def __eq__(self, other):
2005 if other is ANY:
2006 return True
2007 try:
2008 len_other = len(other)
2009 except TypeError:
2010 return False
2011
2012 self_name = ''
2013 if len(self) == 2:
2014 self_args, self_kwargs = self
2015 else:
2016 self_name, self_args, self_kwargs = self
2017
2018 other_name = ''
2019 if len_other == 0:
2020 other_args, other_kwargs = (), {}
2021 elif len_other == 3:
2022 other_name, other_args, other_kwargs = other
2023 elif len_other == 1:
2024 value, = other
2025 if isinstance(value, tuple):
2026 other_args = value
2027 other_kwargs = {}
2028 elif isinstance(value, str):
2029 other_name = value
2030 other_args, other_kwargs = (), {}
2031 else:
2032 other_args = ()
2033 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002034 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002035 # could be (name, args) or (name, kwargs) or (args, kwargs)
2036 first, second = other
2037 if isinstance(first, str):
2038 other_name = first
2039 if isinstance(second, tuple):
2040 other_args, other_kwargs = second, {}
2041 else:
2042 other_args, other_kwargs = (), second
2043 else:
2044 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002045 else:
2046 return False
Michael Foord345266a2012-03-14 12:24:34 -07002047
2048 if self_name and other_name != self_name:
2049 return False
2050
2051 # this order is important for ANY to work!
2052 return (other_args, other_kwargs) == (self_args, self_kwargs)
2053
2054
Berker Peksagce913872016-03-28 00:30:02 +03002055 __ne__ = object.__ne__
2056
2057
Michael Foord345266a2012-03-14 12:24:34 -07002058 def __call__(self, *args, **kwargs):
2059 if self.name is None:
2060 return _Call(('', args, kwargs), name='()')
2061
2062 name = self.name + '()'
2063 return _Call((self.name, args, kwargs), name=name, parent=self)
2064
2065
2066 def __getattr__(self, attr):
2067 if self.name is None:
2068 return _Call(name=attr, from_kall=False)
2069 name = '%s.%s' % (self.name, attr)
2070 return _Call(name=name, parent=self, from_kall=False)
2071
2072
Kushal Dasa37b9582014-09-16 18:33:37 +05302073 def count(self, *args, **kwargs):
2074 return self.__getattr__('count')(*args, **kwargs)
2075
2076 def index(self, *args, **kwargs):
2077 return self.__getattr__('index')(*args, **kwargs)
2078
Michael Foord345266a2012-03-14 12:24:34 -07002079 def __repr__(self):
2080 if not self.from_kall:
2081 name = self.name or 'call'
2082 if name.startswith('()'):
2083 name = 'call%s' % name
2084 return name
2085
2086 if len(self) == 2:
2087 name = 'call'
2088 args, kwargs = self
2089 else:
2090 name, args, kwargs = self
2091 if not name:
2092 name = 'call'
2093 elif not name.startswith('()'):
2094 name = 'call.%s' % name
2095 else:
2096 name = 'call%s' % name
2097 return _format_call_signature(name, args, kwargs)
2098
2099
2100 def call_list(self):
2101 """For a call object that represents multiple calls, `call_list`
2102 returns a list of all the intermediate calls as well as the
2103 final call."""
2104 vals = []
2105 thing = self
2106 while thing is not None:
2107 if thing.from_kall:
2108 vals.append(thing)
2109 thing = thing.parent
2110 return _CallList(reversed(vals))
2111
2112
2113call = _Call(from_kall=False)
2114
2115
2116
2117def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2118 _name=None, **kwargs):
2119 """Create a mock object using another object as a spec. Attributes on the
2120 mock will use the corresponding attribute on the `spec` object as their
2121 spec.
2122
2123 Functions or methods being mocked will have their arguments checked
2124 to check that they are called with the correct signature.
2125
2126 If `spec_set` is True then attempting to set attributes that don't exist
2127 on the spec object will raise an `AttributeError`.
2128
2129 If a class is used as a spec then the return value of the mock (the
2130 instance of the class) will have the same spec. You can use a class as the
2131 spec for an instance object by passing `instance=True`. The returned mock
2132 will only be callable if instances of the mock are callable.
2133
2134 `create_autospec` also takes arbitrary keyword arguments that are passed to
2135 the constructor of the created mock."""
2136 if _is_list(spec):
2137 # can't pass a list instance to the mock constructor as it will be
2138 # interpreted as a list of strings
2139 spec = type(spec)
2140
2141 is_type = isinstance(spec, type)
2142
2143 _kwargs = {'spec': spec}
2144 if spec_set:
2145 _kwargs = {'spec_set': spec}
2146 elif spec is None:
2147 # None we mock with a normal mock without a spec
2148 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002149 if _kwargs and instance:
2150 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002151
2152 _kwargs.update(kwargs)
2153
2154 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002155 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002156 # descriptors don't have a spec
2157 # because we don't know what type they return
2158 _kwargs = {}
2159 elif not _callable(spec):
2160 Klass = NonCallableMagicMock
2161 elif is_type and instance and not _instance_callable(spec):
2162 Klass = NonCallableMagicMock
2163
Kushal Das484f8a82014-04-16 01:05:50 +05302164 _name = _kwargs.pop('name', _name)
2165
Michael Foord345266a2012-03-14 12:24:34 -07002166 _new_name = _name
2167 if _parent is None:
2168 # for a top level object no _new_name should be set
2169 _new_name = ''
2170
2171 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2172 name=_name, **_kwargs)
2173
2174 if isinstance(spec, FunctionTypes):
2175 # should only happen at the top level because we don't
2176 # recurse for functions
2177 mock = _set_signature(mock, spec)
2178 else:
2179 _check_signature(spec, mock, is_type, instance)
2180
2181 if _parent is not None and not instance:
2182 _parent._mock_children[_name] = mock
2183
2184 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002185 mock.return_value = create_autospec(spec, spec_set, instance=True,
2186 _name='()', _parent=mock)
2187
2188 for entry in dir(spec):
2189 if _is_magic(entry):
2190 # MagicMock already does the useful magic methods for us
2191 continue
2192
Michael Foord345266a2012-03-14 12:24:34 -07002193 # XXXX do we need a better way of getting attributes without
2194 # triggering code execution (?) Probably not - we need the actual
2195 # object to mock it so we would rather trigger a property than mock
2196 # the property descriptor. Likewise we want to mock out dynamically
2197 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002198 # XXXX what about attributes that raise exceptions other than
2199 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002200 # we could be resilient against it, or catch and propagate the
2201 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002202 try:
2203 original = getattr(spec, entry)
2204 except AttributeError:
2205 continue
Michael Foord345266a2012-03-14 12:24:34 -07002206
2207 kwargs = {'spec': original}
2208 if spec_set:
2209 kwargs = {'spec_set': original}
2210
2211 if not isinstance(original, FunctionTypes):
2212 new = _SpecState(original, spec_set, mock, entry, instance)
2213 mock._mock_children[entry] = new
2214 else:
2215 parent = mock
2216 if isinstance(spec, FunctionTypes):
2217 parent = mock.mock
2218
Michael Foord345266a2012-03-14 12:24:34 -07002219 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002220 kwargs['_eat_self'] = skipfirst
2221 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2222 _new_parent=parent,
2223 **kwargs)
2224 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002225 _check_signature(original, new, skipfirst=skipfirst)
2226
2227 # so functions created with _set_signature become instance attributes,
2228 # *plus* their underlying mock exists in _mock_children of the parent
2229 # mock. Adding to _mock_children may be unnecessary where we are also
2230 # setting as an instance attribute?
2231 if isinstance(new, FunctionTypes):
2232 setattr(mock, entry, new)
2233
2234 return mock
2235
2236
2237def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002238 """
2239 Return whether we should skip the first argument on spec's `entry`
2240 attribute.
2241 """
Michael Foord345266a2012-03-14 12:24:34 -07002242 if not isinstance(spec, type):
2243 if entry in getattr(spec, '__dict__', {}):
2244 # instance attribute - shouldn't skip
2245 return False
Michael Foord345266a2012-03-14 12:24:34 -07002246 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002247
2248 for klass in spec.__mro__:
2249 result = klass.__dict__.get(entry, DEFAULT)
2250 if result is DEFAULT:
2251 continue
2252 if isinstance(result, (staticmethod, classmethod)):
2253 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002254 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2255 # Normal method => skip if looked up on type
2256 # (if looked up on instance, self is already skipped)
2257 return is_type
2258 else:
2259 return False
Michael Foord345266a2012-03-14 12:24:34 -07002260
2261 # shouldn't get here unless function is a dynamically provided attribute
2262 # XXXX untested behaviour
2263 return is_type
2264
2265
2266def _get_class(obj):
2267 try:
2268 return obj.__class__
2269 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002270 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002271 return type(obj)
2272
2273
2274class _SpecState(object):
2275
2276 def __init__(self, spec, spec_set=False, parent=None,
2277 name=None, ids=None, instance=False):
2278 self.spec = spec
2279 self.ids = ids
2280 self.spec_set = spec_set
2281 self.parent = parent
2282 self.instance = instance
2283 self.name = name
2284
2285
2286FunctionTypes = (
2287 # python function
2288 type(create_autospec),
2289 # instance method
2290 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002291)
2292
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002293MethodWrapperTypes = (
2294 type(ANY.__eq__.__get__),
2295)
2296
Michael Foord345266a2012-03-14 12:24:34 -07002297
Michael Foorda74561a2012-03-25 19:03:13 +01002298file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002299
Michael Foord04cbe0c2013-03-19 17:22:51 -07002300def _iterate_read_data(read_data):
2301 # Helper for mock_open:
2302 # Retrieve lines from read_data via a generator so that separate calls to
2303 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002304 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2305 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002306
Berker Peksag86b34da2015-08-06 13:15:51 +03002307 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002308 # If the last line ended in a newline, the list comprehension will have an
2309 # extra entry that's just a newline. Remove this.
2310 data_as_list = data_as_list[:-1]
2311 else:
2312 # If there wasn't an extra newline by itself, then the file being
2313 # emulated doesn't have a newline to end the last line remove the
2314 # newline that our naive format() added
2315 data_as_list[-1] = data_as_list[-1][:-1]
2316
2317 for line in data_as_list:
2318 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002319
Robert Collins5329aaa2015-07-17 20:08:45 +12002320
Michael Foord0dccf652012-03-25 19:11:50 +01002321def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002322 """
2323 A helper function to create a mock to replace the use of `open`. It works
2324 for `open` called directly or used as a context manager.
2325
2326 The `mock` argument is the mock object to configure. If `None` (the
2327 default) then a `MagicMock` will be created for you, with the API limited
2328 to methods or attributes available on standard file handles.
2329
Michael Foord04cbe0c2013-03-19 17:22:51 -07002330 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2331 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002332 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002333 def _readlines_side_effect(*args, **kwargs):
2334 if handle.readlines.return_value is not None:
2335 return handle.readlines.return_value
2336 return list(_state[0])
2337
2338 def _read_side_effect(*args, **kwargs):
2339 if handle.read.return_value is not None:
2340 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002341 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002342
2343 def _readline_side_effect():
2344 if handle.readline.return_value is not None:
2345 while True:
2346 yield handle.readline.return_value
2347 for line in _state[0]:
2348 yield line
Robert Collins9549a3e2016-05-16 15:22:01 +12002349 while True:
2350 yield type(read_data)()
Robert Collinsca647ef2015-07-24 03:48:20 +12002351
2352
Michael Foorda74561a2012-03-25 19:03:13 +01002353 global file_spec
2354 if file_spec is None:
2355 import _io
2356 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2357
Michael Foord345266a2012-03-14 12:24:34 -07002358 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002359 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002360
Robert Collinsca647ef2015-07-24 03:48:20 +12002361 handle = MagicMock(spec=file_spec)
2362 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002363
Robert Collinsca647ef2015-07-24 03:48:20 +12002364 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002365
Robert Collinsca647ef2015-07-24 03:48:20 +12002366 handle.write.return_value = None
2367 handle.read.return_value = None
2368 handle.readline.return_value = None
2369 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002370
Robert Collinsca647ef2015-07-24 03:48:20 +12002371 handle.read.side_effect = _read_side_effect
2372 _state[1] = _readline_side_effect()
2373 handle.readline.side_effect = _state[1]
2374 handle.readlines.side_effect = _readlines_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002375
Robert Collinsca647ef2015-07-24 03:48:20 +12002376 def reset_data(*args, **kwargs):
2377 _state[0] = _iterate_read_data(read_data)
2378 if handle.readline.side_effect == _state[1]:
2379 # Only reset the side effect if the user hasn't overridden it.
2380 _state[1] = _readline_side_effect()
2381 handle.readline.side_effect = _state[1]
2382 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002383
Robert Collinsca647ef2015-07-24 03:48:20 +12002384 mock.side_effect = reset_data
2385 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002386 return mock
2387
2388
2389class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002390 """
2391 A mock intended to be used as a property, or other descriptor, on a class.
2392 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2393 a return value when it is fetched.
2394
2395 Fetching a `PropertyMock` instance from an object calls the mock, with
2396 no args. Setting it calls the mock with the value being set.
2397 """
Michael Foordc2870622012-04-13 16:57:22 +01002398 def _get_child_mock(self, **kwargs):
2399 return MagicMock(**kwargs)
2400
Michael Foord345266a2012-03-14 12:24:34 -07002401 def __get__(self, obj, obj_type):
2402 return self()
2403 def __set__(self, obj, val):
2404 self(val)