blob: 8b765034293afc544df20869bec9c8e942f40bc1 [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
346
347
348class Base(object):
349 _mock_return_value = DEFAULT
350 _mock_side_effect = None
351 def __init__(self, *args, **kwargs):
352 pass
353
354
355
356class NonCallableMock(Base):
357 """A non-callable version of `Mock`"""
358
359 def __new__(cls, *args, **kw):
360 # every instance has its own class
361 # so we can create magic methods on the
362 # class without stomping on other mocks
363 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
364 instance = object.__new__(new)
365 return instance
366
367
368 def __init__(
369 self, spec=None, wraps=None, name=None, spec_set=None,
370 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100371 _spec_as_instance=False, _eat_self=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700372 ):
373 if _new_parent is None:
374 _new_parent = parent
375
376 __dict__ = self.__dict__
377 __dict__['_mock_parent'] = parent
378 __dict__['_mock_name'] = name
379 __dict__['_mock_new_name'] = _new_name
380 __dict__['_mock_new_parent'] = _new_parent
381
382 if spec_set is not None:
383 spec = spec_set
384 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100385 if _eat_self is None:
386 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700387
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100388 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700389
390 __dict__['_mock_children'] = {}
391 __dict__['_mock_wraps'] = wraps
392 __dict__['_mock_delegate'] = None
393
394 __dict__['_mock_called'] = False
395 __dict__['_mock_call_args'] = None
396 __dict__['_mock_call_count'] = 0
397 __dict__['_mock_call_args_list'] = _CallList()
398 __dict__['_mock_mock_calls'] = _CallList()
399
400 __dict__['method_calls'] = _CallList()
401
402 if kwargs:
403 self.configure_mock(**kwargs)
404
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000405 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700406 spec, wraps, name, spec_set, parent,
407 _spec_state
408 )
409
410
411 def attach_mock(self, mock, attribute):
412 """
413 Attach a mock as an attribute of this one, replacing its name and
414 parent. Calls to the attached mock will be recorded in the
415 `method_calls` and `mock_calls` attributes of this one."""
416 mock._mock_parent = None
417 mock._mock_new_parent = None
418 mock._mock_name = ''
419 mock._mock_new_name = None
420
421 setattr(self, attribute, mock)
422
423
424 def mock_add_spec(self, spec, spec_set=False):
425 """Add a spec to a mock. `spec` can either be an object or a
426 list of strings. Only attributes on the `spec` can be fetched as
427 attributes from the mock.
428
429 If `spec_set` is True then only attributes on the spec can be set."""
430 self._mock_add_spec(spec, spec_set)
431
432
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100433 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
434 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700435 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100436 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700437
438 if spec is not None and not _is_list(spec):
439 if isinstance(spec, type):
440 _spec_class = spec
441 else:
442 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100443 res = _get_signature_object(spec,
444 _spec_as_instance, _eat_self)
445 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700446
447 spec = dir(spec)
448
449 __dict__ = self.__dict__
450 __dict__['_spec_class'] = _spec_class
451 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100452 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700453 __dict__['_mock_methods'] = spec
454
455
456 def __get_return_value(self):
457 ret = self._mock_return_value
458 if self._mock_delegate is not None:
459 ret = self._mock_delegate.return_value
460
461 if ret is DEFAULT:
462 ret = self._get_child_mock(
463 _new_parent=self, _new_name='()'
464 )
465 self.return_value = ret
466 return ret
467
468
469 def __set_return_value(self, value):
470 if self._mock_delegate is not None:
471 self._mock_delegate.return_value = value
472 else:
473 self._mock_return_value = value
474 _check_and_set_parent(self, value, None, '()')
475
476 __return_value_doc = "The value to be returned when the mock is called."
477 return_value = property(__get_return_value, __set_return_value,
478 __return_value_doc)
479
480
481 @property
482 def __class__(self):
483 if self._spec_class is None:
484 return type(self)
485 return self._spec_class
486
487 called = _delegating_property('called')
488 call_count = _delegating_property('call_count')
489 call_args = _delegating_property('call_args')
490 call_args_list = _delegating_property('call_args_list')
491 mock_calls = _delegating_property('mock_calls')
492
493
494 def __get_side_effect(self):
495 delegated = self._mock_delegate
496 if delegated is None:
497 return self._mock_side_effect
498 return delegated.side_effect
499
500 def __set_side_effect(self, value):
501 value = _try_iter(value)
502 delegated = self._mock_delegate
503 if delegated is None:
504 self._mock_side_effect = value
505 else:
506 delegated.side_effect = value
507
508 side_effect = property(__get_side_effect, __set_side_effect)
509
510
511 def reset_mock(self):
512 "Restore the mock object to its initial state."
513 self.called = False
514 self.call_args = None
515 self.call_count = 0
516 self.mock_calls = _CallList()
517 self.call_args_list = _CallList()
518 self.method_calls = _CallList()
519
520 for child in self._mock_children.values():
Michael Foord75963642012-06-09 17:31:59 +0100521 if isinstance(child, _SpecState):
522 continue
Michael Foord345266a2012-03-14 12:24:34 -0700523 child.reset_mock()
524
525 ret = self._mock_return_value
526 if _is_instance_mock(ret) and ret is not self:
527 ret.reset_mock()
528
529
530 def configure_mock(self, **kwargs):
531 """Set attributes on the mock through keyword arguments.
532
533 Attributes plus return values and side effects can be set on child
534 mocks using standard dot notation and unpacking a dictionary in the
535 method call:
536
537 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
538 >>> mock.configure_mock(**attrs)"""
539 for arg, val in sorted(kwargs.items(),
540 # we sort on the number of dots so that
541 # attributes are set before we set attributes on
542 # attributes
543 key=lambda entry: entry[0].count('.')):
544 args = arg.split('.')
545 final = args.pop()
546 obj = self
547 for entry in args:
548 obj = getattr(obj, entry)
549 setattr(obj, final, val)
550
551
552 def __getattr__(self, name):
553 if name == '_mock_methods':
554 raise AttributeError(name)
555 elif self._mock_methods is not None:
556 if name not in self._mock_methods or name in _all_magics:
557 raise AttributeError("Mock object has no attribute %r" % name)
558 elif _is_magic(name):
559 raise AttributeError(name)
560
561 result = self._mock_children.get(name)
562 if result is _deleted:
563 raise AttributeError(name)
564 elif result is None:
565 wraps = None
566 if self._mock_wraps is not None:
567 # XXXX should we get the attribute without triggering code
568 # execution?
569 wraps = getattr(self._mock_wraps, name)
570
571 result = self._get_child_mock(
572 parent=self, name=name, wraps=wraps, _new_name=name,
573 _new_parent=self
574 )
575 self._mock_children[name] = result
576
577 elif isinstance(result, _SpecState):
578 result = create_autospec(
579 result.spec, result.spec_set, result.instance,
580 result.parent, result.name
581 )
582 self._mock_children[name] = result
583
584 return result
585
586
587 def __repr__(self):
588 _name_list = [self._mock_new_name]
589 _parent = self._mock_new_parent
590 last = self
591
592 dot = '.'
593 if _name_list == ['()']:
594 dot = ''
595 seen = set()
596 while _parent is not None:
597 last = _parent
598
599 _name_list.append(_parent._mock_new_name + dot)
600 dot = '.'
601 if _parent._mock_new_name == '()':
602 dot = ''
603
604 _parent = _parent._mock_new_parent
605
606 # use ids here so as not to call __hash__ on the mocks
607 if id(_parent) in seen:
608 break
609 seen.add(id(_parent))
610
611 _name_list = list(reversed(_name_list))
612 _first = last._mock_name or 'mock'
613 if len(_name_list) > 1:
614 if _name_list[1] not in ('()', '().'):
615 _first += '.'
616 _name_list[0] = _first
617 name = ''.join(_name_list)
618
619 name_string = ''
620 if name not in ('mock', 'mock.'):
621 name_string = ' name=%r' % name
622
623 spec_string = ''
624 if self._spec_class is not None:
625 spec_string = ' spec=%r'
626 if self._spec_set:
627 spec_string = ' spec_set=%r'
628 spec_string = spec_string % self._spec_class.__name__
629 return "<%s%s%s id='%s'>" % (
630 type(self).__name__,
631 name_string,
632 spec_string,
633 id(self)
634 )
635
636
637 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700638 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100639 if not FILTER_DIR:
640 return object.__dir__(self)
641
Michael Foord345266a2012-03-14 12:24:34 -0700642 extras = self._mock_methods or []
643 from_type = dir(type(self))
644 from_dict = list(self.__dict__)
645
Michael Foord313f85f2012-03-25 18:16:07 +0100646 from_type = [e for e in from_type if not e.startswith('_')]
647 from_dict = [e for e in from_dict if not e.startswith('_') or
648 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700649 return sorted(set(extras + from_type + from_dict +
650 list(self._mock_children)))
651
652
653 def __setattr__(self, name, value):
654 if name in _allowed_names:
655 # property setters go through here
656 return object.__setattr__(self, name, value)
657 elif (self._spec_set and self._mock_methods is not None and
658 name not in self._mock_methods and
659 name not in self.__dict__):
660 raise AttributeError("Mock object has no attribute '%s'" % name)
661 elif name in _unsupported_magics:
662 msg = 'Attempting to set unsupported magic method %r.' % name
663 raise AttributeError(msg)
664 elif name in _all_magics:
665 if self._mock_methods is not None and name not in self._mock_methods:
666 raise AttributeError("Mock object has no attribute '%s'" % name)
667
668 if not _is_instance_mock(value):
669 setattr(type(self), name, _get_method(name, value))
670 original = value
671 value = lambda *args, **kw: original(self, *args, **kw)
672 else:
673 # only set _new_name and not name so that mock_calls is tracked
674 # but not method calls
675 _check_and_set_parent(self, value, None, name)
676 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100677 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700678 elif name == '__class__':
679 self._spec_class = value
680 return
681 else:
682 if _check_and_set_parent(self, value, name, name):
683 self._mock_children[name] = value
684 return object.__setattr__(self, name, value)
685
686
687 def __delattr__(self, name):
688 if name in _all_magics and name in type(self).__dict__:
689 delattr(type(self), name)
690 if name not in self.__dict__:
691 # for magic methods that are still MagicProxy objects and
692 # not set on the instance itself
693 return
694
695 if name in self.__dict__:
696 object.__delattr__(self, name)
697
698 obj = self._mock_children.get(name, _missing)
699 if obj is _deleted:
700 raise AttributeError(name)
701 if obj is not _missing:
702 del self._mock_children[name]
703 self._mock_children[name] = _deleted
704
705
Michael Foord345266a2012-03-14 12:24:34 -0700706 def _format_mock_call_signature(self, args, kwargs):
707 name = self._mock_name or 'mock'
708 return _format_call_signature(name, args, kwargs)
709
710
711 def _format_mock_failure_message(self, args, kwargs):
712 message = 'Expected call: %s\nActual call: %s'
713 expected_string = self._format_mock_call_signature(args, kwargs)
714 call_args = self.call_args
715 if len(call_args) == 3:
716 call_args = call_args[1:]
717 actual_string = self._format_mock_call_signature(*call_args)
718 return message % (expected_string, actual_string)
719
720
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100721 def _call_matcher(self, _call):
722 """
723 Given a call (or simply a (args, kwargs) tuple), return a
724 comparison key suitable for matching with other calls.
725 This is a best effort method which relies on the spec's signature,
726 if available, or falls back on the arguments themselves.
727 """
728 sig = self._spec_signature
729 if sig is not None:
730 if len(_call) == 2:
731 name = ''
732 args, kwargs = _call
733 else:
734 name, args, kwargs = _call
735 try:
736 return name, sig.bind(*args, **kwargs)
737 except TypeError as e:
738 return e.with_traceback(None)
739 else:
740 return _call
741
742
Michael Foord345266a2012-03-14 12:24:34 -0700743 def assert_called_with(_mock_self, *args, **kwargs):
744 """assert that the mock was called with the specified arguments.
745
746 Raises an AssertionError if the args and keyword args passed in are
747 different to the last call to the mock."""
748 self = _mock_self
749 if self.call_args is None:
750 expected = self._format_mock_call_signature(args, kwargs)
751 raise AssertionError('Expected call: %s\nNot called' % (expected,))
752
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100753 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700754 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100755 return msg
756 expected = self._call_matcher((args, kwargs))
757 actual = self._call_matcher(self.call_args)
758 if expected != actual:
759 cause = expected if isinstance(expected, Exception) else None
760 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700761
762
763 def assert_called_once_with(_mock_self, *args, **kwargs):
764 """assert that the mock was called exactly once and with the specified
765 arguments."""
766 self = _mock_self
767 if not self.call_count == 1:
Michael Foord28d591c2012-09-28 16:15:22 +0100768 msg = ("Expected '%s' to be called once. Called %s times." %
769 (self._mock_name or 'mock', self.call_count))
Michael Foord345266a2012-03-14 12:24:34 -0700770 raise AssertionError(msg)
771 return self.assert_called_with(*args, **kwargs)
772
773
774 def assert_has_calls(self, calls, any_order=False):
775 """assert the mock has been called with the specified calls.
776 The `mock_calls` list is checked for the calls.
777
778 If `any_order` is False (the default) then the calls must be
779 sequential. There can be extra calls before or after the
780 specified calls.
781
782 If `any_order` is True then the calls can be in any order, but
783 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100784 expected = [self._call_matcher(c) for c in calls]
785 cause = expected if isinstance(expected, Exception) else None
786 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700787 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100788 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700789 raise AssertionError(
790 'Calls not found.\nExpected: %r\n'
791 'Actual: %r' % (calls, self.mock_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100792 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700793 return
794
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100795 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700796
797 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100798 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700799 try:
800 all_calls.remove(kall)
801 except ValueError:
802 not_found.append(kall)
803 if not_found:
804 raise AssertionError(
805 '%r not all found in call list' % (tuple(not_found),)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100806 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700807
808
809 def assert_any_call(self, *args, **kwargs):
810 """assert the mock has been called with the specified arguments.
811
812 The assert passes if the mock has *ever* been called, unlike
813 `assert_called_with` and `assert_called_once_with` that only pass if
814 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100815 expected = self._call_matcher((args, kwargs))
816 actual = [self._call_matcher(c) for c in self.call_args_list]
817 if expected not in actual:
818 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700819 expected_string = self._format_mock_call_signature(args, kwargs)
820 raise AssertionError(
821 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100822 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700823
824
825 def _get_child_mock(self, **kw):
826 """Create the child mocks for attributes and return value.
827 By default child mocks will be the same type as the parent.
828 Subclasses of Mock may want to override this to customize the way
829 child mocks are made.
830
831 For non-callable mocks the callable variant will be used (rather than
832 any custom subclass)."""
833 _type = type(self)
834 if not issubclass(_type, CallableMixin):
835 if issubclass(_type, NonCallableMagicMock):
836 klass = MagicMock
837 elif issubclass(_type, NonCallableMock) :
838 klass = Mock
839 else:
840 klass = _type.__mro__[1]
841 return klass(**kw)
842
843
844
845def _try_iter(obj):
846 if obj is None:
847 return obj
848 if _is_exception(obj):
849 return obj
850 if _callable(obj):
851 return obj
852 try:
853 return iter(obj)
854 except TypeError:
855 # XXXX backwards compatibility
856 # but this will blow up on first call - so maybe we should fail early?
857 return obj
858
859
860
861class CallableMixin(Base):
862
863 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
864 wraps=None, name=None, spec_set=None, parent=None,
865 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
866 self.__dict__['_mock_return_value'] = return_value
867
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000868 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700869 spec, wraps, name, spec_set, parent,
870 _spec_state, _new_name, _new_parent, **kwargs
871 )
872
873 self.side_effect = side_effect
874
875
876 def _mock_check_sig(self, *args, **kwargs):
877 # stub method that can be replaced with one with a specific signature
878 pass
879
880
881 def __call__(_mock_self, *args, **kwargs):
882 # can't use self in-case a function / method we are mocking uses self
883 # in the signature
884 _mock_self._mock_check_sig(*args, **kwargs)
885 return _mock_self._mock_call(*args, **kwargs)
886
887
888 def _mock_call(_mock_self, *args, **kwargs):
889 self = _mock_self
890 self.called = True
891 self.call_count += 1
Michael Foord345266a2012-03-14 12:24:34 -0700892 _new_name = self._mock_new_name
893 _new_parent = self._mock_new_parent
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100894
895 _call = _Call((args, kwargs), two=True)
896 self.call_args = _call
897 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700898 self.mock_calls.append(_Call(('', args, kwargs)))
899
900 seen = set()
901 skip_next_dot = _new_name == '()'
902 do_method_calls = self._mock_parent is not None
903 name = self._mock_name
904 while _new_parent is not None:
905 this_mock_call = _Call((_new_name, args, kwargs))
906 if _new_parent._mock_new_name:
907 dot = '.'
908 if skip_next_dot:
909 dot = ''
910
911 skip_next_dot = False
912 if _new_parent._mock_new_name == '()':
913 skip_next_dot = True
914
915 _new_name = _new_parent._mock_new_name + dot + _new_name
916
917 if do_method_calls:
918 if _new_name == name:
919 this_method_call = this_mock_call
920 else:
921 this_method_call = _Call((name, args, kwargs))
922 _new_parent.method_calls.append(this_method_call)
923
924 do_method_calls = _new_parent._mock_parent is not None
925 if do_method_calls:
926 name = _new_parent._mock_name + '.' + name
927
928 _new_parent.mock_calls.append(this_mock_call)
929 _new_parent = _new_parent._mock_new_parent
930
931 # use ids here so as not to call __hash__ on the mocks
932 _new_parent_id = id(_new_parent)
933 if _new_parent_id in seen:
934 break
935 seen.add(_new_parent_id)
936
937 ret_val = DEFAULT
938 effect = self.side_effect
939 if effect is not None:
940 if _is_exception(effect):
941 raise effect
942
943 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +0100944 result = next(effect)
945 if _is_exception(result):
946 raise result
Andrew Svetlov8b2cd752013-04-07 16:42:24 +0300947 if result is DEFAULT:
948 result = self.return_value
Michael Foord2cd48732012-04-21 15:52:11 +0100949 return result
Michael Foord345266a2012-03-14 12:24:34 -0700950
951 ret_val = effect(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700952
953 if (self._mock_wraps is not None and
954 self._mock_return_value is DEFAULT):
955 return self._mock_wraps(*args, **kwargs)
956 if ret_val is DEFAULT:
957 ret_val = self.return_value
958 return ret_val
959
960
961
962class Mock(CallableMixin, NonCallableMock):
963 """
964 Create a new `Mock` object. `Mock` takes several optional arguments
965 that specify the behaviour of the Mock object:
966
967 * `spec`: This can be either a list of strings or an existing object (a
968 class or instance) that acts as the specification for the mock object. If
969 you pass in an object then a list of strings is formed by calling dir on
970 the object (excluding unsupported magic attributes and methods). Accessing
971 any attribute not in this list will raise an `AttributeError`.
972
973 If `spec` is an object (rather than a list of strings) then
974 `mock.__class__` returns the class of the spec object. This allows mocks
975 to pass `isinstance` tests.
976
977 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
978 or get an attribute on the mock that isn't on the object passed as
979 `spec_set` will raise an `AttributeError`.
980
981 * `side_effect`: A function to be called whenever the Mock is called. See
982 the `side_effect` attribute. Useful for raising exceptions or
983 dynamically changing return values. The function is called with the same
984 arguments as the mock, and unless it returns `DEFAULT`, the return
985 value of this function is used as the return value.
986
Michael Foord2cd48732012-04-21 15:52:11 +0100987 If `side_effect` is an iterable then each call to the mock will return
988 the next value from the iterable. If any of the members of the iterable
989 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -0700990
Michael Foord345266a2012-03-14 12:24:34 -0700991 * `return_value`: The value returned when the mock is called. By default
992 this is a new Mock (created on first access). See the
993 `return_value` attribute.
994
Michael Foord0682a0c2012-04-13 20:51:20 +0100995 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
996 calling the Mock will pass the call through to the wrapped object
997 (returning the real result). Attribute access on the mock will return a
998 Mock object that wraps the corresponding attribute of the wrapped object
999 (so attempting to access an attribute that doesn't exist will raise an
1000 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001001
1002 If the mock has an explicit `return_value` set then calls are not passed
1003 to the wrapped object and the `return_value` is returned instead.
1004
1005 * `name`: If the mock has a name then it will be used in the repr of the
1006 mock. This can be useful for debugging. The name is propagated to child
1007 mocks.
1008
1009 Mocks can also be called with arbitrary keyword arguments. These will be
1010 used to set attributes on the mock after it is created.
1011 """
1012
1013
1014
1015def _dot_lookup(thing, comp, import_path):
1016 try:
1017 return getattr(thing, comp)
1018 except AttributeError:
1019 __import__(import_path)
1020 return getattr(thing, comp)
1021
1022
1023def _importer(target):
1024 components = target.split('.')
1025 import_path = components.pop(0)
1026 thing = __import__(import_path)
1027
1028 for comp in components:
1029 import_path += ".%s" % comp
1030 thing = _dot_lookup(thing, comp, import_path)
1031 return thing
1032
1033
1034def _is_started(patcher):
1035 # XXXX horrible
1036 return hasattr(patcher, 'is_local')
1037
1038
1039class _patch(object):
1040
1041 attribute_name = None
Michael Foordf7c41582012-06-10 20:36:32 +01001042 _active_patches = set()
Michael Foord345266a2012-03-14 12:24:34 -07001043
1044 def __init__(
1045 self, getter, attribute, new, spec, create,
1046 spec_set, autospec, new_callable, kwargs
1047 ):
1048 if new_callable is not None:
1049 if new is not DEFAULT:
1050 raise ValueError(
1051 "Cannot use 'new' and 'new_callable' together"
1052 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001053 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001054 raise ValueError(
1055 "Cannot use 'autospec' and 'new_callable' together"
1056 )
1057
1058 self.getter = getter
1059 self.attribute = attribute
1060 self.new = new
1061 self.new_callable = new_callable
1062 self.spec = spec
1063 self.create = create
1064 self.has_local = False
1065 self.spec_set = spec_set
1066 self.autospec = autospec
1067 self.kwargs = kwargs
1068 self.additional_patchers = []
1069
1070
1071 def copy(self):
1072 patcher = _patch(
1073 self.getter, self.attribute, self.new, self.spec,
1074 self.create, self.spec_set,
1075 self.autospec, self.new_callable, self.kwargs
1076 )
1077 patcher.attribute_name = self.attribute_name
1078 patcher.additional_patchers = [
1079 p.copy() for p in self.additional_patchers
1080 ]
1081 return patcher
1082
1083
1084 def __call__(self, func):
1085 if isinstance(func, type):
1086 return self.decorate_class(func)
1087 return self.decorate_callable(func)
1088
1089
1090 def decorate_class(self, klass):
1091 for attr in dir(klass):
1092 if not attr.startswith(patch.TEST_PREFIX):
1093 continue
1094
1095 attr_value = getattr(klass, attr)
1096 if not hasattr(attr_value, "__call__"):
1097 continue
1098
1099 patcher = self.copy()
1100 setattr(klass, attr, patcher(attr_value))
1101 return klass
1102
1103
1104 def decorate_callable(self, func):
1105 if hasattr(func, 'patchings'):
1106 func.patchings.append(self)
1107 return func
1108
1109 @wraps(func)
1110 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001111 extra_args = []
1112 entered_patchers = []
1113
Michael Foord50a8c0e2012-03-25 18:57:58 +01001114 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001115 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001116 for patching in patched.patchings:
1117 arg = patching.__enter__()
1118 entered_patchers.append(patching)
1119 if patching.attribute_name is not None:
1120 keywargs.update(arg)
1121 elif patching.new is DEFAULT:
1122 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001123
Michael Foordd7c65e22012-03-14 14:56:54 -07001124 args += tuple(extra_args)
1125 return func(*args, **keywargs)
1126 except:
1127 if (patching not in entered_patchers and
1128 _is_started(patching)):
1129 # the patcher may have been started, but an exception
1130 # raised whilst entering one of its additional_patchers
1131 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001132 # Pass the exception to __exit__
1133 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001134 # re-raise the exception
1135 raise
Michael Foord345266a2012-03-14 12:24:34 -07001136 finally:
1137 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001138 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001139
1140 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001141 return patched
1142
1143
1144 def get_original(self):
1145 target = self.getter()
1146 name = self.attribute
1147
1148 original = DEFAULT
1149 local = False
1150
1151 try:
1152 original = target.__dict__[name]
1153 except (AttributeError, KeyError):
1154 original = getattr(target, name, DEFAULT)
1155 else:
1156 local = True
1157
1158 if not self.create and original is DEFAULT:
1159 raise AttributeError(
1160 "%s does not have the attribute %r" % (target, name)
1161 )
1162 return original, local
1163
1164
1165 def __enter__(self):
1166 """Perform the patch."""
1167 new, spec, spec_set = self.new, self.spec, self.spec_set
1168 autospec, kwargs = self.autospec, self.kwargs
1169 new_callable = self.new_callable
1170 self.target = self.getter()
1171
Michael Foord50a8c0e2012-03-25 18:57:58 +01001172 # normalise False to None
1173 if spec is False:
1174 spec = None
1175 if spec_set is False:
1176 spec_set = None
1177 if autospec is False:
1178 autospec = None
1179
1180 if spec is not None and autospec is not None:
1181 raise TypeError("Can't specify spec and autospec")
1182 if ((spec is not None or autospec is not None) and
1183 spec_set not in (True, None)):
1184 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1185
Michael Foord345266a2012-03-14 12:24:34 -07001186 original, local = self.get_original()
1187
Michael Foord50a8c0e2012-03-25 18:57:58 +01001188 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001189 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001190 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001191 # set spec to the object we are replacing
1192 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001193 if spec_set is True:
1194 spec_set = original
1195 spec = None
1196 elif spec is not None:
1197 if spec_set is True:
1198 spec_set = spec
1199 spec = None
1200 elif spec_set is True:
1201 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001202
Michael Foord50a8c0e2012-03-25 18:57:58 +01001203 if spec is not None or spec_set is not None:
1204 if original is DEFAULT:
1205 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001206 if isinstance(original, type):
1207 # If we're patching out a class and there is a spec
1208 inherit = True
1209
1210 Klass = MagicMock
1211 _kwargs = {}
1212 if new_callable is not None:
1213 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001214 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001215 this_spec = spec
1216 if spec_set is not None:
1217 this_spec = spec_set
1218 if _is_list(this_spec):
1219 not_callable = '__call__' not in this_spec
1220 else:
1221 not_callable = not callable(this_spec)
1222 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001223 Klass = NonCallableMagicMock
1224
1225 if spec is not None:
1226 _kwargs['spec'] = spec
1227 if spec_set is not None:
1228 _kwargs['spec_set'] = spec_set
1229
1230 # add a name to mocks
1231 if (isinstance(Klass, type) and
1232 issubclass(Klass, NonCallableMock) and self.attribute):
1233 _kwargs['name'] = self.attribute
1234
1235 _kwargs.update(kwargs)
1236 new = Klass(**_kwargs)
1237
1238 if inherit and _is_instance_mock(new):
1239 # we can only tell if the instance should be callable if the
1240 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001241 this_spec = spec
1242 if spec_set is not None:
1243 this_spec = spec_set
1244 if (not _is_list(this_spec) and not
1245 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001246 Klass = NonCallableMagicMock
1247
1248 _kwargs.pop('name')
1249 new.return_value = Klass(_new_parent=new, _new_name='()',
1250 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001251 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001252 # spec is ignored, new *must* be default, spec_set is treated
1253 # as a boolean. Should we check spec is not None and that spec_set
1254 # is a bool?
1255 if new is not DEFAULT:
1256 raise TypeError(
1257 "autospec creates the mock for you. Can't specify "
1258 "autospec and new."
1259 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001260 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001261 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001262 spec_set = bool(spec_set)
1263 if autospec is True:
1264 autospec = original
1265
1266 new = create_autospec(autospec, spec_set=spec_set,
1267 _name=self.attribute, **kwargs)
1268 elif kwargs:
1269 # can't set keyword args when we aren't creating the mock
1270 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1271 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1272
1273 new_attr = new
1274
1275 self.temp_original = original
1276 self.is_local = local
1277 setattr(self.target, self.attribute, new_attr)
1278 if self.attribute_name is not None:
1279 extra_args = {}
1280 if self.new is DEFAULT:
1281 extra_args[self.attribute_name] = new
1282 for patching in self.additional_patchers:
1283 arg = patching.__enter__()
1284 if patching.new is DEFAULT:
1285 extra_args.update(arg)
1286 return extra_args
1287
1288 return new
1289
1290
Michael Foord50a8c0e2012-03-25 18:57:58 +01001291 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001292 """Undo the patch."""
1293 if not _is_started(self):
1294 raise RuntimeError('stop called on unstarted patcher')
1295
1296 if self.is_local and self.temp_original is not DEFAULT:
1297 setattr(self.target, self.attribute, self.temp_original)
1298 else:
1299 delattr(self.target, self.attribute)
1300 if not self.create and not hasattr(self.target, self.attribute):
1301 # needed for proxy objects like django settings
1302 setattr(self.target, self.attribute, self.temp_original)
1303
1304 del self.temp_original
1305 del self.is_local
1306 del self.target
1307 for patcher in reversed(self.additional_patchers):
1308 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001309 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001310
Michael Foordf7c41582012-06-10 20:36:32 +01001311
1312 def start(self):
1313 """Activate a patch, returning any created mock."""
1314 result = self.__enter__()
1315 self._active_patches.add(self)
1316 return result
1317
1318
1319 def stop(self):
1320 """Stop an active patch."""
1321 self._active_patches.discard(self)
1322 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001323
1324
1325
1326def _get_target(target):
1327 try:
1328 target, attribute = target.rsplit('.', 1)
1329 except (TypeError, ValueError):
1330 raise TypeError("Need a valid target to patch. You supplied: %r" %
1331 (target,))
1332 getter = lambda: _importer(target)
1333 return getter, attribute
1334
1335
1336def _patch_object(
1337 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001338 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001339 new_callable=None, **kwargs
1340 ):
1341 """
Michael Foord345266a2012-03-14 12:24:34 -07001342 patch the named member (`attribute`) on an object (`target`) with a mock
1343 object.
1344
1345 `patch.object` can be used as a decorator, class decorator or a context
1346 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1347 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1348 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1349 the mock object it creates.
1350
1351 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1352 for choosing which methods to wrap.
1353 """
1354 getter = lambda: target
1355 return _patch(
1356 getter, attribute, new, spec, create,
1357 spec_set, autospec, new_callable, kwargs
1358 )
1359
1360
Michael Foord50a8c0e2012-03-25 18:57:58 +01001361def _patch_multiple(target, spec=None, create=False, spec_set=None,
1362 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001363 """Perform multiple patches in a single call. It takes the object to be
1364 patched (either as an object or a string to fetch the object by importing)
1365 and keyword arguments for the patches::
1366
1367 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1368 ...
1369
1370 Use `DEFAULT` as the value if you want `patch.multiple` to create
1371 mocks for you. In this case the created mocks are passed into a decorated
1372 function by keyword, and a dictionary is returned when `patch.multiple` is
1373 used as a context manager.
1374
1375 `patch.multiple` can be used as a decorator, class decorator or a context
1376 manager. The arguments `spec`, `spec_set`, `create`,
1377 `autospec` and `new_callable` have the same meaning as for `patch`. These
1378 arguments will be applied to *all* patches done by `patch.multiple`.
1379
1380 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1381 for choosing which methods to wrap.
1382 """
1383 if type(target) is str:
1384 getter = lambda: _importer(target)
1385 else:
1386 getter = lambda: target
1387
1388 if not kwargs:
1389 raise ValueError(
1390 'Must supply at least one keyword argument with patch.multiple'
1391 )
1392 # need to wrap in a list for python 3, where items is a view
1393 items = list(kwargs.items())
1394 attribute, new = items[0]
1395 patcher = _patch(
1396 getter, attribute, new, spec, create, spec_set,
1397 autospec, new_callable, {}
1398 )
1399 patcher.attribute_name = attribute
1400 for attribute, new in items[1:]:
1401 this_patcher = _patch(
1402 getter, attribute, new, spec, create, spec_set,
1403 autospec, new_callable, {}
1404 )
1405 this_patcher.attribute_name = attribute
1406 patcher.additional_patchers.append(this_patcher)
1407 return patcher
1408
1409
1410def patch(
1411 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001412 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001413 ):
1414 """
1415 `patch` acts as a function decorator, class decorator or a context
1416 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001417 is patched with a `new` object. When the function/with statement exits
1418 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001419
Michael Foord54b3db82012-03-28 15:08:08 +01001420 If `new` is omitted, then the target is replaced with a
1421 `MagicMock`. If `patch` is used as a decorator and `new` is
1422 omitted, the created mock is passed in as an extra argument to the
1423 decorated function. If `patch` is used as a context manager the created
1424 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001425
Michael Foord54b3db82012-03-28 15:08:08 +01001426 `target` should be a string in the form `'package.module.ClassName'`. The
1427 `target` is imported and the specified object replaced with the `new`
1428 object, so the `target` must be importable from the environment you are
1429 calling `patch` from. The target is imported when the decorated function
1430 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001431
1432 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1433 if patch is creating one for you.
1434
1435 In addition you can pass `spec=True` or `spec_set=True`, which causes
1436 patch to pass in the object being mocked as the spec/spec_set object.
1437
1438 `new_callable` allows you to specify a different class, or callable object,
1439 that will be called to create the `new` object. By default `MagicMock` is
1440 used.
1441
1442 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1443 then the mock with be created with a spec from the object being replaced.
1444 All attributes of the mock will also have the spec of the corresponding
1445 attribute of the object being replaced. Methods and functions being
1446 mocked will have their arguments checked and will raise a `TypeError` if
1447 they are called with the wrong signature. For mocks replacing a class,
1448 their return value (the 'instance') will have the same spec as the class.
1449
1450 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1451 arbitrary object as the spec instead of the one being replaced.
1452
1453 By default `patch` will fail to replace attributes that don't exist. If
1454 you pass in `create=True`, and the attribute doesn't exist, patch will
1455 create the attribute for you when the patched function is called, and
1456 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001457 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001458 default because it can be dangerous. With it switched on you can write
1459 passing tests against APIs that don't actually exist!
1460
1461 Patch can be used as a `TestCase` class decorator. It works by
1462 decorating each test method in the class. This reduces the boilerplate
1463 code when your test methods share a common patchings set. `patch` finds
1464 tests by looking for method names that start with `patch.TEST_PREFIX`.
1465 By default this is `test`, which matches the way `unittest` finds tests.
1466 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1467
1468 Patch can be used as a context manager, with the with statement. Here the
1469 patching applies to the indented block after the with statement. If you
1470 use "as" then the patched object will be bound to the name after the
1471 "as"; very useful if `patch` is creating a mock object for you.
1472
1473 `patch` takes arbitrary keyword arguments. These will be passed to
1474 the `Mock` (or `new_callable`) on construction.
1475
1476 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1477 available for alternate use-cases.
1478 """
1479 getter, attribute = _get_target(target)
1480 return _patch(
1481 getter, attribute, new, spec, create,
1482 spec_set, autospec, new_callable, kwargs
1483 )
1484
1485
1486class _patch_dict(object):
1487 """
1488 Patch a dictionary, or dictionary like object, and restore the dictionary
1489 to its original state after the test.
1490
1491 `in_dict` can be a dictionary or a mapping like container. If it is a
1492 mapping then it must at least support getting, setting and deleting items
1493 plus iterating over keys.
1494
1495 `in_dict` can also be a string specifying the name of the dictionary, which
1496 will then be fetched by importing it.
1497
1498 `values` can be a dictionary of values to set in the dictionary. `values`
1499 can also be an iterable of `(key, value)` pairs.
1500
1501 If `clear` is True then the dictionary will be cleared before the new
1502 values are set.
1503
1504 `patch.dict` can also be called with arbitrary keyword arguments to set
1505 values in the dictionary::
1506
1507 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1508 ...
1509
1510 `patch.dict` can be used as a context manager, decorator or class
1511 decorator. When used as a class decorator `patch.dict` honours
1512 `patch.TEST_PREFIX` for choosing which methods to wrap.
1513 """
1514
1515 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1516 if isinstance(in_dict, str):
1517 in_dict = _importer(in_dict)
1518 self.in_dict = in_dict
1519 # support any argument supported by dict(...) constructor
1520 self.values = dict(values)
1521 self.values.update(kwargs)
1522 self.clear = clear
1523 self._original = None
1524
1525
1526 def __call__(self, f):
1527 if isinstance(f, type):
1528 return self.decorate_class(f)
1529 @wraps(f)
1530 def _inner(*args, **kw):
1531 self._patch_dict()
1532 try:
1533 return f(*args, **kw)
1534 finally:
1535 self._unpatch_dict()
1536
1537 return _inner
1538
1539
1540 def decorate_class(self, klass):
1541 for attr in dir(klass):
1542 attr_value = getattr(klass, attr)
1543 if (attr.startswith(patch.TEST_PREFIX) and
1544 hasattr(attr_value, "__call__")):
1545 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1546 decorated = decorator(attr_value)
1547 setattr(klass, attr, decorated)
1548 return klass
1549
1550
1551 def __enter__(self):
1552 """Patch the dict."""
1553 self._patch_dict()
1554
1555
1556 def _patch_dict(self):
1557 values = self.values
1558 in_dict = self.in_dict
1559 clear = self.clear
1560
1561 try:
1562 original = in_dict.copy()
1563 except AttributeError:
1564 # dict like object with no copy method
1565 # must support iteration over keys
1566 original = {}
1567 for key in in_dict:
1568 original[key] = in_dict[key]
1569 self._original = original
1570
1571 if clear:
1572 _clear_dict(in_dict)
1573
1574 try:
1575 in_dict.update(values)
1576 except AttributeError:
1577 # dict like object with no update method
1578 for key in values:
1579 in_dict[key] = values[key]
1580
1581
1582 def _unpatch_dict(self):
1583 in_dict = self.in_dict
1584 original = self._original
1585
1586 _clear_dict(in_dict)
1587
1588 try:
1589 in_dict.update(original)
1590 except AttributeError:
1591 for key in original:
1592 in_dict[key] = original[key]
1593
1594
1595 def __exit__(self, *args):
1596 """Unpatch the dict."""
1597 self._unpatch_dict()
1598 return False
1599
1600 start = __enter__
1601 stop = __exit__
1602
1603
1604def _clear_dict(in_dict):
1605 try:
1606 in_dict.clear()
1607 except AttributeError:
1608 keys = list(in_dict)
1609 for key in keys:
1610 del in_dict[key]
1611
1612
Michael Foordf7c41582012-06-10 20:36:32 +01001613def _patch_stopall():
1614 """Stop all active patches."""
1615 for patch in list(_patch._active_patches):
1616 patch.stop()
1617
1618
Michael Foord345266a2012-03-14 12:24:34 -07001619patch.object = _patch_object
1620patch.dict = _patch_dict
1621patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001622patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001623patch.TEST_PREFIX = 'test'
1624
1625magic_methods = (
1626 "lt le gt ge eq ne "
1627 "getitem setitem delitem "
1628 "len contains iter "
1629 "hash str sizeof "
1630 "enter exit "
1631 "divmod neg pos abs invert "
1632 "complex int float index "
1633 "trunc floor ceil "
1634 "bool next "
1635)
1636
1637numerics = "add sub mul div floordiv mod lshift rshift and xor or pow "
1638inplace = ' '.join('i%s' % n for n in numerics.split())
1639right = ' '.join('r%s' % n for n in numerics.split())
1640
1641# not including __prepare__, __instancecheck__, __subclasscheck__
1642# (as they are metaclass methods)
1643# __del__ is not supported at all as it causes problems if it exists
1644
1645_non_defaults = set('__%s__' % method for method in [
Michael Foord944e02d2012-03-25 23:12:55 +01001646 'get', 'set', 'delete', 'reversed', 'missing', 'reduce', 'reduce_ex',
1647 'getinitargs', 'getnewargs', 'getstate', 'setstate', 'getformat',
1648 'setformat', 'repr', 'dir', 'subclasses', 'format',
Michael Foord345266a2012-03-14 12:24:34 -07001649])
1650
1651
1652def _get_method(name, func):
1653 "Turns a callable object (like a mock) into a real function"
1654 def method(self, *args, **kw):
1655 return func(self, *args, **kw)
1656 method.__name__ = name
1657 return method
1658
1659
1660_magics = set(
1661 '__%s__' % method for method in
1662 ' '.join([magic_methods, numerics, inplace, right]).split()
1663)
1664
1665_all_magics = _magics | _non_defaults
1666
1667_unsupported_magics = set([
1668 '__getattr__', '__setattr__',
1669 '__init__', '__new__', '__prepare__'
1670 '__instancecheck__', '__subclasscheck__',
1671 '__del__'
1672])
1673
1674_calculate_return_value = {
1675 '__hash__': lambda self: object.__hash__(self),
1676 '__str__': lambda self: object.__str__(self),
1677 '__sizeof__': lambda self: object.__sizeof__(self),
1678}
1679
1680_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001681 '__lt__': NotImplemented,
1682 '__gt__': NotImplemented,
1683 '__le__': NotImplemented,
1684 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001685 '__int__': 1,
1686 '__contains__': False,
1687 '__len__': 0,
1688 '__exit__': False,
1689 '__complex__': 1j,
1690 '__float__': 1.0,
1691 '__bool__': True,
1692 '__index__': 1,
1693}
1694
1695
1696def _get_eq(self):
1697 def __eq__(other):
1698 ret_val = self.__eq__._mock_return_value
1699 if ret_val is not DEFAULT:
1700 return ret_val
1701 return self is other
1702 return __eq__
1703
1704def _get_ne(self):
1705 def __ne__(other):
1706 if self.__ne__._mock_return_value is not DEFAULT:
1707 return DEFAULT
1708 return self is not other
1709 return __ne__
1710
1711def _get_iter(self):
1712 def __iter__():
1713 ret_val = self.__iter__._mock_return_value
1714 if ret_val is DEFAULT:
1715 return iter([])
1716 # if ret_val was already an iterator, then calling iter on it should
1717 # return the iterator unchanged
1718 return iter(ret_val)
1719 return __iter__
1720
1721_side_effect_methods = {
1722 '__eq__': _get_eq,
1723 '__ne__': _get_ne,
1724 '__iter__': _get_iter,
1725}
1726
1727
1728
1729def _set_return_value(mock, method, name):
1730 fixed = _return_values.get(name, DEFAULT)
1731 if fixed is not DEFAULT:
1732 method.return_value = fixed
1733 return
1734
1735 return_calulator = _calculate_return_value.get(name)
1736 if return_calulator is not None:
1737 try:
1738 return_value = return_calulator(mock)
1739 except AttributeError:
1740 # XXXX why do we return AttributeError here?
1741 # set it as a side_effect instead?
1742 return_value = AttributeError(name)
1743 method.return_value = return_value
1744 return
1745
1746 side_effector = _side_effect_methods.get(name)
1747 if side_effector is not None:
1748 method.side_effect = side_effector(mock)
1749
1750
1751
1752class MagicMixin(object):
1753 def __init__(self, *args, **kw):
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001754 _safe_super(MagicMixin, self).__init__(*args, **kw)
Michael Foord345266a2012-03-14 12:24:34 -07001755 self._mock_set_magics()
1756
1757
1758 def _mock_set_magics(self):
1759 these_magics = _magics
1760
1761 if self._mock_methods is not None:
1762 these_magics = _magics.intersection(self._mock_methods)
1763
1764 remove_magics = set()
1765 remove_magics = _magics - these_magics
1766
1767 for entry in remove_magics:
1768 if entry in type(self).__dict__:
1769 # remove unneeded magic methods
1770 delattr(self, entry)
1771
1772 # don't overwrite existing attributes if called a second time
1773 these_magics = these_magics - set(type(self).__dict__)
1774
1775 _type = type(self)
1776 for entry in these_magics:
1777 setattr(_type, entry, MagicProxy(entry, self))
1778
1779
1780
1781class NonCallableMagicMock(MagicMixin, NonCallableMock):
1782 """A version of `MagicMock` that isn't callable."""
1783 def mock_add_spec(self, spec, spec_set=False):
1784 """Add a spec to a mock. `spec` can either be an object or a
1785 list of strings. Only attributes on the `spec` can be fetched as
1786 attributes from the mock.
1787
1788 If `spec_set` is True then only attributes on the spec can be set."""
1789 self._mock_add_spec(spec, spec_set)
1790 self._mock_set_magics()
1791
1792
1793
1794class MagicMock(MagicMixin, Mock):
1795 """
1796 MagicMock is a subclass of Mock with default implementations
1797 of most of the magic methods. You can use MagicMock without having to
1798 configure the magic methods yourself.
1799
1800 If you use the `spec` or `spec_set` arguments then *only* magic
1801 methods that exist in the spec will be created.
1802
1803 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1804 """
1805 def mock_add_spec(self, spec, spec_set=False):
1806 """Add a spec to a mock. `spec` can either be an object or a
1807 list of strings. Only attributes on the `spec` can be fetched as
1808 attributes from the mock.
1809
1810 If `spec_set` is True then only attributes on the spec can be set."""
1811 self._mock_add_spec(spec, spec_set)
1812 self._mock_set_magics()
1813
1814
1815
1816class MagicProxy(object):
1817 def __init__(self, name, parent):
1818 self.name = name
1819 self.parent = parent
1820
1821 def __call__(self, *args, **kwargs):
1822 m = self.create_mock()
1823 return m(*args, **kwargs)
1824
1825 def create_mock(self):
1826 entry = self.name
1827 parent = self.parent
1828 m = parent._get_child_mock(name=entry, _new_name=entry,
1829 _new_parent=parent)
1830 setattr(parent, entry, m)
1831 _set_return_value(parent, m, entry)
1832 return m
1833
1834 def __get__(self, obj, _type=None):
1835 return self.create_mock()
1836
1837
1838
1839class _ANY(object):
1840 "A helper object that compares equal to everything."
1841
1842 def __eq__(self, other):
1843 return True
1844
1845 def __ne__(self, other):
1846 return False
1847
1848 def __repr__(self):
1849 return '<ANY>'
1850
1851ANY = _ANY()
1852
1853
1854
1855def _format_call_signature(name, args, kwargs):
1856 message = '%s(%%s)' % name
1857 formatted_args = ''
1858 args_string = ', '.join([repr(arg) for arg in args])
1859 kwargs_string = ', '.join([
1860 '%s=%r' % (key, value) for key, value in kwargs.items()
1861 ])
1862 if args_string:
1863 formatted_args = args_string
1864 if kwargs_string:
1865 if formatted_args:
1866 formatted_args += ', '
1867 formatted_args += kwargs_string
1868
1869 return message % formatted_args
1870
1871
1872
1873class _Call(tuple):
1874 """
1875 A tuple for holding the results of a call to a mock, either in the form
1876 `(args, kwargs)` or `(name, args, kwargs)`.
1877
1878 If args or kwargs are empty then a call tuple will compare equal to
1879 a tuple without those values. This makes comparisons less verbose::
1880
1881 _Call(('name', (), {})) == ('name',)
1882 _Call(('name', (1,), {})) == ('name', (1,))
1883 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1884
1885 The `_Call` object provides a useful shortcut for comparing with call::
1886
1887 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1888 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1889
1890 If the _Call has no name then it will match any name.
1891 """
1892 def __new__(cls, value=(), name=None, parent=None, two=False,
1893 from_kall=True):
1894 name = ''
1895 args = ()
1896 kwargs = {}
1897 _len = len(value)
1898 if _len == 3:
1899 name, args, kwargs = value
1900 elif _len == 2:
1901 first, second = value
1902 if isinstance(first, str):
1903 name = first
1904 if isinstance(second, tuple):
1905 args = second
1906 else:
1907 kwargs = second
1908 else:
1909 args, kwargs = first, second
1910 elif _len == 1:
1911 value, = value
1912 if isinstance(value, str):
1913 name = value
1914 elif isinstance(value, tuple):
1915 args = value
1916 else:
1917 kwargs = value
1918
1919 if two:
1920 return tuple.__new__(cls, (args, kwargs))
1921
1922 return tuple.__new__(cls, (name, args, kwargs))
1923
1924
1925 def __init__(self, value=(), name=None, parent=None, two=False,
1926 from_kall=True):
1927 self.name = name
1928 self.parent = parent
1929 self.from_kall = from_kall
1930
1931
1932 def __eq__(self, other):
1933 if other is ANY:
1934 return True
1935 try:
1936 len_other = len(other)
1937 except TypeError:
1938 return False
1939
1940 self_name = ''
1941 if len(self) == 2:
1942 self_args, self_kwargs = self
1943 else:
1944 self_name, self_args, self_kwargs = self
1945
1946 other_name = ''
1947 if len_other == 0:
1948 other_args, other_kwargs = (), {}
1949 elif len_other == 3:
1950 other_name, other_args, other_kwargs = other
1951 elif len_other == 1:
1952 value, = other
1953 if isinstance(value, tuple):
1954 other_args = value
1955 other_kwargs = {}
1956 elif isinstance(value, str):
1957 other_name = value
1958 other_args, other_kwargs = (), {}
1959 else:
1960 other_args = ()
1961 other_kwargs = value
1962 else:
1963 # len 2
1964 # could be (name, args) or (name, kwargs) or (args, kwargs)
1965 first, second = other
1966 if isinstance(first, str):
1967 other_name = first
1968 if isinstance(second, tuple):
1969 other_args, other_kwargs = second, {}
1970 else:
1971 other_args, other_kwargs = (), second
1972 else:
1973 other_args, other_kwargs = first, second
1974
1975 if self_name and other_name != self_name:
1976 return False
1977
1978 # this order is important for ANY to work!
1979 return (other_args, other_kwargs) == (self_args, self_kwargs)
1980
1981
1982 def __ne__(self, other):
1983 return not self.__eq__(other)
1984
1985
1986 def __call__(self, *args, **kwargs):
1987 if self.name is None:
1988 return _Call(('', args, kwargs), name='()')
1989
1990 name = self.name + '()'
1991 return _Call((self.name, args, kwargs), name=name, parent=self)
1992
1993
1994 def __getattr__(self, attr):
1995 if self.name is None:
1996 return _Call(name=attr, from_kall=False)
1997 name = '%s.%s' % (self.name, attr)
1998 return _Call(name=name, parent=self, from_kall=False)
1999
2000
2001 def __repr__(self):
2002 if not self.from_kall:
2003 name = self.name or 'call'
2004 if name.startswith('()'):
2005 name = 'call%s' % name
2006 return name
2007
2008 if len(self) == 2:
2009 name = 'call'
2010 args, kwargs = self
2011 else:
2012 name, args, kwargs = self
2013 if not name:
2014 name = 'call'
2015 elif not name.startswith('()'):
2016 name = 'call.%s' % name
2017 else:
2018 name = 'call%s' % name
2019 return _format_call_signature(name, args, kwargs)
2020
2021
2022 def call_list(self):
2023 """For a call object that represents multiple calls, `call_list`
2024 returns a list of all the intermediate calls as well as the
2025 final call."""
2026 vals = []
2027 thing = self
2028 while thing is not None:
2029 if thing.from_kall:
2030 vals.append(thing)
2031 thing = thing.parent
2032 return _CallList(reversed(vals))
2033
2034
2035call = _Call(from_kall=False)
2036
2037
2038
2039def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2040 _name=None, **kwargs):
2041 """Create a mock object using another object as a spec. Attributes on the
2042 mock will use the corresponding attribute on the `spec` object as their
2043 spec.
2044
2045 Functions or methods being mocked will have their arguments checked
2046 to check that they are called with the correct signature.
2047
2048 If `spec_set` is True then attempting to set attributes that don't exist
2049 on the spec object will raise an `AttributeError`.
2050
2051 If a class is used as a spec then the return value of the mock (the
2052 instance of the class) will have the same spec. You can use a class as the
2053 spec for an instance object by passing `instance=True`. The returned mock
2054 will only be callable if instances of the mock are callable.
2055
2056 `create_autospec` also takes arbitrary keyword arguments that are passed to
2057 the constructor of the created mock."""
2058 if _is_list(spec):
2059 # can't pass a list instance to the mock constructor as it will be
2060 # interpreted as a list of strings
2061 spec = type(spec)
2062
2063 is_type = isinstance(spec, type)
2064
2065 _kwargs = {'spec': spec}
2066 if spec_set:
2067 _kwargs = {'spec_set': spec}
2068 elif spec is None:
2069 # None we mock with a normal mock without a spec
2070 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002071 if _kwargs and instance:
2072 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002073
2074 _kwargs.update(kwargs)
2075
2076 Klass = MagicMock
2077 if type(spec) in DescriptorTypes:
2078 # descriptors don't have a spec
2079 # because we don't know what type they return
2080 _kwargs = {}
2081 elif not _callable(spec):
2082 Klass = NonCallableMagicMock
2083 elif is_type and instance and not _instance_callable(spec):
2084 Klass = NonCallableMagicMock
2085
2086 _new_name = _name
2087 if _parent is None:
2088 # for a top level object no _new_name should be set
2089 _new_name = ''
2090
2091 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2092 name=_name, **_kwargs)
2093
2094 if isinstance(spec, FunctionTypes):
2095 # should only happen at the top level because we don't
2096 # recurse for functions
2097 mock = _set_signature(mock, spec)
2098 else:
2099 _check_signature(spec, mock, is_type, instance)
2100
2101 if _parent is not None and not instance:
2102 _parent._mock_children[_name] = mock
2103
2104 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002105 mock.return_value = create_autospec(spec, spec_set, instance=True,
2106 _name='()', _parent=mock)
2107
2108 for entry in dir(spec):
2109 if _is_magic(entry):
2110 # MagicMock already does the useful magic methods for us
2111 continue
2112
Michael Foord345266a2012-03-14 12:24:34 -07002113 # XXXX do we need a better way of getting attributes without
2114 # triggering code execution (?) Probably not - we need the actual
2115 # object to mock it so we would rather trigger a property than mock
2116 # the property descriptor. Likewise we want to mock out dynamically
2117 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002118 # XXXX what about attributes that raise exceptions other than
2119 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002120 # we could be resilient against it, or catch and propagate the
2121 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002122 try:
2123 original = getattr(spec, entry)
2124 except AttributeError:
2125 continue
Michael Foord345266a2012-03-14 12:24:34 -07002126
2127 kwargs = {'spec': original}
2128 if spec_set:
2129 kwargs = {'spec_set': original}
2130
2131 if not isinstance(original, FunctionTypes):
2132 new = _SpecState(original, spec_set, mock, entry, instance)
2133 mock._mock_children[entry] = new
2134 else:
2135 parent = mock
2136 if isinstance(spec, FunctionTypes):
2137 parent = mock.mock
2138
Michael Foord345266a2012-03-14 12:24:34 -07002139 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002140 kwargs['_eat_self'] = skipfirst
2141 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2142 _new_parent=parent,
2143 **kwargs)
2144 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002145 _check_signature(original, new, skipfirst=skipfirst)
2146
2147 # so functions created with _set_signature become instance attributes,
2148 # *plus* their underlying mock exists in _mock_children of the parent
2149 # mock. Adding to _mock_children may be unnecessary where we are also
2150 # setting as an instance attribute?
2151 if isinstance(new, FunctionTypes):
2152 setattr(mock, entry, new)
2153
2154 return mock
2155
2156
2157def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002158 """
2159 Return whether we should skip the first argument on spec's `entry`
2160 attribute.
2161 """
Michael Foord345266a2012-03-14 12:24:34 -07002162 if not isinstance(spec, type):
2163 if entry in getattr(spec, '__dict__', {}):
2164 # instance attribute - shouldn't skip
2165 return False
Michael Foord345266a2012-03-14 12:24:34 -07002166 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002167
2168 for klass in spec.__mro__:
2169 result = klass.__dict__.get(entry, DEFAULT)
2170 if result is DEFAULT:
2171 continue
2172 if isinstance(result, (staticmethod, classmethod)):
2173 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002174 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2175 # Normal method => skip if looked up on type
2176 # (if looked up on instance, self is already skipped)
2177 return is_type
2178 else:
2179 return False
Michael Foord345266a2012-03-14 12:24:34 -07002180
2181 # shouldn't get here unless function is a dynamically provided attribute
2182 # XXXX untested behaviour
2183 return is_type
2184
2185
2186def _get_class(obj):
2187 try:
2188 return obj.__class__
2189 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002190 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002191 return type(obj)
2192
2193
2194class _SpecState(object):
2195
2196 def __init__(self, spec, spec_set=False, parent=None,
2197 name=None, ids=None, instance=False):
2198 self.spec = spec
2199 self.ids = ids
2200 self.spec_set = spec_set
2201 self.parent = parent
2202 self.instance = instance
2203 self.name = name
2204
2205
2206FunctionTypes = (
2207 # python function
2208 type(create_autospec),
2209 # instance method
2210 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002211)
2212
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002213MethodWrapperTypes = (
2214 type(ANY.__eq__.__get__),
2215)
2216
Michael Foord345266a2012-03-14 12:24:34 -07002217
Michael Foorda74561a2012-03-25 19:03:13 +01002218file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002219
Michael Foord04cbe0c2013-03-19 17:22:51 -07002220def _iterate_read_data(read_data):
2221 # Helper for mock_open:
2222 # Retrieve lines from read_data via a generator so that separate calls to
2223 # readline, read, and readlines are properly interleaved
2224 data_as_list = ['{}\n'.format(l) for l in read_data.split('\n')]
2225
2226 if data_as_list[-1] == '\n':
2227 # If the last line ended in a newline, the list comprehension will have an
2228 # extra entry that's just a newline. Remove this.
2229 data_as_list = data_as_list[:-1]
2230 else:
2231 # If there wasn't an extra newline by itself, then the file being
2232 # emulated doesn't have a newline to end the last line remove the
2233 # newline that our naive format() added
2234 data_as_list[-1] = data_as_list[-1][:-1]
2235
2236 for line in data_as_list:
2237 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002238
2239def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002240 """
2241 A helper function to create a mock to replace the use of `open`. It works
2242 for `open` called directly or used as a context manager.
2243
2244 The `mock` argument is the mock object to configure. If `None` (the
2245 default) then a `MagicMock` will be created for you, with the API limited
2246 to methods or attributes available on standard file handles.
2247
Michael Foord04cbe0c2013-03-19 17:22:51 -07002248 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2249 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002250 """
Michael Foord04cbe0c2013-03-19 17:22:51 -07002251 def _readlines_side_effect(*args, **kwargs):
2252 if handle.readlines.return_value is not None:
2253 return handle.readlines.return_value
2254 return list(_data)
2255
2256 def _read_side_effect(*args, **kwargs):
2257 if handle.read.return_value is not None:
2258 return handle.read.return_value
2259 return ''.join(_data)
2260
2261 def _readline_side_effect():
2262 if handle.readline.return_value is not None:
2263 while True:
2264 yield handle.readline.return_value
2265 for line in _data:
2266 yield line
2267
2268
Michael Foorda74561a2012-03-25 19:03:13 +01002269 global file_spec
2270 if file_spec is None:
2271 import _io
2272 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2273
Michael Foord345266a2012-03-14 12:24:34 -07002274 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002275 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002276
2277 handle = MagicMock(spec=file_spec)
Michael Foord345266a2012-03-14 12:24:34 -07002278 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002279
2280 _data = _iterate_read_data(read_data)
2281
2282 handle.write.return_value = None
2283 handle.read.return_value = None
2284 handle.readline.return_value = None
2285 handle.readlines.return_value = None
2286
2287 handle.read.side_effect = _read_side_effect
2288 handle.readline.side_effect = _readline_side_effect()
2289 handle.readlines.side_effect = _readlines_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002290
2291 mock.return_value = handle
2292 return mock
2293
2294
2295class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002296 """
2297 A mock intended to be used as a property, or other descriptor, on a class.
2298 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2299 a return value when it is fetched.
2300
2301 Fetching a `PropertyMock` instance from an object calls the mock, with
2302 no args. Setting it calls the mock with the value being set.
2303 """
Michael Foordc2870622012-04-13 16:57:22 +01002304 def _get_child_mock(self, **kwargs):
2305 return MagicMock(**kwargs)
2306
Michael Foord345266a2012-03-14 12:24:34 -07002307 def __get__(self, obj, obj_type):
2308 return self()
2309 def __set__(self, obj, val):
2310 self(val)