blob: 5555774467d4cad9b90904ea703dcbf81295c1f8 [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
Antoine Pitrou5c64df72013-02-03 00:23:58 +010030from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070031
32
33BaseExceptions = (BaseException,)
34if 'java' in sys.platform:
35 # jython
36 import java
37 BaseExceptions = (BaseException, java.lang.Throwable)
38
39
40FILTER_DIR = True
41
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100042# Workaround for issue #12370
43# Without this, the __class__ properties wouldn't be set correctly
44_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070045
46def _is_instance_mock(obj):
47 # can't use isinstance on Mock objects because they override __class__
48 # The base class for all mocks is NonCallableMock
49 return issubclass(type(obj), NonCallableMock)
50
51
52def _is_exception(obj):
53 return (
54 isinstance(obj, BaseExceptions) or
55 isinstance(obj, type) and issubclass(obj, BaseExceptions)
56 )
57
58
59class _slotted(object):
60 __slots__ = ['a']
61
62
63DescriptorTypes = (
64 type(_slotted.a),
65 property,
66)
67
68
Antoine Pitrou5c64df72013-02-03 00:23:58 +010069def _get_signature_object(func, as_instance, eat_self):
70 """
71 Given an arbitrary, possibly callable object, try to create a suitable
72 signature object.
73 Return a (reduced func, signature) tuple, or None.
74 """
75 if isinstance(func, type) and not as_instance:
76 # If it's a type and should be modelled as a type, use __init__.
Michael Foord345266a2012-03-14 12:24:34 -070077 try:
78 func = func.__init__
79 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010080 return None
81 # Skip the `self` argument in __init__
82 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070083 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010084 # If we really want to model an instance of the passed type,
85 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070086 try:
87 func = func.__call__
88 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010089 return None
90 if eat_self:
91 sig_func = partial(func, None)
92 else:
93 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -070094 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010095 return func, inspect.signature(sig_func)
96 except ValueError:
97 # Certain callable types are not supported by inspect.signature()
98 return None
Michael Foord345266a2012-03-14 12:24:34 -070099
100
101def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100102 sig = _get_signature_object(func, instance, skipfirst)
103 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700104 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100105 func, sig = sig
106 def checksig(_mock_self, *args, **kwargs):
107 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700108 _copy_func_details(func, checksig)
109 type(mock)._mock_check_sig = checksig
110
111
112def _copy_func_details(func, funcopy):
113 funcopy.__name__ = func.__name__
114 funcopy.__doc__ = func.__doc__
Larry Hastings5c661892014-01-24 06:17:25 -0800115 try:
116 funcopy.__text_signature__ = func.__text_signature__
117 except AttributeError:
118 pass
Michael Foord345266a2012-03-14 12:24:34 -0700119 # we explicitly don't copy func.__dict__ into this copy as it would
120 # expose original attributes that should be mocked
Larry Hastings5c661892014-01-24 06:17:25 -0800121 try:
122 funcopy.__module__ = func.__module__
123 except AttributeError:
124 pass
125 try:
126 funcopy.__defaults__ = func.__defaults__
127 except AttributeError:
128 pass
129 try:
130 funcopy.__kwdefaults__ = func.__kwdefaults__
131 except AttributeError:
132 pass
Michael Foord345266a2012-03-14 12:24:34 -0700133
134
135def _callable(obj):
136 if isinstance(obj, type):
137 return True
138 if getattr(obj, '__call__', None) is not None:
139 return True
140 return False
141
142
143def _is_list(obj):
144 # checks for list or tuples
145 # XXXX badly named!
146 return type(obj) in (list, tuple)
147
148
149def _instance_callable(obj):
150 """Given an object, return True if the object is callable.
151 For classes, return True if instances would be callable."""
152 if not isinstance(obj, type):
153 # already an instance
154 return getattr(obj, '__call__', None) is not None
155
Michael Foorda74b3aa2012-03-14 14:40:22 -0700156 # *could* be broken by a class overriding __mro__ or __dict__ via
157 # a metaclass
158 for base in (obj,) + obj.__mro__:
159 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700160 return True
161 return False
162
163
164def _set_signature(mock, original, instance=False):
165 # creates a function with signature (*args, **kwargs) that delegates to a
166 # mock. It still does signature checking by calling a lambda with the same
167 # signature as the original.
168 if not _callable(original):
169 return
170
171 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100172 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700173 if result is None:
Michael Foord345266a2012-03-14 12:24:34 -0700174 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100175 func, sig = result
176 def checksig(*args, **kwargs):
177 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700178 _copy_func_details(func, checksig)
179
180 name = original.__name__
181 if not name.isidentifier():
182 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100183 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700184 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100185 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700186 return mock(*args, **kwargs)""" % name
187 exec (src, context)
188 funcopy = context[name]
189 _setup_func(funcopy, mock)
190 return funcopy
191
192
193def _setup_func(funcopy, mock):
194 funcopy.mock = mock
195
196 # can't use isinstance with mocks
197 if not _is_instance_mock(mock):
198 return
199
200 def assert_called_with(*args, **kwargs):
201 return mock.assert_called_with(*args, **kwargs)
202 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
232
233 mock._mock_delegate = funcopy
234
235
236def _is_magic(name):
237 return '__%s__' % name[2:-2] == name
238
239
240class _SentinelObject(object):
241 "A unique, named, sentinel object."
242 def __init__(self, name):
243 self.name = name
244
245 def __repr__(self):
246 return 'sentinel.%s' % self.name
247
248
249class _Sentinel(object):
250 """Access attributes to return a named object, usable as a sentinel."""
251 def __init__(self):
252 self._sentinels = {}
253
254 def __getattr__(self, name):
255 if name == '__bases__':
256 # Without this help(unittest.mock) raises an exception
257 raise AttributeError
258 return self._sentinels.setdefault(name, _SentinelObject(name))
259
260
261sentinel = _Sentinel()
262
263DEFAULT = sentinel.DEFAULT
264_missing = sentinel.MISSING
265_deleted = sentinel.DELETED
266
267
Michael Foord345266a2012-03-14 12:24:34 -0700268def _copy(value):
269 if type(value) in (dict, list, tuple, set):
270 return type(value)(value)
271 return value
272
273
274_allowed_names = set(
275 [
276 'return_value', '_mock_return_value', 'side_effect',
277 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
278 '_mock_name', '_mock_new_name'
279 ]
280)
281
282
283def _delegating_property(name):
284 _allowed_names.add(name)
285 _the_name = '_mock_' + name
286 def _get(self, name=name, _the_name=_the_name):
287 sig = self._mock_delegate
288 if sig is None:
289 return getattr(self, _the_name)
290 return getattr(sig, name)
291 def _set(self, value, name=name, _the_name=_the_name):
292 sig = self._mock_delegate
293 if sig is None:
294 self.__dict__[_the_name] = value
295 else:
296 setattr(sig, name, value)
297
298 return property(_get, _set)
299
300
301
302class _CallList(list):
303
304 def __contains__(self, value):
305 if not isinstance(value, list):
306 return list.__contains__(self, value)
307 len_value = len(value)
308 len_self = len(self)
309 if len_value > len_self:
310 return False
311
312 for i in range(0, len_self - len_value + 1):
313 sub_list = self[i:i+len_value]
314 if sub_list == value:
315 return True
316 return False
317
318 def __repr__(self):
319 return pprint.pformat(list(self))
320
321
322def _check_and_set_parent(parent, value, name, new_name):
323 if not _is_instance_mock(value):
324 return False
325 if ((value._mock_name or value._mock_new_name) or
326 (value._mock_parent is not None) or
327 (value._mock_new_parent is not None)):
328 return False
329
330 _parent = parent
331 while _parent is not None:
332 # setting a mock (value) as a child or return value of itself
333 # should not modify the mock
334 if _parent is value:
335 return False
336 _parent = _parent._mock_new_parent
337
338 if new_name:
339 value._mock_new_parent = parent
340 value._mock_new_name = new_name
341 if name:
342 value._mock_parent = parent
343 value._mock_name = name
344 return True
345
Michael Foord01bafdc2014-04-14 16:09:42 -0400346# Internal class to identify if we wrapped an iterator object or not.
347class _MockIter(object):
348 def __init__(self, obj):
349 self.obj = iter(obj)
350 def __iter__(self):
351 return self
352 def __next__(self):
353 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700354
355class Base(object):
356 _mock_return_value = DEFAULT
357 _mock_side_effect = None
358 def __init__(self, *args, **kwargs):
359 pass
360
361
362
363class NonCallableMock(Base):
364 """A non-callable version of `Mock`"""
365
366 def __new__(cls, *args, **kw):
367 # every instance has its own class
368 # so we can create magic methods on the
369 # class without stomping on other mocks
370 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
371 instance = object.__new__(new)
372 return instance
373
374
375 def __init__(
376 self, spec=None, wraps=None, name=None, spec_set=None,
377 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100378 _spec_as_instance=False, _eat_self=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700379 ):
380 if _new_parent is None:
381 _new_parent = parent
382
383 __dict__ = self.__dict__
384 __dict__['_mock_parent'] = parent
385 __dict__['_mock_name'] = name
386 __dict__['_mock_new_name'] = _new_name
387 __dict__['_mock_new_parent'] = _new_parent
388
389 if spec_set is not None:
390 spec = spec_set
391 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100392 if _eat_self is None:
393 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700394
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100395 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700396
397 __dict__['_mock_children'] = {}
398 __dict__['_mock_wraps'] = wraps
399 __dict__['_mock_delegate'] = None
400
401 __dict__['_mock_called'] = False
402 __dict__['_mock_call_args'] = None
403 __dict__['_mock_call_count'] = 0
404 __dict__['_mock_call_args_list'] = _CallList()
405 __dict__['_mock_mock_calls'] = _CallList()
406
407 __dict__['method_calls'] = _CallList()
408
409 if kwargs:
410 self.configure_mock(**kwargs)
411
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000412 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700413 spec, wraps, name, spec_set, parent,
414 _spec_state
415 )
416
417
418 def attach_mock(self, mock, attribute):
419 """
420 Attach a mock as an attribute of this one, replacing its name and
421 parent. Calls to the attached mock will be recorded in the
422 `method_calls` and `mock_calls` attributes of this one."""
423 mock._mock_parent = None
424 mock._mock_new_parent = None
425 mock._mock_name = ''
426 mock._mock_new_name = None
427
428 setattr(self, attribute, mock)
429
430
431 def mock_add_spec(self, spec, spec_set=False):
432 """Add a spec to a mock. `spec` can either be an object or a
433 list of strings. Only attributes on the `spec` can be fetched as
434 attributes from the mock.
435
436 If `spec_set` is True then only attributes on the spec can be set."""
437 self._mock_add_spec(spec, spec_set)
438
439
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100440 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
441 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700442 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100443 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700444
445 if spec is not None and not _is_list(spec):
446 if isinstance(spec, type):
447 _spec_class = spec
448 else:
449 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100450 res = _get_signature_object(spec,
451 _spec_as_instance, _eat_self)
452 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700453
454 spec = dir(spec)
455
456 __dict__ = self.__dict__
457 __dict__['_spec_class'] = _spec_class
458 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100459 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700460 __dict__['_mock_methods'] = spec
461
462
463 def __get_return_value(self):
464 ret = self._mock_return_value
465 if self._mock_delegate is not None:
466 ret = self._mock_delegate.return_value
467
468 if ret is DEFAULT:
469 ret = self._get_child_mock(
470 _new_parent=self, _new_name='()'
471 )
472 self.return_value = ret
473 return ret
474
475
476 def __set_return_value(self, value):
477 if self._mock_delegate is not None:
478 self._mock_delegate.return_value = value
479 else:
480 self._mock_return_value = value
481 _check_and_set_parent(self, value, None, '()')
482
483 __return_value_doc = "The value to be returned when the mock is called."
484 return_value = property(__get_return_value, __set_return_value,
485 __return_value_doc)
486
487
488 @property
489 def __class__(self):
490 if self._spec_class is None:
491 return type(self)
492 return self._spec_class
493
494 called = _delegating_property('called')
495 call_count = _delegating_property('call_count')
496 call_args = _delegating_property('call_args')
497 call_args_list = _delegating_property('call_args_list')
498 mock_calls = _delegating_property('mock_calls')
499
500
501 def __get_side_effect(self):
502 delegated = self._mock_delegate
503 if delegated is None:
504 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400505 sf = delegated.side_effect
506 if sf is not None and not callable(sf) and not isinstance(sf, _MockIter):
507 sf = _MockIter(sf)
508 delegated.side_effect = sf
509 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700510
511 def __set_side_effect(self, value):
512 value = _try_iter(value)
513 delegated = self._mock_delegate
514 if delegated is None:
515 self._mock_side_effect = value
516 else:
517 delegated.side_effect = value
518
519 side_effect = property(__get_side_effect, __set_side_effect)
520
521
522 def reset_mock(self):
523 "Restore the mock object to its initial state."
524 self.called = False
525 self.call_args = None
526 self.call_count = 0
527 self.mock_calls = _CallList()
528 self.call_args_list = _CallList()
529 self.method_calls = _CallList()
530
531 for child in self._mock_children.values():
Michael Foord75963642012-06-09 17:31:59 +0100532 if isinstance(child, _SpecState):
533 continue
Michael Foord345266a2012-03-14 12:24:34 -0700534 child.reset_mock()
535
536 ret = self._mock_return_value
537 if _is_instance_mock(ret) and ret is not self:
538 ret.reset_mock()
539
540
541 def configure_mock(self, **kwargs):
542 """Set attributes on the mock through keyword arguments.
543
544 Attributes plus return values and side effects can be set on child
545 mocks using standard dot notation and unpacking a dictionary in the
546 method call:
547
548 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
549 >>> mock.configure_mock(**attrs)"""
550 for arg, val in sorted(kwargs.items(),
551 # we sort on the number of dots so that
552 # attributes are set before we set attributes on
553 # attributes
554 key=lambda entry: entry[0].count('.')):
555 args = arg.split('.')
556 final = args.pop()
557 obj = self
558 for entry in args:
559 obj = getattr(obj, entry)
560 setattr(obj, final, val)
561
562
563 def __getattr__(self, name):
564 if name == '_mock_methods':
565 raise AttributeError(name)
566 elif self._mock_methods is not None:
567 if name not in self._mock_methods or name in _all_magics:
568 raise AttributeError("Mock object has no attribute %r" % name)
569 elif _is_magic(name):
570 raise AttributeError(name)
571
572 result = self._mock_children.get(name)
573 if result is _deleted:
574 raise AttributeError(name)
575 elif result is None:
576 wraps = None
577 if self._mock_wraps is not None:
578 # XXXX should we get the attribute without triggering code
579 # execution?
580 wraps = getattr(self._mock_wraps, name)
581
582 result = self._get_child_mock(
583 parent=self, name=name, wraps=wraps, _new_name=name,
584 _new_parent=self
585 )
586 self._mock_children[name] = result
587
588 elif isinstance(result, _SpecState):
589 result = create_autospec(
590 result.spec, result.spec_set, result.instance,
591 result.parent, result.name
592 )
593 self._mock_children[name] = result
594
595 return result
596
597
598 def __repr__(self):
599 _name_list = [self._mock_new_name]
600 _parent = self._mock_new_parent
601 last = self
602
603 dot = '.'
604 if _name_list == ['()']:
605 dot = ''
606 seen = set()
607 while _parent is not None:
608 last = _parent
609
610 _name_list.append(_parent._mock_new_name + dot)
611 dot = '.'
612 if _parent._mock_new_name == '()':
613 dot = ''
614
615 _parent = _parent._mock_new_parent
616
617 # use ids here so as not to call __hash__ on the mocks
618 if id(_parent) in seen:
619 break
620 seen.add(id(_parent))
621
622 _name_list = list(reversed(_name_list))
623 _first = last._mock_name or 'mock'
624 if len(_name_list) > 1:
625 if _name_list[1] not in ('()', '().'):
626 _first += '.'
627 _name_list[0] = _first
628 name = ''.join(_name_list)
629
630 name_string = ''
631 if name not in ('mock', 'mock.'):
632 name_string = ' name=%r' % name
633
634 spec_string = ''
635 if self._spec_class is not None:
636 spec_string = ' spec=%r'
637 if self._spec_set:
638 spec_string = ' spec_set=%r'
639 spec_string = spec_string % self._spec_class.__name__
640 return "<%s%s%s id='%s'>" % (
641 type(self).__name__,
642 name_string,
643 spec_string,
644 id(self)
645 )
646
647
648 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700649 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100650 if not FILTER_DIR:
651 return object.__dir__(self)
652
Michael Foord345266a2012-03-14 12:24:34 -0700653 extras = self._mock_methods or []
654 from_type = dir(type(self))
655 from_dict = list(self.__dict__)
656
Michael Foord313f85f2012-03-25 18:16:07 +0100657 from_type = [e for e in from_type if not e.startswith('_')]
658 from_dict = [e for e in from_dict if not e.startswith('_') or
659 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700660 return sorted(set(extras + from_type + from_dict +
661 list(self._mock_children)))
662
663
664 def __setattr__(self, name, value):
665 if name in _allowed_names:
666 # property setters go through here
667 return object.__setattr__(self, name, value)
668 elif (self._spec_set and self._mock_methods is not None and
669 name not in self._mock_methods and
670 name not in self.__dict__):
671 raise AttributeError("Mock object has no attribute '%s'" % name)
672 elif name in _unsupported_magics:
673 msg = 'Attempting to set unsupported magic method %r.' % name
674 raise AttributeError(msg)
675 elif name in _all_magics:
676 if self._mock_methods is not None and name not in self._mock_methods:
677 raise AttributeError("Mock object has no attribute '%s'" % name)
678
679 if not _is_instance_mock(value):
680 setattr(type(self), name, _get_method(name, value))
681 original = value
682 value = lambda *args, **kw: original(self, *args, **kw)
683 else:
684 # only set _new_name and not name so that mock_calls is tracked
685 # but not method calls
686 _check_and_set_parent(self, value, None, name)
687 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100688 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700689 elif name == '__class__':
690 self._spec_class = value
691 return
692 else:
693 if _check_and_set_parent(self, value, name, name):
694 self._mock_children[name] = value
695 return object.__setattr__(self, name, value)
696
697
698 def __delattr__(self, name):
699 if name in _all_magics and name in type(self).__dict__:
700 delattr(type(self), name)
701 if name not in self.__dict__:
702 # for magic methods that are still MagicProxy objects and
703 # not set on the instance itself
704 return
705
706 if name in self.__dict__:
707 object.__delattr__(self, name)
708
709 obj = self._mock_children.get(name, _missing)
710 if obj is _deleted:
711 raise AttributeError(name)
712 if obj is not _missing:
713 del self._mock_children[name]
714 self._mock_children[name] = _deleted
715
716
Michael Foord345266a2012-03-14 12:24:34 -0700717 def _format_mock_call_signature(self, args, kwargs):
718 name = self._mock_name or 'mock'
719 return _format_call_signature(name, args, kwargs)
720
721
722 def _format_mock_failure_message(self, args, kwargs):
723 message = 'Expected call: %s\nActual call: %s'
724 expected_string = self._format_mock_call_signature(args, kwargs)
725 call_args = self.call_args
726 if len(call_args) == 3:
727 call_args = call_args[1:]
728 actual_string = self._format_mock_call_signature(*call_args)
729 return message % (expected_string, actual_string)
730
731
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100732 def _call_matcher(self, _call):
733 """
734 Given a call (or simply a (args, kwargs) tuple), return a
735 comparison key suitable for matching with other calls.
736 This is a best effort method which relies on the spec's signature,
737 if available, or falls back on the arguments themselves.
738 """
739 sig = self._spec_signature
740 if sig is not None:
741 if len(_call) == 2:
742 name = ''
743 args, kwargs = _call
744 else:
745 name, args, kwargs = _call
746 try:
747 return name, sig.bind(*args, **kwargs)
748 except TypeError as e:
749 return e.with_traceback(None)
750 else:
751 return _call
752
753
Michael Foord345266a2012-03-14 12:24:34 -0700754 def assert_called_with(_mock_self, *args, **kwargs):
755 """assert that the mock was called with the specified arguments.
756
757 Raises an AssertionError if the args and keyword args passed in are
758 different to the last call to the mock."""
759 self = _mock_self
760 if self.call_args is None:
761 expected = self._format_mock_call_signature(args, kwargs)
762 raise AssertionError('Expected call: %s\nNot called' % (expected,))
763
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100764 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700765 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100766 return msg
767 expected = self._call_matcher((args, kwargs))
768 actual = self._call_matcher(self.call_args)
769 if expected != actual:
770 cause = expected if isinstance(expected, Exception) else None
771 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700772
773
774 def assert_called_once_with(_mock_self, *args, **kwargs):
775 """assert that the mock was called exactly once and with the specified
776 arguments."""
777 self = _mock_self
778 if not self.call_count == 1:
Michael Foord28d591c2012-09-28 16:15:22 +0100779 msg = ("Expected '%s' to be called once. Called %s times." %
780 (self._mock_name or 'mock', self.call_count))
Michael Foord345266a2012-03-14 12:24:34 -0700781 raise AssertionError(msg)
782 return self.assert_called_with(*args, **kwargs)
783
784
785 def assert_has_calls(self, calls, any_order=False):
786 """assert the mock has been called with the specified calls.
787 The `mock_calls` list is checked for the calls.
788
789 If `any_order` is False (the default) then the calls must be
790 sequential. There can be extra calls before or after the
791 specified calls.
792
793 If `any_order` is True then the calls can be in any order, but
794 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100795 expected = [self._call_matcher(c) for c in calls]
796 cause = expected if isinstance(expected, Exception) else None
797 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700798 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100799 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700800 raise AssertionError(
801 'Calls not found.\nExpected: %r\n'
802 'Actual: %r' % (calls, self.mock_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100803 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700804 return
805
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100806 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700807
808 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100809 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700810 try:
811 all_calls.remove(kall)
812 except ValueError:
813 not_found.append(kall)
814 if not_found:
815 raise AssertionError(
816 '%r not all found in call list' % (tuple(not_found),)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100817 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700818
819
820 def assert_any_call(self, *args, **kwargs):
821 """assert the mock has been called with the specified arguments.
822
823 The assert passes if the mock has *ever* been called, unlike
824 `assert_called_with` and `assert_called_once_with` that only pass if
825 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100826 expected = self._call_matcher((args, kwargs))
827 actual = [self._call_matcher(c) for c in self.call_args_list]
828 if expected not in actual:
829 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700830 expected_string = self._format_mock_call_signature(args, kwargs)
831 raise AssertionError(
832 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100833 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700834
835
836 def _get_child_mock(self, **kw):
837 """Create the child mocks for attributes and return value.
838 By default child mocks will be the same type as the parent.
839 Subclasses of Mock may want to override this to customize the way
840 child mocks are made.
841
842 For non-callable mocks the callable variant will be used (rather than
843 any custom subclass)."""
844 _type = type(self)
845 if not issubclass(_type, CallableMixin):
846 if issubclass(_type, NonCallableMagicMock):
847 klass = MagicMock
848 elif issubclass(_type, NonCallableMock) :
849 klass = Mock
850 else:
851 klass = _type.__mro__[1]
852 return klass(**kw)
853
854
855
856def _try_iter(obj):
857 if obj is None:
858 return obj
859 if _is_exception(obj):
860 return obj
861 if _callable(obj):
862 return obj
863 try:
864 return iter(obj)
865 except TypeError:
866 # XXXX backwards compatibility
867 # but this will blow up on first call - so maybe we should fail early?
868 return obj
869
870
871
872class CallableMixin(Base):
873
874 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
875 wraps=None, name=None, spec_set=None, parent=None,
876 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
877 self.__dict__['_mock_return_value'] = return_value
878
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000879 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700880 spec, wraps, name, spec_set, parent,
881 _spec_state, _new_name, _new_parent, **kwargs
882 )
883
884 self.side_effect = side_effect
885
886
887 def _mock_check_sig(self, *args, **kwargs):
888 # stub method that can be replaced with one with a specific signature
889 pass
890
891
892 def __call__(_mock_self, *args, **kwargs):
893 # can't use self in-case a function / method we are mocking uses self
894 # in the signature
895 _mock_self._mock_check_sig(*args, **kwargs)
896 return _mock_self._mock_call(*args, **kwargs)
897
898
899 def _mock_call(_mock_self, *args, **kwargs):
900 self = _mock_self
901 self.called = True
902 self.call_count += 1
Michael Foord345266a2012-03-14 12:24:34 -0700903 _new_name = self._mock_new_name
904 _new_parent = self._mock_new_parent
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100905
906 _call = _Call((args, kwargs), two=True)
907 self.call_args = _call
908 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700909 self.mock_calls.append(_Call(('', args, kwargs)))
910
911 seen = set()
912 skip_next_dot = _new_name == '()'
913 do_method_calls = self._mock_parent is not None
914 name = self._mock_name
915 while _new_parent is not None:
916 this_mock_call = _Call((_new_name, args, kwargs))
917 if _new_parent._mock_new_name:
918 dot = '.'
919 if skip_next_dot:
920 dot = ''
921
922 skip_next_dot = False
923 if _new_parent._mock_new_name == '()':
924 skip_next_dot = True
925
926 _new_name = _new_parent._mock_new_name + dot + _new_name
927
928 if do_method_calls:
929 if _new_name == name:
930 this_method_call = this_mock_call
931 else:
932 this_method_call = _Call((name, args, kwargs))
933 _new_parent.method_calls.append(this_method_call)
934
935 do_method_calls = _new_parent._mock_parent is not None
936 if do_method_calls:
937 name = _new_parent._mock_name + '.' + name
938
939 _new_parent.mock_calls.append(this_mock_call)
940 _new_parent = _new_parent._mock_new_parent
941
942 # use ids here so as not to call __hash__ on the mocks
943 _new_parent_id = id(_new_parent)
944 if _new_parent_id in seen:
945 break
946 seen.add(_new_parent_id)
947
948 ret_val = DEFAULT
949 effect = self.side_effect
950 if effect is not None:
951 if _is_exception(effect):
952 raise effect
953
954 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +0100955 result = next(effect)
956 if _is_exception(result):
957 raise result
Andrew Svetlov8b2cd752013-04-07 16:42:24 +0300958 if result is DEFAULT:
959 result = self.return_value
Michael Foord2cd48732012-04-21 15:52:11 +0100960 return result
Michael Foord345266a2012-03-14 12:24:34 -0700961
962 ret_val = effect(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700963
964 if (self._mock_wraps is not None and
965 self._mock_return_value is DEFAULT):
966 return self._mock_wraps(*args, **kwargs)
967 if ret_val is DEFAULT:
968 ret_val = self.return_value
969 return ret_val
970
971
972
973class Mock(CallableMixin, NonCallableMock):
974 """
975 Create a new `Mock` object. `Mock` takes several optional arguments
976 that specify the behaviour of the Mock object:
977
978 * `spec`: This can be either a list of strings or an existing object (a
979 class or instance) that acts as the specification for the mock object. If
980 you pass in an object then a list of strings is formed by calling dir on
981 the object (excluding unsupported magic attributes and methods). Accessing
982 any attribute not in this list will raise an `AttributeError`.
983
984 If `spec` is an object (rather than a list of strings) then
985 `mock.__class__` returns the class of the spec object. This allows mocks
986 to pass `isinstance` tests.
987
988 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
989 or get an attribute on the mock that isn't on the object passed as
990 `spec_set` will raise an `AttributeError`.
991
992 * `side_effect`: A function to be called whenever the Mock is called. See
993 the `side_effect` attribute. Useful for raising exceptions or
994 dynamically changing return values. The function is called with the same
995 arguments as the mock, and unless it returns `DEFAULT`, the return
996 value of this function is used as the return value.
997
Michael Foord2cd48732012-04-21 15:52:11 +0100998 If `side_effect` is an iterable then each call to the mock will return
999 the next value from the iterable. If any of the members of the iterable
1000 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001001
Michael Foord345266a2012-03-14 12:24:34 -07001002 * `return_value`: The value returned when the mock is called. By default
1003 this is a new Mock (created on first access). See the
1004 `return_value` attribute.
1005
Michael Foord0682a0c2012-04-13 20:51:20 +01001006 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1007 calling the Mock will pass the call through to the wrapped object
1008 (returning the real result). Attribute access on the mock will return a
1009 Mock object that wraps the corresponding attribute of the wrapped object
1010 (so attempting to access an attribute that doesn't exist will raise an
1011 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001012
1013 If the mock has an explicit `return_value` set then calls are not passed
1014 to the wrapped object and the `return_value` is returned instead.
1015
1016 * `name`: If the mock has a name then it will be used in the repr of the
1017 mock. This can be useful for debugging. The name is propagated to child
1018 mocks.
1019
1020 Mocks can also be called with arbitrary keyword arguments. These will be
1021 used to set attributes on the mock after it is created.
1022 """
1023
1024
1025
1026def _dot_lookup(thing, comp, import_path):
1027 try:
1028 return getattr(thing, comp)
1029 except AttributeError:
1030 __import__(import_path)
1031 return getattr(thing, comp)
1032
1033
1034def _importer(target):
1035 components = target.split('.')
1036 import_path = components.pop(0)
1037 thing = __import__(import_path)
1038
1039 for comp in components:
1040 import_path += ".%s" % comp
1041 thing = _dot_lookup(thing, comp, import_path)
1042 return thing
1043
1044
1045def _is_started(patcher):
1046 # XXXX horrible
1047 return hasattr(patcher, 'is_local')
1048
1049
1050class _patch(object):
1051
1052 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001053 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001054
1055 def __init__(
1056 self, getter, attribute, new, spec, create,
1057 spec_set, autospec, new_callable, kwargs
1058 ):
1059 if new_callable is not None:
1060 if new is not DEFAULT:
1061 raise ValueError(
1062 "Cannot use 'new' and 'new_callable' together"
1063 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001064 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001065 raise ValueError(
1066 "Cannot use 'autospec' and 'new_callable' together"
1067 )
1068
1069 self.getter = getter
1070 self.attribute = attribute
1071 self.new = new
1072 self.new_callable = new_callable
1073 self.spec = spec
1074 self.create = create
1075 self.has_local = False
1076 self.spec_set = spec_set
1077 self.autospec = autospec
1078 self.kwargs = kwargs
1079 self.additional_patchers = []
1080
1081
1082 def copy(self):
1083 patcher = _patch(
1084 self.getter, self.attribute, self.new, self.spec,
1085 self.create, self.spec_set,
1086 self.autospec, self.new_callable, self.kwargs
1087 )
1088 patcher.attribute_name = self.attribute_name
1089 patcher.additional_patchers = [
1090 p.copy() for p in self.additional_patchers
1091 ]
1092 return patcher
1093
1094
1095 def __call__(self, func):
1096 if isinstance(func, type):
1097 return self.decorate_class(func)
1098 return self.decorate_callable(func)
1099
1100
1101 def decorate_class(self, klass):
1102 for attr in dir(klass):
1103 if not attr.startswith(patch.TEST_PREFIX):
1104 continue
1105
1106 attr_value = getattr(klass, attr)
1107 if not hasattr(attr_value, "__call__"):
1108 continue
1109
1110 patcher = self.copy()
1111 setattr(klass, attr, patcher(attr_value))
1112 return klass
1113
1114
1115 def decorate_callable(self, func):
1116 if hasattr(func, 'patchings'):
1117 func.patchings.append(self)
1118 return func
1119
1120 @wraps(func)
1121 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001122 extra_args = []
1123 entered_patchers = []
1124
Michael Foord50a8c0e2012-03-25 18:57:58 +01001125 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001126 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001127 for patching in patched.patchings:
1128 arg = patching.__enter__()
1129 entered_patchers.append(patching)
1130 if patching.attribute_name is not None:
1131 keywargs.update(arg)
1132 elif patching.new is DEFAULT:
1133 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001134
Michael Foordd7c65e22012-03-14 14:56:54 -07001135 args += tuple(extra_args)
1136 return func(*args, **keywargs)
1137 except:
1138 if (patching not in entered_patchers and
1139 _is_started(patching)):
1140 # the patcher may have been started, but an exception
1141 # raised whilst entering one of its additional_patchers
1142 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001143 # Pass the exception to __exit__
1144 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001145 # re-raise the exception
1146 raise
Michael Foord345266a2012-03-14 12:24:34 -07001147 finally:
1148 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001149 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001150
1151 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001152 return patched
1153
1154
1155 def get_original(self):
1156 target = self.getter()
1157 name = self.attribute
1158
1159 original = DEFAULT
1160 local = False
1161
1162 try:
1163 original = target.__dict__[name]
1164 except (AttributeError, KeyError):
1165 original = getattr(target, name, DEFAULT)
1166 else:
1167 local = True
1168
1169 if not self.create and original is DEFAULT:
1170 raise AttributeError(
1171 "%s does not have the attribute %r" % (target, name)
1172 )
1173 return original, local
1174
1175
1176 def __enter__(self):
1177 """Perform the patch."""
1178 new, spec, spec_set = self.new, self.spec, self.spec_set
1179 autospec, kwargs = self.autospec, self.kwargs
1180 new_callable = self.new_callable
1181 self.target = self.getter()
1182
Michael Foord50a8c0e2012-03-25 18:57:58 +01001183 # normalise False to None
1184 if spec is False:
1185 spec = None
1186 if spec_set is False:
1187 spec_set = None
1188 if autospec is False:
1189 autospec = None
1190
1191 if spec is not None and autospec is not None:
1192 raise TypeError("Can't specify spec and autospec")
1193 if ((spec is not None or autospec is not None) and
1194 spec_set not in (True, None)):
1195 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1196
Michael Foord345266a2012-03-14 12:24:34 -07001197 original, local = self.get_original()
1198
Michael Foord50a8c0e2012-03-25 18:57:58 +01001199 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001200 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001201 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001202 # set spec to the object we are replacing
1203 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001204 if spec_set is True:
1205 spec_set = original
1206 spec = None
1207 elif spec is not None:
1208 if spec_set is True:
1209 spec_set = spec
1210 spec = None
1211 elif spec_set is True:
1212 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001213
Michael Foord50a8c0e2012-03-25 18:57:58 +01001214 if spec is not None or spec_set is not None:
1215 if original is DEFAULT:
1216 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001217 if isinstance(original, type):
1218 # If we're patching out a class and there is a spec
1219 inherit = True
1220
1221 Klass = MagicMock
1222 _kwargs = {}
1223 if new_callable is not None:
1224 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001225 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001226 this_spec = spec
1227 if spec_set is not None:
1228 this_spec = spec_set
1229 if _is_list(this_spec):
1230 not_callable = '__call__' not in this_spec
1231 else:
1232 not_callable = not callable(this_spec)
1233 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001234 Klass = NonCallableMagicMock
1235
1236 if spec is not None:
1237 _kwargs['spec'] = spec
1238 if spec_set is not None:
1239 _kwargs['spec_set'] = spec_set
1240
1241 # add a name to mocks
1242 if (isinstance(Klass, type) and
1243 issubclass(Klass, NonCallableMock) and self.attribute):
1244 _kwargs['name'] = self.attribute
1245
1246 _kwargs.update(kwargs)
1247 new = Klass(**_kwargs)
1248
1249 if inherit and _is_instance_mock(new):
1250 # we can only tell if the instance should be callable if the
1251 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001252 this_spec = spec
1253 if spec_set is not None:
1254 this_spec = spec_set
1255 if (not _is_list(this_spec) and not
1256 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001257 Klass = NonCallableMagicMock
1258
1259 _kwargs.pop('name')
1260 new.return_value = Klass(_new_parent=new, _new_name='()',
1261 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001262 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001263 # spec is ignored, new *must* be default, spec_set is treated
1264 # as a boolean. Should we check spec is not None and that spec_set
1265 # is a bool?
1266 if new is not DEFAULT:
1267 raise TypeError(
1268 "autospec creates the mock for you. Can't specify "
1269 "autospec and new."
1270 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001271 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001272 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001273 spec_set = bool(spec_set)
1274 if autospec is True:
1275 autospec = original
1276
1277 new = create_autospec(autospec, spec_set=spec_set,
1278 _name=self.attribute, **kwargs)
1279 elif kwargs:
1280 # can't set keyword args when we aren't creating the mock
1281 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1282 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1283
1284 new_attr = new
1285
1286 self.temp_original = original
1287 self.is_local = local
1288 setattr(self.target, self.attribute, new_attr)
1289 if self.attribute_name is not None:
1290 extra_args = {}
1291 if self.new is DEFAULT:
1292 extra_args[self.attribute_name] = new
1293 for patching in self.additional_patchers:
1294 arg = patching.__enter__()
1295 if patching.new is DEFAULT:
1296 extra_args.update(arg)
1297 return extra_args
1298
1299 return new
1300
1301
Michael Foord50a8c0e2012-03-25 18:57:58 +01001302 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001303 """Undo the patch."""
1304 if not _is_started(self):
1305 raise RuntimeError('stop called on unstarted patcher')
1306
1307 if self.is_local and self.temp_original is not DEFAULT:
1308 setattr(self.target, self.attribute, self.temp_original)
1309 else:
1310 delattr(self.target, self.attribute)
1311 if not self.create and not hasattr(self.target, self.attribute):
1312 # needed for proxy objects like django settings
1313 setattr(self.target, self.attribute, self.temp_original)
1314
1315 del self.temp_original
1316 del self.is_local
1317 del self.target
1318 for patcher in reversed(self.additional_patchers):
1319 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001320 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001321
Michael Foordf7c41582012-06-10 20:36:32 +01001322
1323 def start(self):
1324 """Activate a patch, returning any created mock."""
1325 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001326 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001327 return result
1328
1329
1330 def stop(self):
1331 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001332 try:
1333 self._active_patches.remove(self)
1334 except ValueError:
1335 # If the patch hasn't been started this will fail
1336 pass
1337
Michael Foordf7c41582012-06-10 20:36:32 +01001338 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001339
1340
1341
1342def _get_target(target):
1343 try:
1344 target, attribute = target.rsplit('.', 1)
1345 except (TypeError, ValueError):
1346 raise TypeError("Need a valid target to patch. You supplied: %r" %
1347 (target,))
1348 getter = lambda: _importer(target)
1349 return getter, attribute
1350
1351
1352def _patch_object(
1353 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001354 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001355 new_callable=None, **kwargs
1356 ):
1357 """
Michael Foord345266a2012-03-14 12:24:34 -07001358 patch the named member (`attribute`) on an object (`target`) with a mock
1359 object.
1360
1361 `patch.object` can be used as a decorator, class decorator or a context
1362 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1363 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1364 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1365 the mock object it creates.
1366
1367 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1368 for choosing which methods to wrap.
1369 """
1370 getter = lambda: target
1371 return _patch(
1372 getter, attribute, new, spec, create,
1373 spec_set, autospec, new_callable, kwargs
1374 )
1375
1376
Michael Foord50a8c0e2012-03-25 18:57:58 +01001377def _patch_multiple(target, spec=None, create=False, spec_set=None,
1378 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001379 """Perform multiple patches in a single call. It takes the object to be
1380 patched (either as an object or a string to fetch the object by importing)
1381 and keyword arguments for the patches::
1382
1383 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1384 ...
1385
1386 Use `DEFAULT` as the value if you want `patch.multiple` to create
1387 mocks for you. In this case the created mocks are passed into a decorated
1388 function by keyword, and a dictionary is returned when `patch.multiple` is
1389 used as a context manager.
1390
1391 `patch.multiple` can be used as a decorator, class decorator or a context
1392 manager. The arguments `spec`, `spec_set`, `create`,
1393 `autospec` and `new_callable` have the same meaning as for `patch`. These
1394 arguments will be applied to *all* patches done by `patch.multiple`.
1395
1396 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1397 for choosing which methods to wrap.
1398 """
1399 if type(target) is str:
1400 getter = lambda: _importer(target)
1401 else:
1402 getter = lambda: target
1403
1404 if not kwargs:
1405 raise ValueError(
1406 'Must supply at least one keyword argument with patch.multiple'
1407 )
1408 # need to wrap in a list for python 3, where items is a view
1409 items = list(kwargs.items())
1410 attribute, new = items[0]
1411 patcher = _patch(
1412 getter, attribute, new, spec, create, spec_set,
1413 autospec, new_callable, {}
1414 )
1415 patcher.attribute_name = attribute
1416 for attribute, new in items[1:]:
1417 this_patcher = _patch(
1418 getter, attribute, new, spec, create, spec_set,
1419 autospec, new_callable, {}
1420 )
1421 this_patcher.attribute_name = attribute
1422 patcher.additional_patchers.append(this_patcher)
1423 return patcher
1424
1425
1426def patch(
1427 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001428 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001429 ):
1430 """
1431 `patch` acts as a function decorator, class decorator or a context
1432 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001433 is patched with a `new` object. When the function/with statement exits
1434 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001435
Michael Foord54b3db82012-03-28 15:08:08 +01001436 If `new` is omitted, then the target is replaced with a
1437 `MagicMock`. If `patch` is used as a decorator and `new` is
1438 omitted, the created mock is passed in as an extra argument to the
1439 decorated function. If `patch` is used as a context manager the created
1440 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001441
Michael Foord54b3db82012-03-28 15:08:08 +01001442 `target` should be a string in the form `'package.module.ClassName'`. The
1443 `target` is imported and the specified object replaced with the `new`
1444 object, so the `target` must be importable from the environment you are
1445 calling `patch` from. The target is imported when the decorated function
1446 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001447
1448 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1449 if patch is creating one for you.
1450
1451 In addition you can pass `spec=True` or `spec_set=True`, which causes
1452 patch to pass in the object being mocked as the spec/spec_set object.
1453
1454 `new_callable` allows you to specify a different class, or callable object,
1455 that will be called to create the `new` object. By default `MagicMock` is
1456 used.
1457
1458 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1459 then the mock with be created with a spec from the object being replaced.
1460 All attributes of the mock will also have the spec of the corresponding
1461 attribute of the object being replaced. Methods and functions being
1462 mocked will have their arguments checked and will raise a `TypeError` if
1463 they are called with the wrong signature. For mocks replacing a class,
1464 their return value (the 'instance') will have the same spec as the class.
1465
1466 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1467 arbitrary object as the spec instead of the one being replaced.
1468
1469 By default `patch` will fail to replace attributes that don't exist. If
1470 you pass in `create=True`, and the attribute doesn't exist, patch will
1471 create the attribute for you when the patched function is called, and
1472 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001473 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001474 default because it can be dangerous. With it switched on you can write
1475 passing tests against APIs that don't actually exist!
1476
1477 Patch can be used as a `TestCase` class decorator. It works by
1478 decorating each test method in the class. This reduces the boilerplate
1479 code when your test methods share a common patchings set. `patch` finds
1480 tests by looking for method names that start with `patch.TEST_PREFIX`.
1481 By default this is `test`, which matches the way `unittest` finds tests.
1482 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1483
1484 Patch can be used as a context manager, with the with statement. Here the
1485 patching applies to the indented block after the with statement. If you
1486 use "as" then the patched object will be bound to the name after the
1487 "as"; very useful if `patch` is creating a mock object for you.
1488
1489 `patch` takes arbitrary keyword arguments. These will be passed to
1490 the `Mock` (or `new_callable`) on construction.
1491
1492 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1493 available for alternate use-cases.
1494 """
1495 getter, attribute = _get_target(target)
1496 return _patch(
1497 getter, attribute, new, spec, create,
1498 spec_set, autospec, new_callable, kwargs
1499 )
1500
1501
1502class _patch_dict(object):
1503 """
1504 Patch a dictionary, or dictionary like object, and restore the dictionary
1505 to its original state after the test.
1506
1507 `in_dict` can be a dictionary or a mapping like container. If it is a
1508 mapping then it must at least support getting, setting and deleting items
1509 plus iterating over keys.
1510
1511 `in_dict` can also be a string specifying the name of the dictionary, which
1512 will then be fetched by importing it.
1513
1514 `values` can be a dictionary of values to set in the dictionary. `values`
1515 can also be an iterable of `(key, value)` pairs.
1516
1517 If `clear` is True then the dictionary will be cleared before the new
1518 values are set.
1519
1520 `patch.dict` can also be called with arbitrary keyword arguments to set
1521 values in the dictionary::
1522
1523 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1524 ...
1525
1526 `patch.dict` can be used as a context manager, decorator or class
1527 decorator. When used as a class decorator `patch.dict` honours
1528 `patch.TEST_PREFIX` for choosing which methods to wrap.
1529 """
1530
1531 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1532 if isinstance(in_dict, str):
1533 in_dict = _importer(in_dict)
1534 self.in_dict = in_dict
1535 # support any argument supported by dict(...) constructor
1536 self.values = dict(values)
1537 self.values.update(kwargs)
1538 self.clear = clear
1539 self._original = None
1540
1541
1542 def __call__(self, f):
1543 if isinstance(f, type):
1544 return self.decorate_class(f)
1545 @wraps(f)
1546 def _inner(*args, **kw):
1547 self._patch_dict()
1548 try:
1549 return f(*args, **kw)
1550 finally:
1551 self._unpatch_dict()
1552
1553 return _inner
1554
1555
1556 def decorate_class(self, klass):
1557 for attr in dir(klass):
1558 attr_value = getattr(klass, attr)
1559 if (attr.startswith(patch.TEST_PREFIX) and
1560 hasattr(attr_value, "__call__")):
1561 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1562 decorated = decorator(attr_value)
1563 setattr(klass, attr, decorated)
1564 return klass
1565
1566
1567 def __enter__(self):
1568 """Patch the dict."""
1569 self._patch_dict()
1570
1571
1572 def _patch_dict(self):
1573 values = self.values
1574 in_dict = self.in_dict
1575 clear = self.clear
1576
1577 try:
1578 original = in_dict.copy()
1579 except AttributeError:
1580 # dict like object with no copy method
1581 # must support iteration over keys
1582 original = {}
1583 for key in in_dict:
1584 original[key] = in_dict[key]
1585 self._original = original
1586
1587 if clear:
1588 _clear_dict(in_dict)
1589
1590 try:
1591 in_dict.update(values)
1592 except AttributeError:
1593 # dict like object with no update method
1594 for key in values:
1595 in_dict[key] = values[key]
1596
1597
1598 def _unpatch_dict(self):
1599 in_dict = self.in_dict
1600 original = self._original
1601
1602 _clear_dict(in_dict)
1603
1604 try:
1605 in_dict.update(original)
1606 except AttributeError:
1607 for key in original:
1608 in_dict[key] = original[key]
1609
1610
1611 def __exit__(self, *args):
1612 """Unpatch the dict."""
1613 self._unpatch_dict()
1614 return False
1615
1616 start = __enter__
1617 stop = __exit__
1618
1619
1620def _clear_dict(in_dict):
1621 try:
1622 in_dict.clear()
1623 except AttributeError:
1624 keys = list(in_dict)
1625 for key in keys:
1626 del in_dict[key]
1627
1628
Michael Foordf7c41582012-06-10 20:36:32 +01001629def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001630 """Stop all active patches. LIFO to unroll nested patches."""
1631 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001632 patch.stop()
1633
1634
Michael Foord345266a2012-03-14 12:24:34 -07001635patch.object = _patch_object
1636patch.dict = _patch_dict
1637patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001638patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001639patch.TEST_PREFIX = 'test'
1640
1641magic_methods = (
1642 "lt le gt ge eq ne "
1643 "getitem setitem delitem "
1644 "len contains iter "
1645 "hash str sizeof "
1646 "enter exit "
1647 "divmod neg pos abs invert "
1648 "complex int float index "
1649 "trunc floor ceil "
1650 "bool next "
1651)
1652
Michael Foordd2623d72014-04-14 11:23:48 -04001653numerics = (
1654 "add sub mul div floordiv mod lshift rshift and xor or pow truediv"
1655)
Michael Foord345266a2012-03-14 12:24:34 -07001656inplace = ' '.join('i%s' % n for n in numerics.split())
1657right = ' '.join('r%s' % n for n in numerics.split())
1658
1659# not including __prepare__, __instancecheck__, __subclasscheck__
1660# (as they are metaclass methods)
1661# __del__ is not supported at all as it causes problems if it exists
1662
1663_non_defaults = set('__%s__' % method for method in [
Michael Foord944e02d2012-03-25 23:12:55 +01001664 'get', 'set', 'delete', 'reversed', 'missing', 'reduce', 'reduce_ex',
1665 'getinitargs', 'getnewargs', 'getstate', 'setstate', 'getformat',
1666 'setformat', 'repr', 'dir', 'subclasses', 'format',
Michael Foord345266a2012-03-14 12:24:34 -07001667])
1668
1669
1670def _get_method(name, func):
1671 "Turns a callable object (like a mock) into a real function"
1672 def method(self, *args, **kw):
1673 return func(self, *args, **kw)
1674 method.__name__ = name
1675 return method
1676
1677
1678_magics = set(
1679 '__%s__' % method for method in
1680 ' '.join([magic_methods, numerics, inplace, right]).split()
1681)
1682
1683_all_magics = _magics | _non_defaults
1684
1685_unsupported_magics = set([
1686 '__getattr__', '__setattr__',
1687 '__init__', '__new__', '__prepare__'
1688 '__instancecheck__', '__subclasscheck__',
1689 '__del__'
1690])
1691
1692_calculate_return_value = {
1693 '__hash__': lambda self: object.__hash__(self),
1694 '__str__': lambda self: object.__str__(self),
1695 '__sizeof__': lambda self: object.__sizeof__(self),
1696}
1697
1698_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001699 '__lt__': NotImplemented,
1700 '__gt__': NotImplemented,
1701 '__le__': NotImplemented,
1702 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001703 '__int__': 1,
1704 '__contains__': False,
1705 '__len__': 0,
1706 '__exit__': False,
1707 '__complex__': 1j,
1708 '__float__': 1.0,
1709 '__bool__': True,
1710 '__index__': 1,
1711}
1712
1713
1714def _get_eq(self):
1715 def __eq__(other):
1716 ret_val = self.__eq__._mock_return_value
1717 if ret_val is not DEFAULT:
1718 return ret_val
1719 return self is other
1720 return __eq__
1721
1722def _get_ne(self):
1723 def __ne__(other):
1724 if self.__ne__._mock_return_value is not DEFAULT:
1725 return DEFAULT
1726 return self is not other
1727 return __ne__
1728
1729def _get_iter(self):
1730 def __iter__():
1731 ret_val = self.__iter__._mock_return_value
1732 if ret_val is DEFAULT:
1733 return iter([])
1734 # if ret_val was already an iterator, then calling iter on it should
1735 # return the iterator unchanged
1736 return iter(ret_val)
1737 return __iter__
1738
1739_side_effect_methods = {
1740 '__eq__': _get_eq,
1741 '__ne__': _get_ne,
1742 '__iter__': _get_iter,
1743}
1744
1745
1746
1747def _set_return_value(mock, method, name):
1748 fixed = _return_values.get(name, DEFAULT)
1749 if fixed is not DEFAULT:
1750 method.return_value = fixed
1751 return
1752
1753 return_calulator = _calculate_return_value.get(name)
1754 if return_calulator is not None:
1755 try:
1756 return_value = return_calulator(mock)
1757 except AttributeError:
1758 # XXXX why do we return AttributeError here?
1759 # set it as a side_effect instead?
1760 return_value = AttributeError(name)
1761 method.return_value = return_value
1762 return
1763
1764 side_effector = _side_effect_methods.get(name)
1765 if side_effector is not None:
1766 method.side_effect = side_effector(mock)
1767
1768
1769
1770class MagicMixin(object):
1771 def __init__(self, *args, **kw):
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001772 _safe_super(MagicMixin, self).__init__(*args, **kw)
Michael Foord345266a2012-03-14 12:24:34 -07001773 self._mock_set_magics()
1774
1775
1776 def _mock_set_magics(self):
1777 these_magics = _magics
1778
1779 if self._mock_methods is not None:
1780 these_magics = _magics.intersection(self._mock_methods)
1781
1782 remove_magics = set()
1783 remove_magics = _magics - these_magics
1784
1785 for entry in remove_magics:
1786 if entry in type(self).__dict__:
1787 # remove unneeded magic methods
1788 delattr(self, entry)
1789
1790 # don't overwrite existing attributes if called a second time
1791 these_magics = these_magics - set(type(self).__dict__)
1792
1793 _type = type(self)
1794 for entry in these_magics:
1795 setattr(_type, entry, MagicProxy(entry, self))
1796
1797
1798
1799class NonCallableMagicMock(MagicMixin, NonCallableMock):
1800 """A version of `MagicMock` that isn't callable."""
1801 def mock_add_spec(self, spec, spec_set=False):
1802 """Add a spec to a mock. `spec` can either be an object or a
1803 list of strings. Only attributes on the `spec` can be fetched as
1804 attributes from the mock.
1805
1806 If `spec_set` is True then only attributes on the spec can be set."""
1807 self._mock_add_spec(spec, spec_set)
1808 self._mock_set_magics()
1809
1810
1811
1812class MagicMock(MagicMixin, Mock):
1813 """
1814 MagicMock is a subclass of Mock with default implementations
1815 of most of the magic methods. You can use MagicMock without having to
1816 configure the magic methods yourself.
1817
1818 If you use the `spec` or `spec_set` arguments then *only* magic
1819 methods that exist in the spec will be created.
1820
1821 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1822 """
1823 def mock_add_spec(self, spec, spec_set=False):
1824 """Add a spec to a mock. `spec` can either be an object or a
1825 list of strings. Only attributes on the `spec` can be fetched as
1826 attributes from the mock.
1827
1828 If `spec_set` is True then only attributes on the spec can be set."""
1829 self._mock_add_spec(spec, spec_set)
1830 self._mock_set_magics()
1831
1832
1833
1834class MagicProxy(object):
1835 def __init__(self, name, parent):
1836 self.name = name
1837 self.parent = parent
1838
1839 def __call__(self, *args, **kwargs):
1840 m = self.create_mock()
1841 return m(*args, **kwargs)
1842
1843 def create_mock(self):
1844 entry = self.name
1845 parent = self.parent
1846 m = parent._get_child_mock(name=entry, _new_name=entry,
1847 _new_parent=parent)
1848 setattr(parent, entry, m)
1849 _set_return_value(parent, m, entry)
1850 return m
1851
1852 def __get__(self, obj, _type=None):
1853 return self.create_mock()
1854
1855
1856
1857class _ANY(object):
1858 "A helper object that compares equal to everything."
1859
1860 def __eq__(self, other):
1861 return True
1862
1863 def __ne__(self, other):
1864 return False
1865
1866 def __repr__(self):
1867 return '<ANY>'
1868
1869ANY = _ANY()
1870
1871
1872
1873def _format_call_signature(name, args, kwargs):
1874 message = '%s(%%s)' % name
1875 formatted_args = ''
1876 args_string = ', '.join([repr(arg) for arg in args])
1877 kwargs_string = ', '.join([
1878 '%s=%r' % (key, value) for key, value in kwargs.items()
1879 ])
1880 if args_string:
1881 formatted_args = args_string
1882 if kwargs_string:
1883 if formatted_args:
1884 formatted_args += ', '
1885 formatted_args += kwargs_string
1886
1887 return message % formatted_args
1888
1889
1890
1891class _Call(tuple):
1892 """
1893 A tuple for holding the results of a call to a mock, either in the form
1894 `(args, kwargs)` or `(name, args, kwargs)`.
1895
1896 If args or kwargs are empty then a call tuple will compare equal to
1897 a tuple without those values. This makes comparisons less verbose::
1898
1899 _Call(('name', (), {})) == ('name',)
1900 _Call(('name', (1,), {})) == ('name', (1,))
1901 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1902
1903 The `_Call` object provides a useful shortcut for comparing with call::
1904
1905 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1906 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1907
1908 If the _Call has no name then it will match any name.
1909 """
1910 def __new__(cls, value=(), name=None, parent=None, two=False,
1911 from_kall=True):
1912 name = ''
1913 args = ()
1914 kwargs = {}
1915 _len = len(value)
1916 if _len == 3:
1917 name, args, kwargs = value
1918 elif _len == 2:
1919 first, second = value
1920 if isinstance(first, str):
1921 name = first
1922 if isinstance(second, tuple):
1923 args = second
1924 else:
1925 kwargs = second
1926 else:
1927 args, kwargs = first, second
1928 elif _len == 1:
1929 value, = value
1930 if isinstance(value, str):
1931 name = value
1932 elif isinstance(value, tuple):
1933 args = value
1934 else:
1935 kwargs = value
1936
1937 if two:
1938 return tuple.__new__(cls, (args, kwargs))
1939
1940 return tuple.__new__(cls, (name, args, kwargs))
1941
1942
1943 def __init__(self, value=(), name=None, parent=None, two=False,
1944 from_kall=True):
1945 self.name = name
1946 self.parent = parent
1947 self.from_kall = from_kall
1948
1949
1950 def __eq__(self, other):
1951 if other is ANY:
1952 return True
1953 try:
1954 len_other = len(other)
1955 except TypeError:
1956 return False
1957
1958 self_name = ''
1959 if len(self) == 2:
1960 self_args, self_kwargs = self
1961 else:
1962 self_name, self_args, self_kwargs = self
1963
1964 other_name = ''
1965 if len_other == 0:
1966 other_args, other_kwargs = (), {}
1967 elif len_other == 3:
1968 other_name, other_args, other_kwargs = other
1969 elif len_other == 1:
1970 value, = other
1971 if isinstance(value, tuple):
1972 other_args = value
1973 other_kwargs = {}
1974 elif isinstance(value, str):
1975 other_name = value
1976 other_args, other_kwargs = (), {}
1977 else:
1978 other_args = ()
1979 other_kwargs = value
1980 else:
1981 # len 2
1982 # could be (name, args) or (name, kwargs) or (args, kwargs)
1983 first, second = other
1984 if isinstance(first, str):
1985 other_name = first
1986 if isinstance(second, tuple):
1987 other_args, other_kwargs = second, {}
1988 else:
1989 other_args, other_kwargs = (), second
1990 else:
1991 other_args, other_kwargs = first, second
1992
1993 if self_name and other_name != self_name:
1994 return False
1995
1996 # this order is important for ANY to work!
1997 return (other_args, other_kwargs) == (self_args, self_kwargs)
1998
1999
2000 def __ne__(self, other):
2001 return not self.__eq__(other)
2002
2003
2004 def __call__(self, *args, **kwargs):
2005 if self.name is None:
2006 return _Call(('', args, kwargs), name='()')
2007
2008 name = self.name + '()'
2009 return _Call((self.name, args, kwargs), name=name, parent=self)
2010
2011
2012 def __getattr__(self, attr):
2013 if self.name is None:
2014 return _Call(name=attr, from_kall=False)
2015 name = '%s.%s' % (self.name, attr)
2016 return _Call(name=name, parent=self, from_kall=False)
2017
2018
2019 def __repr__(self):
2020 if not self.from_kall:
2021 name = self.name or 'call'
2022 if name.startswith('()'):
2023 name = 'call%s' % name
2024 return name
2025
2026 if len(self) == 2:
2027 name = 'call'
2028 args, kwargs = self
2029 else:
2030 name, args, kwargs = self
2031 if not name:
2032 name = 'call'
2033 elif not name.startswith('()'):
2034 name = 'call.%s' % name
2035 else:
2036 name = 'call%s' % name
2037 return _format_call_signature(name, args, kwargs)
2038
2039
2040 def call_list(self):
2041 """For a call object that represents multiple calls, `call_list`
2042 returns a list of all the intermediate calls as well as the
2043 final call."""
2044 vals = []
2045 thing = self
2046 while thing is not None:
2047 if thing.from_kall:
2048 vals.append(thing)
2049 thing = thing.parent
2050 return _CallList(reversed(vals))
2051
2052
2053call = _Call(from_kall=False)
2054
2055
2056
2057def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2058 _name=None, **kwargs):
2059 """Create a mock object using another object as a spec. Attributes on the
2060 mock will use the corresponding attribute on the `spec` object as their
2061 spec.
2062
2063 Functions or methods being mocked will have their arguments checked
2064 to check that they are called with the correct signature.
2065
2066 If `spec_set` is True then attempting to set attributes that don't exist
2067 on the spec object will raise an `AttributeError`.
2068
2069 If a class is used as a spec then the return value of the mock (the
2070 instance of the class) will have the same spec. You can use a class as the
2071 spec for an instance object by passing `instance=True`. The returned mock
2072 will only be callable if instances of the mock are callable.
2073
2074 `create_autospec` also takes arbitrary keyword arguments that are passed to
2075 the constructor of the created mock."""
2076 if _is_list(spec):
2077 # can't pass a list instance to the mock constructor as it will be
2078 # interpreted as a list of strings
2079 spec = type(spec)
2080
2081 is_type = isinstance(spec, type)
2082
2083 _kwargs = {'spec': spec}
2084 if spec_set:
2085 _kwargs = {'spec_set': spec}
2086 elif spec is None:
2087 # None we mock with a normal mock without a spec
2088 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002089 if _kwargs and instance:
2090 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002091
2092 _kwargs.update(kwargs)
2093
2094 Klass = MagicMock
2095 if type(spec) in DescriptorTypes:
2096 # descriptors don't have a spec
2097 # because we don't know what type they return
2098 _kwargs = {}
2099 elif not _callable(spec):
2100 Klass = NonCallableMagicMock
2101 elif is_type and instance and not _instance_callable(spec):
2102 Klass = NonCallableMagicMock
2103
Kushal Das484f8a82014-04-16 01:05:50 +05302104 _name = _kwargs.pop('name', _name)
2105
Michael Foord345266a2012-03-14 12:24:34 -07002106 _new_name = _name
2107 if _parent is None:
2108 # for a top level object no _new_name should be set
2109 _new_name = ''
2110
2111 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2112 name=_name, **_kwargs)
2113
2114 if isinstance(spec, FunctionTypes):
2115 # should only happen at the top level because we don't
2116 # recurse for functions
2117 mock = _set_signature(mock, spec)
2118 else:
2119 _check_signature(spec, mock, is_type, instance)
2120
2121 if _parent is not None and not instance:
2122 _parent._mock_children[_name] = mock
2123
2124 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002125 mock.return_value = create_autospec(spec, spec_set, instance=True,
2126 _name='()', _parent=mock)
2127
2128 for entry in dir(spec):
2129 if _is_magic(entry):
2130 # MagicMock already does the useful magic methods for us
2131 continue
2132
Michael Foord345266a2012-03-14 12:24:34 -07002133 # XXXX do we need a better way of getting attributes without
2134 # triggering code execution (?) Probably not - we need the actual
2135 # object to mock it so we would rather trigger a property than mock
2136 # the property descriptor. Likewise we want to mock out dynamically
2137 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002138 # XXXX what about attributes that raise exceptions other than
2139 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002140 # we could be resilient against it, or catch and propagate the
2141 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002142 try:
2143 original = getattr(spec, entry)
2144 except AttributeError:
2145 continue
Michael Foord345266a2012-03-14 12:24:34 -07002146
2147 kwargs = {'spec': original}
2148 if spec_set:
2149 kwargs = {'spec_set': original}
2150
2151 if not isinstance(original, FunctionTypes):
2152 new = _SpecState(original, spec_set, mock, entry, instance)
2153 mock._mock_children[entry] = new
2154 else:
2155 parent = mock
2156 if isinstance(spec, FunctionTypes):
2157 parent = mock.mock
2158
Michael Foord345266a2012-03-14 12:24:34 -07002159 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002160 kwargs['_eat_self'] = skipfirst
2161 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2162 _new_parent=parent,
2163 **kwargs)
2164 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002165 _check_signature(original, new, skipfirst=skipfirst)
2166
2167 # so functions created with _set_signature become instance attributes,
2168 # *plus* their underlying mock exists in _mock_children of the parent
2169 # mock. Adding to _mock_children may be unnecessary where we are also
2170 # setting as an instance attribute?
2171 if isinstance(new, FunctionTypes):
2172 setattr(mock, entry, new)
2173
2174 return mock
2175
2176
2177def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002178 """
2179 Return whether we should skip the first argument on spec's `entry`
2180 attribute.
2181 """
Michael Foord345266a2012-03-14 12:24:34 -07002182 if not isinstance(spec, type):
2183 if entry in getattr(spec, '__dict__', {}):
2184 # instance attribute - shouldn't skip
2185 return False
Michael Foord345266a2012-03-14 12:24:34 -07002186 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002187
2188 for klass in spec.__mro__:
2189 result = klass.__dict__.get(entry, DEFAULT)
2190 if result is DEFAULT:
2191 continue
2192 if isinstance(result, (staticmethod, classmethod)):
2193 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002194 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2195 # Normal method => skip if looked up on type
2196 # (if looked up on instance, self is already skipped)
2197 return is_type
2198 else:
2199 return False
Michael Foord345266a2012-03-14 12:24:34 -07002200
2201 # shouldn't get here unless function is a dynamically provided attribute
2202 # XXXX untested behaviour
2203 return is_type
2204
2205
2206def _get_class(obj):
2207 try:
2208 return obj.__class__
2209 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002210 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002211 return type(obj)
2212
2213
2214class _SpecState(object):
2215
2216 def __init__(self, spec, spec_set=False, parent=None,
2217 name=None, ids=None, instance=False):
2218 self.spec = spec
2219 self.ids = ids
2220 self.spec_set = spec_set
2221 self.parent = parent
2222 self.instance = instance
2223 self.name = name
2224
2225
2226FunctionTypes = (
2227 # python function
2228 type(create_autospec),
2229 # instance method
2230 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002231)
2232
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002233MethodWrapperTypes = (
2234 type(ANY.__eq__.__get__),
2235)
2236
Michael Foord345266a2012-03-14 12:24:34 -07002237
Michael Foorda74561a2012-03-25 19:03:13 +01002238file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002239
Michael Foord04cbe0c2013-03-19 17:22:51 -07002240def _iterate_read_data(read_data):
2241 # Helper for mock_open:
2242 # Retrieve lines from read_data via a generator so that separate calls to
2243 # readline, read, and readlines are properly interleaved
2244 data_as_list = ['{}\n'.format(l) for l in read_data.split('\n')]
2245
2246 if data_as_list[-1] == '\n':
2247 # If the last line ended in a newline, the list comprehension will have an
2248 # extra entry that's just a newline. Remove this.
2249 data_as_list = data_as_list[:-1]
2250 else:
2251 # If there wasn't an extra newline by itself, then the file being
2252 # emulated doesn't have a newline to end the last line remove the
2253 # newline that our naive format() added
2254 data_as_list[-1] = data_as_list[-1][:-1]
2255
2256 for line in data_as_list:
2257 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002258
2259def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002260 """
2261 A helper function to create a mock to replace the use of `open`. It works
2262 for `open` called directly or used as a context manager.
2263
2264 The `mock` argument is the mock object to configure. If `None` (the
2265 default) then a `MagicMock` will be created for you, with the API limited
2266 to methods or attributes available on standard file handles.
2267
Michael Foord04cbe0c2013-03-19 17:22:51 -07002268 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2269 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002270 """
Michael Foord04cbe0c2013-03-19 17:22:51 -07002271 def _readlines_side_effect(*args, **kwargs):
2272 if handle.readlines.return_value is not None:
2273 return handle.readlines.return_value
2274 return list(_data)
2275
2276 def _read_side_effect(*args, **kwargs):
2277 if handle.read.return_value is not None:
2278 return handle.read.return_value
2279 return ''.join(_data)
2280
2281 def _readline_side_effect():
2282 if handle.readline.return_value is not None:
2283 while True:
2284 yield handle.readline.return_value
2285 for line in _data:
2286 yield line
2287
2288
Michael Foorda74561a2012-03-25 19:03:13 +01002289 global file_spec
2290 if file_spec is None:
2291 import _io
2292 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2293
Michael Foord345266a2012-03-14 12:24:34 -07002294 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002295 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002296
2297 handle = MagicMock(spec=file_spec)
Michael Foord345266a2012-03-14 12:24:34 -07002298 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002299
2300 _data = _iterate_read_data(read_data)
2301
2302 handle.write.return_value = None
2303 handle.read.return_value = None
2304 handle.readline.return_value = None
2305 handle.readlines.return_value = None
2306
2307 handle.read.side_effect = _read_side_effect
2308 handle.readline.side_effect = _readline_side_effect()
2309 handle.readlines.side_effect = _readlines_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002310
2311 mock.return_value = handle
2312 return mock
2313
2314
2315class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002316 """
2317 A mock intended to be used as a property, or other descriptor, on a class.
2318 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2319 a return value when it is fetched.
2320
2321 Fetching a `PropertyMock` instance from an object calls the mock, with
2322 no args. Setting it calls the mock with the value being set.
2323 """
Michael Foordc2870622012-04-13 16:57:22 +01002324 def _get_child_mock(self, **kwargs):
2325 return MagicMock(**kwargs)
2326
Michael Foord345266a2012-03-14 12:24:34 -07002327 def __get__(self, obj, obj_type):
2328 return self()
2329 def __set__(self, obj, val):
2330 self(val)