blob: 315b61157bd65383f1ec22baa0e06d5e2cb41d32 [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):
Michael Foord345266a2012-03-14 12:24:34 -0700107 # we explicitly don't copy func.__dict__ into this copy as it would
108 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300109 for attribute in (
110 '__name__', '__doc__', '__text_signature__',
111 '__module__', '__defaults__', '__kwdefaults__',
112 ):
113 try:
114 setattr(funcopy, attribute, getattr(func, attribute))
115 except AttributeError:
116 pass
Michael Foord345266a2012-03-14 12:24:34 -0700117
118
119def _callable(obj):
120 if isinstance(obj, type):
121 return True
122 if getattr(obj, '__call__', None) is not None:
123 return True
124 return False
125
126
127def _is_list(obj):
128 # checks for list or tuples
129 # XXXX badly named!
130 return type(obj) in (list, tuple)
131
132
133def _instance_callable(obj):
134 """Given an object, return True if the object is callable.
135 For classes, return True if instances would be callable."""
136 if not isinstance(obj, type):
137 # already an instance
138 return getattr(obj, '__call__', None) is not None
139
Michael Foorda74b3aa2012-03-14 14:40:22 -0700140 # *could* be broken by a class overriding __mro__ or __dict__ via
141 # a metaclass
142 for base in (obj,) + obj.__mro__:
143 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700144 return True
145 return False
146
147
148def _set_signature(mock, original, instance=False):
149 # creates a function with signature (*args, **kwargs) that delegates to a
150 # mock. It still does signature checking by calling a lambda with the same
151 # signature as the original.
152 if not _callable(original):
153 return
154
155 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100156 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700157 if result is None:
Michael Foord345266a2012-03-14 12:24:34 -0700158 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100159 func, sig = result
160 def checksig(*args, **kwargs):
161 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700162 _copy_func_details(func, checksig)
163
164 name = original.__name__
165 if not name.isidentifier():
166 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100167 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700168 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100169 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700170 return mock(*args, **kwargs)""" % name
171 exec (src, context)
172 funcopy = context[name]
173 _setup_func(funcopy, mock)
174 return funcopy
175
176
177def _setup_func(funcopy, mock):
178 funcopy.mock = mock
179
180 # can't use isinstance with mocks
181 if not _is_instance_mock(mock):
182 return
183
184 def assert_called_with(*args, **kwargs):
185 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700186 def assert_called(*args, **kwargs):
187 return mock.assert_called(*args, **kwargs)
188 def assert_not_called(*args, **kwargs):
189 return mock.assert_not_called(*args, **kwargs)
190 def assert_called_once(*args, **kwargs):
191 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700192 def assert_called_once_with(*args, **kwargs):
193 return mock.assert_called_once_with(*args, **kwargs)
194 def assert_has_calls(*args, **kwargs):
195 return mock.assert_has_calls(*args, **kwargs)
196 def assert_any_call(*args, **kwargs):
197 return mock.assert_any_call(*args, **kwargs)
198 def reset_mock():
199 funcopy.method_calls = _CallList()
200 funcopy.mock_calls = _CallList()
201 mock.reset_mock()
202 ret = funcopy.return_value
203 if _is_instance_mock(ret) and not ret is mock:
204 ret.reset_mock()
205
206 funcopy.called = False
207 funcopy.call_count = 0
208 funcopy.call_args = None
209 funcopy.call_args_list = _CallList()
210 funcopy.method_calls = _CallList()
211 funcopy.mock_calls = _CallList()
212
213 funcopy.return_value = mock.return_value
214 funcopy.side_effect = mock.side_effect
215 funcopy._mock_children = mock._mock_children
216
217 funcopy.assert_called_with = assert_called_with
218 funcopy.assert_called_once_with = assert_called_once_with
219 funcopy.assert_has_calls = assert_has_calls
220 funcopy.assert_any_call = assert_any_call
221 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700222 funcopy.assert_called = assert_called
223 funcopy.assert_not_called = assert_not_called
224 funcopy.assert_called_once = assert_called_once
Michael Foord345266a2012-03-14 12:24:34 -0700225
226 mock._mock_delegate = funcopy
227
228
229def _is_magic(name):
230 return '__%s__' % name[2:-2] == name
231
232
233class _SentinelObject(object):
234 "A unique, named, sentinel object."
235 def __init__(self, name):
236 self.name = name
237
238 def __repr__(self):
239 return 'sentinel.%s' % self.name
240
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200241 def __reduce__(self):
242 return 'sentinel.%s' % self.name
243
Michael Foord345266a2012-03-14 12:24:34 -0700244
245class _Sentinel(object):
246 """Access attributes to return a named object, usable as a sentinel."""
247 def __init__(self):
248 self._sentinels = {}
249
250 def __getattr__(self, name):
251 if name == '__bases__':
252 # Without this help(unittest.mock) raises an exception
253 raise AttributeError
254 return self._sentinels.setdefault(name, _SentinelObject(name))
255
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200256 def __reduce__(self):
257 return 'sentinel'
258
Michael Foord345266a2012-03-14 12:24:34 -0700259
260sentinel = _Sentinel()
261
262DEFAULT = sentinel.DEFAULT
263_missing = sentinel.MISSING
264_deleted = sentinel.DELETED
265
266
Michael Foord345266a2012-03-14 12:24:34 -0700267def _copy(value):
268 if type(value) in (dict, list, tuple, set):
269 return type(value)(value)
270 return value
271
272
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200273_allowed_names = {
274 'return_value', '_mock_return_value', 'side_effect',
275 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
276 '_mock_name', '_mock_new_name'
277}
Michael Foord345266a2012-03-14 12:24:34 -0700278
279
280def _delegating_property(name):
281 _allowed_names.add(name)
282 _the_name = '_mock_' + name
283 def _get(self, name=name, _the_name=_the_name):
284 sig = self._mock_delegate
285 if sig is None:
286 return getattr(self, _the_name)
287 return getattr(sig, name)
288 def _set(self, value, name=name, _the_name=_the_name):
289 sig = self._mock_delegate
290 if sig is None:
291 self.__dict__[_the_name] = value
292 else:
293 setattr(sig, name, value)
294
295 return property(_get, _set)
296
297
298
299class _CallList(list):
300
301 def __contains__(self, value):
302 if not isinstance(value, list):
303 return list.__contains__(self, value)
304 len_value = len(value)
305 len_self = len(self)
306 if len_value > len_self:
307 return False
308
309 for i in range(0, len_self - len_value + 1):
310 sub_list = self[i:i+len_value]
311 if sub_list == value:
312 return True
313 return False
314
315 def __repr__(self):
316 return pprint.pformat(list(self))
317
318
319def _check_and_set_parent(parent, value, name, new_name):
320 if not _is_instance_mock(value):
321 return False
322 if ((value._mock_name or value._mock_new_name) or
323 (value._mock_parent is not None) or
324 (value._mock_new_parent is not None)):
325 return False
326
327 _parent = parent
328 while _parent is not None:
329 # setting a mock (value) as a child or return value of itself
330 # should not modify the mock
331 if _parent is value:
332 return False
333 _parent = _parent._mock_new_parent
334
335 if new_name:
336 value._mock_new_parent = parent
337 value._mock_new_name = new_name
338 if name:
339 value._mock_parent = parent
340 value._mock_name = name
341 return True
342
Michael Foord01bafdc2014-04-14 16:09:42 -0400343# Internal class to identify if we wrapped an iterator object or not.
344class _MockIter(object):
345 def __init__(self, obj):
346 self.obj = iter(obj)
347 def __iter__(self):
348 return self
349 def __next__(self):
350 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700351
352class Base(object):
353 _mock_return_value = DEFAULT
354 _mock_side_effect = None
355 def __init__(self, *args, **kwargs):
356 pass
357
358
359
360class NonCallableMock(Base):
361 """A non-callable version of `Mock`"""
362
363 def __new__(cls, *args, **kw):
364 # every instance has its own class
365 # so we can create magic methods on the
366 # class without stomping on other mocks
367 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
368 instance = object.__new__(new)
369 return instance
370
371
372 def __init__(
373 self, spec=None, wraps=None, name=None, spec_set=None,
374 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530375 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700376 ):
377 if _new_parent is None:
378 _new_parent = parent
379
380 __dict__ = self.__dict__
381 __dict__['_mock_parent'] = parent
382 __dict__['_mock_name'] = name
383 __dict__['_mock_new_name'] = _new_name
384 __dict__['_mock_new_parent'] = _new_parent
385
386 if spec_set is not None:
387 spec = spec_set
388 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100389 if _eat_self is None:
390 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700391
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100392 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700393
394 __dict__['_mock_children'] = {}
395 __dict__['_mock_wraps'] = wraps
396 __dict__['_mock_delegate'] = None
397
398 __dict__['_mock_called'] = False
399 __dict__['_mock_call_args'] = None
400 __dict__['_mock_call_count'] = 0
401 __dict__['_mock_call_args_list'] = _CallList()
402 __dict__['_mock_mock_calls'] = _CallList()
403
404 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530405 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700406
407 if kwargs:
408 self.configure_mock(**kwargs)
409
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000410 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700411 spec, wraps, name, spec_set, parent,
412 _spec_state
413 )
414
415
416 def attach_mock(self, mock, attribute):
417 """
418 Attach a mock as an attribute of this one, replacing its name and
419 parent. Calls to the attached mock will be recorded in the
420 `method_calls` and `mock_calls` attributes of this one."""
421 mock._mock_parent = None
422 mock._mock_new_parent = None
423 mock._mock_name = ''
424 mock._mock_new_name = None
425
426 setattr(self, attribute, mock)
427
428
429 def mock_add_spec(self, spec, spec_set=False):
430 """Add a spec to a mock. `spec` can either be an object or a
431 list of strings. Only attributes on the `spec` can be fetched as
432 attributes from the mock.
433
434 If `spec_set` is True then only attributes on the spec can be set."""
435 self._mock_add_spec(spec, spec_set)
436
437
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100438 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
439 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700440 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100441 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700442
443 if spec is not None and not _is_list(spec):
444 if isinstance(spec, type):
445 _spec_class = spec
446 else:
447 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100448 res = _get_signature_object(spec,
449 _spec_as_instance, _eat_self)
450 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700451
452 spec = dir(spec)
453
454 __dict__ = self.__dict__
455 __dict__['_spec_class'] = _spec_class
456 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100457 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700458 __dict__['_mock_methods'] = spec
459
460
461 def __get_return_value(self):
462 ret = self._mock_return_value
463 if self._mock_delegate is not None:
464 ret = self._mock_delegate.return_value
465
466 if ret is DEFAULT:
467 ret = self._get_child_mock(
468 _new_parent=self, _new_name='()'
469 )
470 self.return_value = ret
471 return ret
472
473
474 def __set_return_value(self, value):
475 if self._mock_delegate is not None:
476 self._mock_delegate.return_value = value
477 else:
478 self._mock_return_value = value
479 _check_and_set_parent(self, value, None, '()')
480
481 __return_value_doc = "The value to be returned when the mock is called."
482 return_value = property(__get_return_value, __set_return_value,
483 __return_value_doc)
484
485
486 @property
487 def __class__(self):
488 if self._spec_class is None:
489 return type(self)
490 return self._spec_class
491
492 called = _delegating_property('called')
493 call_count = _delegating_property('call_count')
494 call_args = _delegating_property('call_args')
495 call_args_list = _delegating_property('call_args_list')
496 mock_calls = _delegating_property('mock_calls')
497
498
499 def __get_side_effect(self):
500 delegated = self._mock_delegate
501 if delegated is None:
502 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400503 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200504 if (sf is not None and not callable(sf)
505 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400506 sf = _MockIter(sf)
507 delegated.side_effect = sf
508 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700509
510 def __set_side_effect(self, value):
511 value = _try_iter(value)
512 delegated = self._mock_delegate
513 if delegated is None:
514 self._mock_side_effect = value
515 else:
516 delegated.side_effect = value
517
518 side_effect = property(__get_side_effect, __set_side_effect)
519
520
Kushal Das9cd39a12016-06-02 10:20:16 -0700521 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700522 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200523 if visited is None:
524 visited = []
525 if id(self) in visited:
526 return
527 visited.append(id(self))
528
Michael Foord345266a2012-03-14 12:24:34 -0700529 self.called = False
530 self.call_args = None
531 self.call_count = 0
532 self.mock_calls = _CallList()
533 self.call_args_list = _CallList()
534 self.method_calls = _CallList()
535
Kushal Das9cd39a12016-06-02 10:20:16 -0700536 if return_value:
537 self._mock_return_value = DEFAULT
538 if side_effect:
539 self._mock_side_effect = None
540
Michael Foord345266a2012-03-14 12:24:34 -0700541 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 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000747 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100748 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
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100775 def assert_called(_mock_self):
776 """assert that the mock was called at least once
777 """
778 self = _mock_self
779 if self.call_count == 0:
780 msg = ("Expected '%s' to have been called." %
781 self._mock_name or 'mock')
782 raise AssertionError(msg)
783
784 def assert_called_once(_mock_self):
785 """assert that the mock was called only once.
786 """
787 self = _mock_self
788 if not self.call_count == 1:
789 msg = ("Expected '%s' to have been called once. Called %s times." %
790 (self._mock_name or 'mock', self.call_count))
791 raise AssertionError(msg)
792
Michael Foord345266a2012-03-14 12:24:34 -0700793 def assert_called_with(_mock_self, *args, **kwargs):
794 """assert that the mock was called with the specified arguments.
795
796 Raises an AssertionError if the args and keyword args passed in are
797 different to the last call to the mock."""
798 self = _mock_self
799 if self.call_args is None:
800 expected = self._format_mock_call_signature(args, kwargs)
801 raise AssertionError('Expected call: %s\nNot called' % (expected,))
802
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100803 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700804 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100805 return msg
806 expected = self._call_matcher((args, kwargs))
807 actual = self._call_matcher(self.call_args)
808 if expected != actual:
809 cause = expected if isinstance(expected, Exception) else None
810 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700811
812
813 def assert_called_once_with(_mock_self, *args, **kwargs):
814 """assert that the mock was called exactly once and with the specified
815 arguments."""
816 self = _mock_self
817 if not self.call_count == 1:
Michael Foord28d591c2012-09-28 16:15:22 +0100818 msg = ("Expected '%s' to be called once. Called %s times." %
819 (self._mock_name or 'mock', self.call_count))
Michael Foord345266a2012-03-14 12:24:34 -0700820 raise AssertionError(msg)
821 return self.assert_called_with(*args, **kwargs)
822
823
824 def assert_has_calls(self, calls, any_order=False):
825 """assert the mock has been called with the specified calls.
826 The `mock_calls` list is checked for the calls.
827
828 If `any_order` is False (the default) then the calls must be
829 sequential. There can be extra calls before or after the
830 specified calls.
831
832 If `any_order` is True then the calls can be in any order, but
833 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100834 expected = [self._call_matcher(c) for c in calls]
835 cause = expected if isinstance(expected, Exception) else None
836 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700837 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100838 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700839 raise AssertionError(
840 'Calls not found.\nExpected: %r\n'
Senthil Kumaran121edbf2016-01-12 06:18:32 -0800841 'Actual: %r' % (_CallList(calls), self.mock_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100842 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700843 return
844
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100845 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700846
847 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100848 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700849 try:
850 all_calls.remove(kall)
851 except ValueError:
852 not_found.append(kall)
853 if not_found:
854 raise AssertionError(
855 '%r not all found in call list' % (tuple(not_found),)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100856 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700857
858
859 def assert_any_call(self, *args, **kwargs):
860 """assert the mock has been called with the specified arguments.
861
862 The assert passes if the mock has *ever* been called, unlike
863 `assert_called_with` and `assert_called_once_with` that only pass if
864 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100865 expected = self._call_matcher((args, kwargs))
866 actual = [self._call_matcher(c) for c in self.call_args_list]
867 if expected not in actual:
868 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700869 expected_string = self._format_mock_call_signature(args, kwargs)
870 raise AssertionError(
871 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100872 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700873
874
875 def _get_child_mock(self, **kw):
876 """Create the child mocks for attributes and return value.
877 By default child mocks will be the same type as the parent.
878 Subclasses of Mock may want to override this to customize the way
879 child mocks are made.
880
881 For non-callable mocks the callable variant will be used (rather than
882 any custom subclass)."""
883 _type = type(self)
884 if not issubclass(_type, CallableMixin):
885 if issubclass(_type, NonCallableMagicMock):
886 klass = MagicMock
887 elif issubclass(_type, NonCallableMock) :
888 klass = Mock
889 else:
890 klass = _type.__mro__[1]
891 return klass(**kw)
892
893
894
895def _try_iter(obj):
896 if obj is None:
897 return obj
898 if _is_exception(obj):
899 return obj
900 if _callable(obj):
901 return obj
902 try:
903 return iter(obj)
904 except TypeError:
905 # XXXX backwards compatibility
906 # but this will blow up on first call - so maybe we should fail early?
907 return obj
908
909
910
911class CallableMixin(Base):
912
913 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
914 wraps=None, name=None, spec_set=None, parent=None,
915 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
916 self.__dict__['_mock_return_value'] = return_value
917
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000918 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700919 spec, wraps, name, spec_set, parent,
920 _spec_state, _new_name, _new_parent, **kwargs
921 )
922
923 self.side_effect = side_effect
924
925
926 def _mock_check_sig(self, *args, **kwargs):
927 # stub method that can be replaced with one with a specific signature
928 pass
929
930
931 def __call__(_mock_self, *args, **kwargs):
932 # can't use self in-case a function / method we are mocking uses self
933 # in the signature
934 _mock_self._mock_check_sig(*args, **kwargs)
935 return _mock_self._mock_call(*args, **kwargs)
936
937
938 def _mock_call(_mock_self, *args, **kwargs):
939 self = _mock_self
940 self.called = True
941 self.call_count += 1
Michael Foord345266a2012-03-14 12:24:34 -0700942 _new_name = self._mock_new_name
943 _new_parent = self._mock_new_parent
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100944
945 _call = _Call((args, kwargs), two=True)
946 self.call_args = _call
947 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700948 self.mock_calls.append(_Call(('', args, kwargs)))
949
950 seen = set()
951 skip_next_dot = _new_name == '()'
952 do_method_calls = self._mock_parent is not None
953 name = self._mock_name
954 while _new_parent is not None:
955 this_mock_call = _Call((_new_name, args, kwargs))
956 if _new_parent._mock_new_name:
957 dot = '.'
958 if skip_next_dot:
959 dot = ''
960
961 skip_next_dot = False
962 if _new_parent._mock_new_name == '()':
963 skip_next_dot = True
964
965 _new_name = _new_parent._mock_new_name + dot + _new_name
966
967 if do_method_calls:
968 if _new_name == name:
969 this_method_call = this_mock_call
970 else:
971 this_method_call = _Call((name, args, kwargs))
972 _new_parent.method_calls.append(this_method_call)
973
974 do_method_calls = _new_parent._mock_parent is not None
975 if do_method_calls:
976 name = _new_parent._mock_name + '.' + name
977
978 _new_parent.mock_calls.append(this_mock_call)
979 _new_parent = _new_parent._mock_new_parent
980
981 # use ids here so as not to call __hash__ on the mocks
982 _new_parent_id = id(_new_parent)
983 if _new_parent_id in seen:
984 break
985 seen.add(_new_parent_id)
986
987 ret_val = DEFAULT
988 effect = self.side_effect
989 if effect is not None:
990 if _is_exception(effect):
991 raise effect
992
993 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +0100994 result = next(effect)
995 if _is_exception(result):
996 raise result
Andrew Svetlov8b2cd752013-04-07 16:42:24 +0300997 if result is DEFAULT:
998 result = self.return_value
Michael Foord2cd48732012-04-21 15:52:11 +0100999 return result
Michael Foord345266a2012-03-14 12:24:34 -07001000
1001 ret_val = effect(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001002
1003 if (self._mock_wraps is not None and
1004 self._mock_return_value is DEFAULT):
1005 return self._mock_wraps(*args, **kwargs)
1006 if ret_val is DEFAULT:
1007 ret_val = self.return_value
1008 return ret_val
1009
1010
1011
1012class Mock(CallableMixin, NonCallableMock):
1013 """
1014 Create a new `Mock` object. `Mock` takes several optional arguments
1015 that specify the behaviour of the Mock object:
1016
1017 * `spec`: This can be either a list of strings or an existing object (a
1018 class or instance) that acts as the specification for the mock object. If
1019 you pass in an object then a list of strings is formed by calling dir on
1020 the object (excluding unsupported magic attributes and methods). Accessing
1021 any attribute not in this list will raise an `AttributeError`.
1022
1023 If `spec` is an object (rather than a list of strings) then
1024 `mock.__class__` returns the class of the spec object. This allows mocks
1025 to pass `isinstance` tests.
1026
1027 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1028 or get an attribute on the mock that isn't on the object passed as
1029 `spec_set` will raise an `AttributeError`.
1030
1031 * `side_effect`: A function to be called whenever the Mock is called. See
1032 the `side_effect` attribute. Useful for raising exceptions or
1033 dynamically changing return values. The function is called with the same
1034 arguments as the mock, and unless it returns `DEFAULT`, the return
1035 value of this function is used as the return value.
1036
Michael Foord2cd48732012-04-21 15:52:11 +01001037 If `side_effect` is an iterable then each call to the mock will return
1038 the next value from the iterable. If any of the members of the iterable
1039 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001040
Michael Foord345266a2012-03-14 12:24:34 -07001041 * `return_value`: The value returned when the mock is called. By default
1042 this is a new Mock (created on first access). See the
1043 `return_value` attribute.
1044
Michael Foord0682a0c2012-04-13 20:51:20 +01001045 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1046 calling the Mock will pass the call through to the wrapped object
1047 (returning the real result). Attribute access on the mock will return a
1048 Mock object that wraps the corresponding attribute of the wrapped object
1049 (so attempting to access an attribute that doesn't exist will raise an
1050 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001051
1052 If the mock has an explicit `return_value` set then calls are not passed
1053 to the wrapped object and the `return_value` is returned instead.
1054
1055 * `name`: If the mock has a name then it will be used in the repr of the
1056 mock. This can be useful for debugging. The name is propagated to child
1057 mocks.
1058
1059 Mocks can also be called with arbitrary keyword arguments. These will be
1060 used to set attributes on the mock after it is created.
1061 """
1062
1063
1064
1065def _dot_lookup(thing, comp, import_path):
1066 try:
1067 return getattr(thing, comp)
1068 except AttributeError:
1069 __import__(import_path)
1070 return getattr(thing, comp)
1071
1072
1073def _importer(target):
1074 components = target.split('.')
1075 import_path = components.pop(0)
1076 thing = __import__(import_path)
1077
1078 for comp in components:
1079 import_path += ".%s" % comp
1080 thing = _dot_lookup(thing, comp, import_path)
1081 return thing
1082
1083
1084def _is_started(patcher):
1085 # XXXX horrible
1086 return hasattr(patcher, 'is_local')
1087
1088
1089class _patch(object):
1090
1091 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001092 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001093
1094 def __init__(
1095 self, getter, attribute, new, spec, create,
1096 spec_set, autospec, new_callable, kwargs
1097 ):
1098 if new_callable is not None:
1099 if new is not DEFAULT:
1100 raise ValueError(
1101 "Cannot use 'new' and 'new_callable' together"
1102 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001103 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001104 raise ValueError(
1105 "Cannot use 'autospec' and 'new_callable' together"
1106 )
1107
1108 self.getter = getter
1109 self.attribute = attribute
1110 self.new = new
1111 self.new_callable = new_callable
1112 self.spec = spec
1113 self.create = create
1114 self.has_local = False
1115 self.spec_set = spec_set
1116 self.autospec = autospec
1117 self.kwargs = kwargs
1118 self.additional_patchers = []
1119
1120
1121 def copy(self):
1122 patcher = _patch(
1123 self.getter, self.attribute, self.new, self.spec,
1124 self.create, self.spec_set,
1125 self.autospec, self.new_callable, self.kwargs
1126 )
1127 patcher.attribute_name = self.attribute_name
1128 patcher.additional_patchers = [
1129 p.copy() for p in self.additional_patchers
1130 ]
1131 return patcher
1132
1133
1134 def __call__(self, func):
1135 if isinstance(func, type):
1136 return self.decorate_class(func)
1137 return self.decorate_callable(func)
1138
1139
1140 def decorate_class(self, klass):
1141 for attr in dir(klass):
1142 if not attr.startswith(patch.TEST_PREFIX):
1143 continue
1144
1145 attr_value = getattr(klass, attr)
1146 if not hasattr(attr_value, "__call__"):
1147 continue
1148
1149 patcher = self.copy()
1150 setattr(klass, attr, patcher(attr_value))
1151 return klass
1152
1153
1154 def decorate_callable(self, func):
1155 if hasattr(func, 'patchings'):
1156 func.patchings.append(self)
1157 return func
1158
1159 @wraps(func)
1160 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001161 extra_args = []
1162 entered_patchers = []
1163
Michael Foord50a8c0e2012-03-25 18:57:58 +01001164 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001165 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001166 for patching in patched.patchings:
1167 arg = patching.__enter__()
1168 entered_patchers.append(patching)
1169 if patching.attribute_name is not None:
1170 keywargs.update(arg)
1171 elif patching.new is DEFAULT:
1172 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001173
Michael Foordd7c65e22012-03-14 14:56:54 -07001174 args += tuple(extra_args)
1175 return func(*args, **keywargs)
1176 except:
1177 if (patching not in entered_patchers and
1178 _is_started(patching)):
1179 # the patcher may have been started, but an exception
1180 # raised whilst entering one of its additional_patchers
1181 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001182 # Pass the exception to __exit__
1183 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001184 # re-raise the exception
1185 raise
Michael Foord345266a2012-03-14 12:24:34 -07001186 finally:
1187 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001188 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001189
1190 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001191 return patched
1192
1193
1194 def get_original(self):
1195 target = self.getter()
1196 name = self.attribute
1197
1198 original = DEFAULT
1199 local = False
1200
1201 try:
1202 original = target.__dict__[name]
1203 except (AttributeError, KeyError):
1204 original = getattr(target, name, DEFAULT)
1205 else:
1206 local = True
1207
Michael Foordfddcfa22014-04-14 16:25:20 -04001208 if name in _builtins and isinstance(target, ModuleType):
1209 self.create = True
1210
Michael Foord345266a2012-03-14 12:24:34 -07001211 if not self.create and original is DEFAULT:
1212 raise AttributeError(
1213 "%s does not have the attribute %r" % (target, name)
1214 )
1215 return original, local
1216
1217
1218 def __enter__(self):
1219 """Perform the patch."""
1220 new, spec, spec_set = self.new, self.spec, self.spec_set
1221 autospec, kwargs = self.autospec, self.kwargs
1222 new_callable = self.new_callable
1223 self.target = self.getter()
1224
Michael Foord50a8c0e2012-03-25 18:57:58 +01001225 # normalise False to None
1226 if spec is False:
1227 spec = None
1228 if spec_set is False:
1229 spec_set = None
1230 if autospec is False:
1231 autospec = None
1232
1233 if spec is not None and autospec is not None:
1234 raise TypeError("Can't specify spec and autospec")
1235 if ((spec is not None or autospec is not None) and
1236 spec_set not in (True, None)):
1237 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1238
Michael Foord345266a2012-03-14 12:24:34 -07001239 original, local = self.get_original()
1240
Michael Foord50a8c0e2012-03-25 18:57:58 +01001241 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001242 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001243 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001244 # set spec to the object we are replacing
1245 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001246 if spec_set is True:
1247 spec_set = original
1248 spec = None
1249 elif spec is not None:
1250 if spec_set is True:
1251 spec_set = spec
1252 spec = None
1253 elif spec_set is True:
1254 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001255
Michael Foord50a8c0e2012-03-25 18:57:58 +01001256 if spec is not None or spec_set is not None:
1257 if original is DEFAULT:
1258 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001259 if isinstance(original, type):
1260 # If we're patching out a class and there is a spec
1261 inherit = True
1262
1263 Klass = MagicMock
1264 _kwargs = {}
1265 if new_callable is not None:
1266 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001267 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001268 this_spec = spec
1269 if spec_set is not None:
1270 this_spec = spec_set
1271 if _is_list(this_spec):
1272 not_callable = '__call__' not in this_spec
1273 else:
1274 not_callable = not callable(this_spec)
1275 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001276 Klass = NonCallableMagicMock
1277
1278 if spec is not None:
1279 _kwargs['spec'] = spec
1280 if spec_set is not None:
1281 _kwargs['spec_set'] = spec_set
1282
1283 # add a name to mocks
1284 if (isinstance(Klass, type) and
1285 issubclass(Klass, NonCallableMock) and self.attribute):
1286 _kwargs['name'] = self.attribute
1287
1288 _kwargs.update(kwargs)
1289 new = Klass(**_kwargs)
1290
1291 if inherit and _is_instance_mock(new):
1292 # we can only tell if the instance should be callable if the
1293 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001294 this_spec = spec
1295 if spec_set is not None:
1296 this_spec = spec_set
1297 if (not _is_list(this_spec) and not
1298 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001299 Klass = NonCallableMagicMock
1300
1301 _kwargs.pop('name')
1302 new.return_value = Klass(_new_parent=new, _new_name='()',
1303 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001304 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001305 # spec is ignored, new *must* be default, spec_set is treated
1306 # as a boolean. Should we check spec is not None and that spec_set
1307 # is a bool?
1308 if new is not DEFAULT:
1309 raise TypeError(
1310 "autospec creates the mock for you. Can't specify "
1311 "autospec and new."
1312 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001313 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001314 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001315 spec_set = bool(spec_set)
1316 if autospec is True:
1317 autospec = original
1318
1319 new = create_autospec(autospec, spec_set=spec_set,
1320 _name=self.attribute, **kwargs)
1321 elif kwargs:
1322 # can't set keyword args when we aren't creating the mock
1323 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1324 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1325
1326 new_attr = new
1327
1328 self.temp_original = original
1329 self.is_local = local
1330 setattr(self.target, self.attribute, new_attr)
1331 if self.attribute_name is not None:
1332 extra_args = {}
1333 if self.new is DEFAULT:
1334 extra_args[self.attribute_name] = new
1335 for patching in self.additional_patchers:
1336 arg = patching.__enter__()
1337 if patching.new is DEFAULT:
1338 extra_args.update(arg)
1339 return extra_args
1340
1341 return new
1342
1343
Michael Foord50a8c0e2012-03-25 18:57:58 +01001344 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001345 """Undo the patch."""
1346 if not _is_started(self):
1347 raise RuntimeError('stop called on unstarted patcher')
1348
1349 if self.is_local and self.temp_original is not DEFAULT:
1350 setattr(self.target, self.attribute, self.temp_original)
1351 else:
1352 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001353 if not self.create and (not hasattr(self.target, self.attribute) or
1354 self.attribute in ('__doc__', '__module__',
1355 '__defaults__', '__annotations__',
1356 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001357 # needed for proxy objects like django settings
1358 setattr(self.target, self.attribute, self.temp_original)
1359
1360 del self.temp_original
1361 del self.is_local
1362 del self.target
1363 for patcher in reversed(self.additional_patchers):
1364 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001365 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001366
Michael Foordf7c41582012-06-10 20:36:32 +01001367
1368 def start(self):
1369 """Activate a patch, returning any created mock."""
1370 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001371 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001372 return result
1373
1374
1375 def stop(self):
1376 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001377 try:
1378 self._active_patches.remove(self)
1379 except ValueError:
1380 # If the patch hasn't been started this will fail
1381 pass
1382
Michael Foordf7c41582012-06-10 20:36:32 +01001383 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001384
1385
1386
1387def _get_target(target):
1388 try:
1389 target, attribute = target.rsplit('.', 1)
1390 except (TypeError, ValueError):
1391 raise TypeError("Need a valid target to patch. You supplied: %r" %
1392 (target,))
1393 getter = lambda: _importer(target)
1394 return getter, attribute
1395
1396
1397def _patch_object(
1398 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001399 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001400 new_callable=None, **kwargs
1401 ):
1402 """
Michael Foord345266a2012-03-14 12:24:34 -07001403 patch the named member (`attribute`) on an object (`target`) with a mock
1404 object.
1405
1406 `patch.object` can be used as a decorator, class decorator or a context
1407 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1408 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1409 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1410 the mock object it creates.
1411
1412 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1413 for choosing which methods to wrap.
1414 """
1415 getter = lambda: target
1416 return _patch(
1417 getter, attribute, new, spec, create,
1418 spec_set, autospec, new_callable, kwargs
1419 )
1420
1421
Michael Foord50a8c0e2012-03-25 18:57:58 +01001422def _patch_multiple(target, spec=None, create=False, spec_set=None,
1423 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001424 """Perform multiple patches in a single call. It takes the object to be
1425 patched (either as an object or a string to fetch the object by importing)
1426 and keyword arguments for the patches::
1427
1428 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1429 ...
1430
1431 Use `DEFAULT` as the value if you want `patch.multiple` to create
1432 mocks for you. In this case the created mocks are passed into a decorated
1433 function by keyword, and a dictionary is returned when `patch.multiple` is
1434 used as a context manager.
1435
1436 `patch.multiple` can be used as a decorator, class decorator or a context
1437 manager. The arguments `spec`, `spec_set`, `create`,
1438 `autospec` and `new_callable` have the same meaning as for `patch`. These
1439 arguments will be applied to *all* patches done by `patch.multiple`.
1440
1441 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1442 for choosing which methods to wrap.
1443 """
1444 if type(target) is str:
1445 getter = lambda: _importer(target)
1446 else:
1447 getter = lambda: target
1448
1449 if not kwargs:
1450 raise ValueError(
1451 'Must supply at least one keyword argument with patch.multiple'
1452 )
1453 # need to wrap in a list for python 3, where items is a view
1454 items = list(kwargs.items())
1455 attribute, new = items[0]
1456 patcher = _patch(
1457 getter, attribute, new, spec, create, spec_set,
1458 autospec, new_callable, {}
1459 )
1460 patcher.attribute_name = attribute
1461 for attribute, new in items[1:]:
1462 this_patcher = _patch(
1463 getter, attribute, new, spec, create, spec_set,
1464 autospec, new_callable, {}
1465 )
1466 this_patcher.attribute_name = attribute
1467 patcher.additional_patchers.append(this_patcher)
1468 return patcher
1469
1470
1471def patch(
1472 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001473 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001474 ):
1475 """
1476 `patch` acts as a function decorator, class decorator or a context
1477 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001478 is patched with a `new` object. When the function/with statement exits
1479 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001480
Michael Foord54b3db82012-03-28 15:08:08 +01001481 If `new` is omitted, then the target is replaced with a
1482 `MagicMock`. If `patch` is used as a decorator and `new` is
1483 omitted, the created mock is passed in as an extra argument to the
1484 decorated function. If `patch` is used as a context manager the created
1485 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001486
Michael Foord54b3db82012-03-28 15:08:08 +01001487 `target` should be a string in the form `'package.module.ClassName'`. The
1488 `target` is imported and the specified object replaced with the `new`
1489 object, so the `target` must be importable from the environment you are
1490 calling `patch` from. The target is imported when the decorated function
1491 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001492
1493 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1494 if patch is creating one for you.
1495
1496 In addition you can pass `spec=True` or `spec_set=True`, which causes
1497 patch to pass in the object being mocked as the spec/spec_set object.
1498
1499 `new_callable` allows you to specify a different class, or callable object,
1500 that will be called to create the `new` object. By default `MagicMock` is
1501 used.
1502
1503 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001504 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001505 All attributes of the mock will also have the spec of the corresponding
1506 attribute of the object being replaced. Methods and functions being
1507 mocked will have their arguments checked and will raise a `TypeError` if
1508 they are called with the wrong signature. For mocks replacing a class,
1509 their return value (the 'instance') will have the same spec as the class.
1510
1511 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1512 arbitrary object as the spec instead of the one being replaced.
1513
1514 By default `patch` will fail to replace attributes that don't exist. If
1515 you pass in `create=True`, and the attribute doesn't exist, patch will
1516 create the attribute for you when the patched function is called, and
1517 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001518 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001519 default because it can be dangerous. With it switched on you can write
1520 passing tests against APIs that don't actually exist!
1521
1522 Patch can be used as a `TestCase` class decorator. It works by
1523 decorating each test method in the class. This reduces the boilerplate
1524 code when your test methods share a common patchings set. `patch` finds
1525 tests by looking for method names that start with `patch.TEST_PREFIX`.
1526 By default this is `test`, which matches the way `unittest` finds tests.
1527 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1528
1529 Patch can be used as a context manager, with the with statement. Here the
1530 patching applies to the indented block after the with statement. If you
1531 use "as" then the patched object will be bound to the name after the
1532 "as"; very useful if `patch` is creating a mock object for you.
1533
1534 `patch` takes arbitrary keyword arguments. These will be passed to
1535 the `Mock` (or `new_callable`) on construction.
1536
1537 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1538 available for alternate use-cases.
1539 """
1540 getter, attribute = _get_target(target)
1541 return _patch(
1542 getter, attribute, new, spec, create,
1543 spec_set, autospec, new_callable, kwargs
1544 )
1545
1546
1547class _patch_dict(object):
1548 """
1549 Patch a dictionary, or dictionary like object, and restore the dictionary
1550 to its original state after the test.
1551
1552 `in_dict` can be a dictionary or a mapping like container. If it is a
1553 mapping then it must at least support getting, setting and deleting items
1554 plus iterating over keys.
1555
1556 `in_dict` can also be a string specifying the name of the dictionary, which
1557 will then be fetched by importing it.
1558
1559 `values` can be a dictionary of values to set in the dictionary. `values`
1560 can also be an iterable of `(key, value)` pairs.
1561
1562 If `clear` is True then the dictionary will be cleared before the new
1563 values are set.
1564
1565 `patch.dict` can also be called with arbitrary keyword arguments to set
1566 values in the dictionary::
1567
1568 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1569 ...
1570
1571 `patch.dict` can be used as a context manager, decorator or class
1572 decorator. When used as a class decorator `patch.dict` honours
1573 `patch.TEST_PREFIX` for choosing which methods to wrap.
1574 """
1575
1576 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1577 if isinstance(in_dict, str):
1578 in_dict = _importer(in_dict)
1579 self.in_dict = in_dict
1580 # support any argument supported by dict(...) constructor
1581 self.values = dict(values)
1582 self.values.update(kwargs)
1583 self.clear = clear
1584 self._original = None
1585
1586
1587 def __call__(self, f):
1588 if isinstance(f, type):
1589 return self.decorate_class(f)
1590 @wraps(f)
1591 def _inner(*args, **kw):
1592 self._patch_dict()
1593 try:
1594 return f(*args, **kw)
1595 finally:
1596 self._unpatch_dict()
1597
1598 return _inner
1599
1600
1601 def decorate_class(self, klass):
1602 for attr in dir(klass):
1603 attr_value = getattr(klass, attr)
1604 if (attr.startswith(patch.TEST_PREFIX) and
1605 hasattr(attr_value, "__call__")):
1606 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1607 decorated = decorator(attr_value)
1608 setattr(klass, attr, decorated)
1609 return klass
1610
1611
1612 def __enter__(self):
1613 """Patch the dict."""
1614 self._patch_dict()
1615
1616
1617 def _patch_dict(self):
1618 values = self.values
1619 in_dict = self.in_dict
1620 clear = self.clear
1621
1622 try:
1623 original = in_dict.copy()
1624 except AttributeError:
1625 # dict like object with no copy method
1626 # must support iteration over keys
1627 original = {}
1628 for key in in_dict:
1629 original[key] = in_dict[key]
1630 self._original = original
1631
1632 if clear:
1633 _clear_dict(in_dict)
1634
1635 try:
1636 in_dict.update(values)
1637 except AttributeError:
1638 # dict like object with no update method
1639 for key in values:
1640 in_dict[key] = values[key]
1641
1642
1643 def _unpatch_dict(self):
1644 in_dict = self.in_dict
1645 original = self._original
1646
1647 _clear_dict(in_dict)
1648
1649 try:
1650 in_dict.update(original)
1651 except AttributeError:
1652 for key in original:
1653 in_dict[key] = original[key]
1654
1655
1656 def __exit__(self, *args):
1657 """Unpatch the dict."""
1658 self._unpatch_dict()
1659 return False
1660
1661 start = __enter__
1662 stop = __exit__
1663
1664
1665def _clear_dict(in_dict):
1666 try:
1667 in_dict.clear()
1668 except AttributeError:
1669 keys = list(in_dict)
1670 for key in keys:
1671 del in_dict[key]
1672
1673
Michael Foordf7c41582012-06-10 20:36:32 +01001674def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001675 """Stop all active patches. LIFO to unroll nested patches."""
1676 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001677 patch.stop()
1678
1679
Michael Foord345266a2012-03-14 12:24:34 -07001680patch.object = _patch_object
1681patch.dict = _patch_dict
1682patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001683patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001684patch.TEST_PREFIX = 'test'
1685
1686magic_methods = (
1687 "lt le gt ge eq ne "
1688 "getitem setitem delitem "
1689 "len contains iter "
1690 "hash str sizeof "
1691 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001692 # we added divmod and rdivmod here instead of numerics
1693 # because there is no idivmod
1694 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001695 "complex int float index "
1696 "trunc floor ceil "
1697 "bool next "
1698)
1699
Michael Foordd2623d72014-04-14 11:23:48 -04001700numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001701 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001702)
Michael Foord345266a2012-03-14 12:24:34 -07001703inplace = ' '.join('i%s' % n for n in numerics.split())
1704right = ' '.join('r%s' % n for n in numerics.split())
1705
1706# not including __prepare__, __instancecheck__, __subclasscheck__
1707# (as they are metaclass methods)
1708# __del__ is not supported at all as it causes problems if it exists
1709
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001710_non_defaults = {
1711 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1712 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1713 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1714 '__repr__', '__dir__', '__subclasses__', '__format__',
Serhiy Storchaka5943ea72016-06-19 18:30:43 +03001715 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001716}
Michael Foord345266a2012-03-14 12:24:34 -07001717
1718
1719def _get_method(name, func):
1720 "Turns a callable object (like a mock) into a real function"
1721 def method(self, *args, **kw):
1722 return func(self, *args, **kw)
1723 method.__name__ = name
1724 return method
1725
1726
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001727_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001728 '__%s__' % method for method in
1729 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001730}
Michael Foord345266a2012-03-14 12:24:34 -07001731
1732_all_magics = _magics | _non_defaults
1733
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001734_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001735 '__getattr__', '__setattr__',
1736 '__init__', '__new__', '__prepare__'
1737 '__instancecheck__', '__subclasscheck__',
1738 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001739}
Michael Foord345266a2012-03-14 12:24:34 -07001740
1741_calculate_return_value = {
1742 '__hash__': lambda self: object.__hash__(self),
1743 '__str__': lambda self: object.__str__(self),
1744 '__sizeof__': lambda self: object.__sizeof__(self),
1745}
1746
1747_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001748 '__lt__': NotImplemented,
1749 '__gt__': NotImplemented,
1750 '__le__': NotImplemented,
1751 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001752 '__int__': 1,
1753 '__contains__': False,
1754 '__len__': 0,
1755 '__exit__': False,
1756 '__complex__': 1j,
1757 '__float__': 1.0,
1758 '__bool__': True,
1759 '__index__': 1,
1760}
1761
1762
1763def _get_eq(self):
1764 def __eq__(other):
1765 ret_val = self.__eq__._mock_return_value
1766 if ret_val is not DEFAULT:
1767 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001768 if self is other:
1769 return True
1770 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001771 return __eq__
1772
1773def _get_ne(self):
1774 def __ne__(other):
1775 if self.__ne__._mock_return_value is not DEFAULT:
1776 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001777 if self is other:
1778 return False
1779 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001780 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 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01001964 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07001965 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07001966 args = ()
1967 kwargs = {}
1968 _len = len(value)
1969 if _len == 3:
1970 name, args, kwargs = value
1971 elif _len == 2:
1972 first, second = value
1973 if isinstance(first, str):
1974 name = first
1975 if isinstance(second, tuple):
1976 args = second
1977 else:
1978 kwargs = second
1979 else:
1980 args, kwargs = first, second
1981 elif _len == 1:
1982 value, = value
1983 if isinstance(value, str):
1984 name = value
1985 elif isinstance(value, tuple):
1986 args = value
1987 else:
1988 kwargs = value
1989
1990 if two:
1991 return tuple.__new__(cls, (args, kwargs))
1992
1993 return tuple.__new__(cls, (name, args, kwargs))
1994
1995
1996 def __init__(self, value=(), name=None, parent=None, two=False,
1997 from_kall=True):
1998 self.name = name
1999 self.parent = parent
2000 self.from_kall = from_kall
2001
2002
2003 def __eq__(self, other):
2004 if other is ANY:
2005 return True
2006 try:
2007 len_other = len(other)
2008 except TypeError:
2009 return False
2010
2011 self_name = ''
2012 if len(self) == 2:
2013 self_args, self_kwargs = self
2014 else:
2015 self_name, self_args, self_kwargs = self
2016
2017 other_name = ''
2018 if len_other == 0:
2019 other_args, other_kwargs = (), {}
2020 elif len_other == 3:
2021 other_name, other_args, other_kwargs = other
2022 elif len_other == 1:
2023 value, = other
2024 if isinstance(value, tuple):
2025 other_args = value
2026 other_kwargs = {}
2027 elif isinstance(value, str):
2028 other_name = value
2029 other_args, other_kwargs = (), {}
2030 else:
2031 other_args = ()
2032 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002033 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002034 # could be (name, args) or (name, kwargs) or (args, kwargs)
2035 first, second = other
2036 if isinstance(first, str):
2037 other_name = first
2038 if isinstance(second, tuple):
2039 other_args, other_kwargs = second, {}
2040 else:
2041 other_args, other_kwargs = (), second
2042 else:
2043 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002044 else:
2045 return False
Michael Foord345266a2012-03-14 12:24:34 -07002046
2047 if self_name and other_name != self_name:
2048 return False
2049
2050 # this order is important for ANY to work!
2051 return (other_args, other_kwargs) == (self_args, self_kwargs)
2052
2053
Berker Peksagce913872016-03-28 00:30:02 +03002054 __ne__ = object.__ne__
2055
2056
Michael Foord345266a2012-03-14 12:24:34 -07002057 def __call__(self, *args, **kwargs):
2058 if self.name is None:
2059 return _Call(('', args, kwargs), name='()')
2060
2061 name = self.name + '()'
2062 return _Call((self.name, args, kwargs), name=name, parent=self)
2063
2064
2065 def __getattr__(self, attr):
2066 if self.name is None:
2067 return _Call(name=attr, from_kall=False)
2068 name = '%s.%s' % (self.name, attr)
2069 return _Call(name=name, parent=self, from_kall=False)
2070
2071
Kushal Dasa37b9582014-09-16 18:33:37 +05302072 def count(self, *args, **kwargs):
2073 return self.__getattr__('count')(*args, **kwargs)
2074
2075 def index(self, *args, **kwargs):
2076 return self.__getattr__('index')(*args, **kwargs)
2077
Michael Foord345266a2012-03-14 12:24:34 -07002078 def __repr__(self):
2079 if not self.from_kall:
2080 name = self.name or 'call'
2081 if name.startswith('()'):
2082 name = 'call%s' % name
2083 return name
2084
2085 if len(self) == 2:
2086 name = 'call'
2087 args, kwargs = self
2088 else:
2089 name, args, kwargs = self
2090 if not name:
2091 name = 'call'
2092 elif not name.startswith('()'):
2093 name = 'call.%s' % name
2094 else:
2095 name = 'call%s' % name
2096 return _format_call_signature(name, args, kwargs)
2097
2098
2099 def call_list(self):
2100 """For a call object that represents multiple calls, `call_list`
2101 returns a list of all the intermediate calls as well as the
2102 final call."""
2103 vals = []
2104 thing = self
2105 while thing is not None:
2106 if thing.from_kall:
2107 vals.append(thing)
2108 thing = thing.parent
2109 return _CallList(reversed(vals))
2110
2111
2112call = _Call(from_kall=False)
2113
2114
2115
2116def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2117 _name=None, **kwargs):
2118 """Create a mock object using another object as a spec. Attributes on the
2119 mock will use the corresponding attribute on the `spec` object as their
2120 spec.
2121
2122 Functions or methods being mocked will have their arguments checked
2123 to check that they are called with the correct signature.
2124
2125 If `spec_set` is True then attempting to set attributes that don't exist
2126 on the spec object will raise an `AttributeError`.
2127
2128 If a class is used as a spec then the return value of the mock (the
2129 instance of the class) will have the same spec. You can use a class as the
2130 spec for an instance object by passing `instance=True`. The returned mock
2131 will only be callable if instances of the mock are callable.
2132
2133 `create_autospec` also takes arbitrary keyword arguments that are passed to
2134 the constructor of the created mock."""
2135 if _is_list(spec):
2136 # can't pass a list instance to the mock constructor as it will be
2137 # interpreted as a list of strings
2138 spec = type(spec)
2139
2140 is_type = isinstance(spec, type)
2141
2142 _kwargs = {'spec': spec}
2143 if spec_set:
2144 _kwargs = {'spec_set': spec}
2145 elif spec is None:
2146 # None we mock with a normal mock without a spec
2147 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002148 if _kwargs and instance:
2149 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002150
2151 _kwargs.update(kwargs)
2152
2153 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002154 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002155 # descriptors don't have a spec
2156 # because we don't know what type they return
2157 _kwargs = {}
2158 elif not _callable(spec):
2159 Klass = NonCallableMagicMock
2160 elif is_type and instance and not _instance_callable(spec):
2161 Klass = NonCallableMagicMock
2162
Kushal Das484f8a82014-04-16 01:05:50 +05302163 _name = _kwargs.pop('name', _name)
2164
Michael Foord345266a2012-03-14 12:24:34 -07002165 _new_name = _name
2166 if _parent is None:
2167 # for a top level object no _new_name should be set
2168 _new_name = ''
2169
2170 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2171 name=_name, **_kwargs)
2172
2173 if isinstance(spec, FunctionTypes):
2174 # should only happen at the top level because we don't
2175 # recurse for functions
2176 mock = _set_signature(mock, spec)
2177 else:
2178 _check_signature(spec, mock, is_type, instance)
2179
2180 if _parent is not None and not instance:
2181 _parent._mock_children[_name] = mock
2182
2183 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002184 mock.return_value = create_autospec(spec, spec_set, instance=True,
2185 _name='()', _parent=mock)
2186
2187 for entry in dir(spec):
2188 if _is_magic(entry):
2189 # MagicMock already does the useful magic methods for us
2190 continue
2191
Michael Foord345266a2012-03-14 12:24:34 -07002192 # XXXX do we need a better way of getting attributes without
2193 # triggering code execution (?) Probably not - we need the actual
2194 # object to mock it so we would rather trigger a property than mock
2195 # the property descriptor. Likewise we want to mock out dynamically
2196 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002197 # XXXX what about attributes that raise exceptions other than
2198 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002199 # we could be resilient against it, or catch and propagate the
2200 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002201 try:
2202 original = getattr(spec, entry)
2203 except AttributeError:
2204 continue
Michael Foord345266a2012-03-14 12:24:34 -07002205
2206 kwargs = {'spec': original}
2207 if spec_set:
2208 kwargs = {'spec_set': original}
2209
2210 if not isinstance(original, FunctionTypes):
2211 new = _SpecState(original, spec_set, mock, entry, instance)
2212 mock._mock_children[entry] = new
2213 else:
2214 parent = mock
2215 if isinstance(spec, FunctionTypes):
2216 parent = mock.mock
2217
Michael Foord345266a2012-03-14 12:24:34 -07002218 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002219 kwargs['_eat_self'] = skipfirst
2220 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2221 _new_parent=parent,
2222 **kwargs)
2223 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002224 _check_signature(original, new, skipfirst=skipfirst)
2225
2226 # so functions created with _set_signature become instance attributes,
2227 # *plus* their underlying mock exists in _mock_children of the parent
2228 # mock. Adding to _mock_children may be unnecessary where we are also
2229 # setting as an instance attribute?
2230 if isinstance(new, FunctionTypes):
2231 setattr(mock, entry, new)
2232
2233 return mock
2234
2235
2236def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002237 """
2238 Return whether we should skip the first argument on spec's `entry`
2239 attribute.
2240 """
Michael Foord345266a2012-03-14 12:24:34 -07002241 if not isinstance(spec, type):
2242 if entry in getattr(spec, '__dict__', {}):
2243 # instance attribute - shouldn't skip
2244 return False
Michael Foord345266a2012-03-14 12:24:34 -07002245 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002246
2247 for klass in spec.__mro__:
2248 result = klass.__dict__.get(entry, DEFAULT)
2249 if result is DEFAULT:
2250 continue
2251 if isinstance(result, (staticmethod, classmethod)):
2252 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002253 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2254 # Normal method => skip if looked up on type
2255 # (if looked up on instance, self is already skipped)
2256 return is_type
2257 else:
2258 return False
Michael Foord345266a2012-03-14 12:24:34 -07002259
2260 # shouldn't get here unless function is a dynamically provided attribute
2261 # XXXX untested behaviour
2262 return is_type
2263
2264
2265def _get_class(obj):
2266 try:
2267 return obj.__class__
2268 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002269 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002270 return type(obj)
2271
2272
2273class _SpecState(object):
2274
2275 def __init__(self, spec, spec_set=False, parent=None,
2276 name=None, ids=None, instance=False):
2277 self.spec = spec
2278 self.ids = ids
2279 self.spec_set = spec_set
2280 self.parent = parent
2281 self.instance = instance
2282 self.name = name
2283
2284
2285FunctionTypes = (
2286 # python function
2287 type(create_autospec),
2288 # instance method
2289 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002290)
2291
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002292MethodWrapperTypes = (
2293 type(ANY.__eq__.__get__),
2294)
2295
Michael Foord345266a2012-03-14 12:24:34 -07002296
Michael Foorda74561a2012-03-25 19:03:13 +01002297file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002298
Michael Foord04cbe0c2013-03-19 17:22:51 -07002299def _iterate_read_data(read_data):
2300 # Helper for mock_open:
2301 # Retrieve lines from read_data via a generator so that separate calls to
2302 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002303 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2304 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002305
Berker Peksag86b34da2015-08-06 13:15:51 +03002306 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002307 # If the last line ended in a newline, the list comprehension will have an
2308 # extra entry that's just a newline. Remove this.
2309 data_as_list = data_as_list[:-1]
2310 else:
2311 # If there wasn't an extra newline by itself, then the file being
2312 # emulated doesn't have a newline to end the last line remove the
2313 # newline that our naive format() added
2314 data_as_list[-1] = data_as_list[-1][:-1]
2315
2316 for line in data_as_list:
2317 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002318
Robert Collins5329aaa2015-07-17 20:08:45 +12002319
Michael Foord0dccf652012-03-25 19:11:50 +01002320def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002321 """
2322 A helper function to create a mock to replace the use of `open`. It works
2323 for `open` called directly or used as a context manager.
2324
2325 The `mock` argument is the mock object to configure. If `None` (the
2326 default) then a `MagicMock` will be created for you, with the API limited
2327 to methods or attributes available on standard file handles.
2328
Michael Foord04cbe0c2013-03-19 17:22:51 -07002329 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2330 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002331 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002332 def _readlines_side_effect(*args, **kwargs):
2333 if handle.readlines.return_value is not None:
2334 return handle.readlines.return_value
2335 return list(_state[0])
2336
2337 def _read_side_effect(*args, **kwargs):
2338 if handle.read.return_value is not None:
2339 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002340 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002341
2342 def _readline_side_effect():
2343 if handle.readline.return_value is not None:
2344 while True:
2345 yield handle.readline.return_value
2346 for line in _state[0]:
2347 yield line
Robert Collins9549a3e2016-05-16 15:22:01 +12002348 while True:
2349 yield type(read_data)()
Robert Collinsca647ef2015-07-24 03:48:20 +12002350
2351
Michael Foorda74561a2012-03-25 19:03:13 +01002352 global file_spec
2353 if file_spec is None:
2354 import _io
2355 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2356
Michael Foord345266a2012-03-14 12:24:34 -07002357 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002358 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002359
Robert Collinsca647ef2015-07-24 03:48:20 +12002360 handle = MagicMock(spec=file_spec)
2361 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002362
Robert Collinsca647ef2015-07-24 03:48:20 +12002363 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002364
Robert Collinsca647ef2015-07-24 03:48:20 +12002365 handle.write.return_value = None
2366 handle.read.return_value = None
2367 handle.readline.return_value = None
2368 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002369
Robert Collinsca647ef2015-07-24 03:48:20 +12002370 handle.read.side_effect = _read_side_effect
2371 _state[1] = _readline_side_effect()
2372 handle.readline.side_effect = _state[1]
2373 handle.readlines.side_effect = _readlines_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002374
Robert Collinsca647ef2015-07-24 03:48:20 +12002375 def reset_data(*args, **kwargs):
2376 _state[0] = _iterate_read_data(read_data)
2377 if handle.readline.side_effect == _state[1]:
2378 # Only reset the side effect if the user hasn't overridden it.
2379 _state[1] = _readline_side_effect()
2380 handle.readline.side_effect = _state[1]
2381 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002382
Robert Collinsca647ef2015-07-24 03:48:20 +12002383 mock.side_effect = reset_data
2384 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002385 return mock
2386
2387
2388class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002389 """
2390 A mock intended to be used as a property, or other descriptor, on a class.
2391 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2392 a return value when it is fetched.
2393
2394 Fetching a `PropertyMock` instance from an object calls the mock, with
2395 no args. Setting it calls the mock with the value being set.
2396 """
Michael Foordc2870622012-04-13 16:57:22 +01002397 def _get_child_mock(self, **kwargs):
2398 return MagicMock(**kwargs)
2399
Michael Foord345266a2012-03-14 12:24:34 -07002400 def __get__(self, obj, obj_type):
2401 return self()
2402 def __set__(self, obj, val):
2403 self(val)