blob: 0f0e9ed1dd42afc3e65e1578549521477ef56778 [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__
115 # we explicitly don't copy func.__dict__ into this copy as it would
116 # expose original attributes that should be mocked
117 funcopy.__module__ = func.__module__
118 funcopy.__defaults__ = func.__defaults__
119 funcopy.__kwdefaults__ = func.__kwdefaults__
120
121
122def _callable(obj):
123 if isinstance(obj, type):
124 return True
125 if getattr(obj, '__call__', None) is not None:
126 return True
127 return False
128
129
130def _is_list(obj):
131 # checks for list or tuples
132 # XXXX badly named!
133 return type(obj) in (list, tuple)
134
135
136def _instance_callable(obj):
137 """Given an object, return True if the object is callable.
138 For classes, return True if instances would be callable."""
139 if not isinstance(obj, type):
140 # already an instance
141 return getattr(obj, '__call__', None) is not None
142
Michael Foorda74b3aa2012-03-14 14:40:22 -0700143 # *could* be broken by a class overriding __mro__ or __dict__ via
144 # a metaclass
145 for base in (obj,) + obj.__mro__:
146 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700147 return True
148 return False
149
150
151def _set_signature(mock, original, instance=False):
152 # creates a function with signature (*args, **kwargs) that delegates to a
153 # mock. It still does signature checking by calling a lambda with the same
154 # signature as the original.
155 if not _callable(original):
156 return
157
158 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100159 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700160 if result is None:
Michael Foord345266a2012-03-14 12:24:34 -0700161 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100162 func, sig = result
163 def checksig(*args, **kwargs):
164 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700165 _copy_func_details(func, checksig)
166
167 name = original.__name__
168 if not name.isidentifier():
169 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100170 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700171 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100172 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700173 return mock(*args, **kwargs)""" % name
174 exec (src, context)
175 funcopy = context[name]
176 _setup_func(funcopy, mock)
177 return funcopy
178
179
180def _setup_func(funcopy, mock):
181 funcopy.mock = mock
182
183 # can't use isinstance with mocks
184 if not _is_instance_mock(mock):
185 return
186
187 def assert_called_with(*args, **kwargs):
188 return mock.assert_called_with(*args, **kwargs)
189 def assert_called_once_with(*args, **kwargs):
190 return mock.assert_called_once_with(*args, **kwargs)
191 def assert_has_calls(*args, **kwargs):
192 return mock.assert_has_calls(*args, **kwargs)
193 def assert_any_call(*args, **kwargs):
194 return mock.assert_any_call(*args, **kwargs)
195 def reset_mock():
196 funcopy.method_calls = _CallList()
197 funcopy.mock_calls = _CallList()
198 mock.reset_mock()
199 ret = funcopy.return_value
200 if _is_instance_mock(ret) and not ret is mock:
201 ret.reset_mock()
202
203 funcopy.called = False
204 funcopy.call_count = 0
205 funcopy.call_args = None
206 funcopy.call_args_list = _CallList()
207 funcopy.method_calls = _CallList()
208 funcopy.mock_calls = _CallList()
209
210 funcopy.return_value = mock.return_value
211 funcopy.side_effect = mock.side_effect
212 funcopy._mock_children = mock._mock_children
213
214 funcopy.assert_called_with = assert_called_with
215 funcopy.assert_called_once_with = assert_called_once_with
216 funcopy.assert_has_calls = assert_has_calls
217 funcopy.assert_any_call = assert_any_call
218 funcopy.reset_mock = reset_mock
219
220 mock._mock_delegate = funcopy
221
222
223def _is_magic(name):
224 return '__%s__' % name[2:-2] == name
225
226
227class _SentinelObject(object):
228 "A unique, named, sentinel object."
229 def __init__(self, name):
230 self.name = name
231
232 def __repr__(self):
233 return 'sentinel.%s' % self.name
234
235
236class _Sentinel(object):
237 """Access attributes to return a named object, usable as a sentinel."""
238 def __init__(self):
239 self._sentinels = {}
240
241 def __getattr__(self, name):
242 if name == '__bases__':
243 # Without this help(unittest.mock) raises an exception
244 raise AttributeError
245 return self._sentinels.setdefault(name, _SentinelObject(name))
246
247
248sentinel = _Sentinel()
249
250DEFAULT = sentinel.DEFAULT
251_missing = sentinel.MISSING
252_deleted = sentinel.DELETED
253
254
Michael Foord345266a2012-03-14 12:24:34 -0700255def _copy(value):
256 if type(value) in (dict, list, tuple, set):
257 return type(value)(value)
258 return value
259
260
261_allowed_names = set(
262 [
263 'return_value', '_mock_return_value', 'side_effect',
264 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
265 '_mock_name', '_mock_new_name'
266 ]
267)
268
269
270def _delegating_property(name):
271 _allowed_names.add(name)
272 _the_name = '_mock_' + name
273 def _get(self, name=name, _the_name=_the_name):
274 sig = self._mock_delegate
275 if sig is None:
276 return getattr(self, _the_name)
277 return getattr(sig, name)
278 def _set(self, value, name=name, _the_name=_the_name):
279 sig = self._mock_delegate
280 if sig is None:
281 self.__dict__[_the_name] = value
282 else:
283 setattr(sig, name, value)
284
285 return property(_get, _set)
286
287
288
289class _CallList(list):
290
291 def __contains__(self, value):
292 if not isinstance(value, list):
293 return list.__contains__(self, value)
294 len_value = len(value)
295 len_self = len(self)
296 if len_value > len_self:
297 return False
298
299 for i in range(0, len_self - len_value + 1):
300 sub_list = self[i:i+len_value]
301 if sub_list == value:
302 return True
303 return False
304
305 def __repr__(self):
306 return pprint.pformat(list(self))
307
308
309def _check_and_set_parent(parent, value, name, new_name):
310 if not _is_instance_mock(value):
311 return False
312 if ((value._mock_name or value._mock_new_name) or
313 (value._mock_parent is not None) or
314 (value._mock_new_parent is not None)):
315 return False
316
317 _parent = parent
318 while _parent is not None:
319 # setting a mock (value) as a child or return value of itself
320 # should not modify the mock
321 if _parent is value:
322 return False
323 _parent = _parent._mock_new_parent
324
325 if new_name:
326 value._mock_new_parent = parent
327 value._mock_new_name = new_name
328 if name:
329 value._mock_parent = parent
330 value._mock_name = name
331 return True
332
333
334
335class Base(object):
336 _mock_return_value = DEFAULT
337 _mock_side_effect = None
338 def __init__(self, *args, **kwargs):
339 pass
340
341
342
343class NonCallableMock(Base):
344 """A non-callable version of `Mock`"""
345
346 def __new__(cls, *args, **kw):
347 # every instance has its own class
348 # so we can create magic methods on the
349 # class without stomping on other mocks
350 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
351 instance = object.__new__(new)
352 return instance
353
354
355 def __init__(
356 self, spec=None, wraps=None, name=None, spec_set=None,
357 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100358 _spec_as_instance=False, _eat_self=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700359 ):
360 if _new_parent is None:
361 _new_parent = parent
362
363 __dict__ = self.__dict__
364 __dict__['_mock_parent'] = parent
365 __dict__['_mock_name'] = name
366 __dict__['_mock_new_name'] = _new_name
367 __dict__['_mock_new_parent'] = _new_parent
368
369 if spec_set is not None:
370 spec = spec_set
371 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100372 if _eat_self is None:
373 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700374
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100375 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700376
377 __dict__['_mock_children'] = {}
378 __dict__['_mock_wraps'] = wraps
379 __dict__['_mock_delegate'] = None
380
381 __dict__['_mock_called'] = False
382 __dict__['_mock_call_args'] = None
383 __dict__['_mock_call_count'] = 0
384 __dict__['_mock_call_args_list'] = _CallList()
385 __dict__['_mock_mock_calls'] = _CallList()
386
387 __dict__['method_calls'] = _CallList()
388
389 if kwargs:
390 self.configure_mock(**kwargs)
391
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000392 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700393 spec, wraps, name, spec_set, parent,
394 _spec_state
395 )
396
397
398 def attach_mock(self, mock, attribute):
399 """
400 Attach a mock as an attribute of this one, replacing its name and
401 parent. Calls to the attached mock will be recorded in the
402 `method_calls` and `mock_calls` attributes of this one."""
403 mock._mock_parent = None
404 mock._mock_new_parent = None
405 mock._mock_name = ''
406 mock._mock_new_name = None
407
408 setattr(self, attribute, mock)
409
410
411 def mock_add_spec(self, spec, spec_set=False):
412 """Add a spec to a mock. `spec` can either be an object or a
413 list of strings. Only attributes on the `spec` can be fetched as
414 attributes from the mock.
415
416 If `spec_set` is True then only attributes on the spec can be set."""
417 self._mock_add_spec(spec, spec_set)
418
419
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100420 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
421 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700422 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100423 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700424
425 if spec is not None and not _is_list(spec):
426 if isinstance(spec, type):
427 _spec_class = spec
428 else:
429 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100430 res = _get_signature_object(spec,
431 _spec_as_instance, _eat_self)
432 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700433
434 spec = dir(spec)
435
436 __dict__ = self.__dict__
437 __dict__['_spec_class'] = _spec_class
438 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100439 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700440 __dict__['_mock_methods'] = spec
441
442
443 def __get_return_value(self):
444 ret = self._mock_return_value
445 if self._mock_delegate is not None:
446 ret = self._mock_delegate.return_value
447
448 if ret is DEFAULT:
449 ret = self._get_child_mock(
450 _new_parent=self, _new_name='()'
451 )
452 self.return_value = ret
453 return ret
454
455
456 def __set_return_value(self, value):
457 if self._mock_delegate is not None:
458 self._mock_delegate.return_value = value
459 else:
460 self._mock_return_value = value
461 _check_and_set_parent(self, value, None, '()')
462
463 __return_value_doc = "The value to be returned when the mock is called."
464 return_value = property(__get_return_value, __set_return_value,
465 __return_value_doc)
466
467
468 @property
469 def __class__(self):
470 if self._spec_class is None:
471 return type(self)
472 return self._spec_class
473
474 called = _delegating_property('called')
475 call_count = _delegating_property('call_count')
476 call_args = _delegating_property('call_args')
477 call_args_list = _delegating_property('call_args_list')
478 mock_calls = _delegating_property('mock_calls')
479
480
481 def __get_side_effect(self):
482 delegated = self._mock_delegate
483 if delegated is None:
484 return self._mock_side_effect
485 return delegated.side_effect
486
487 def __set_side_effect(self, value):
488 value = _try_iter(value)
489 delegated = self._mock_delegate
490 if delegated is None:
491 self._mock_side_effect = value
492 else:
493 delegated.side_effect = value
494
495 side_effect = property(__get_side_effect, __set_side_effect)
496
497
498 def reset_mock(self):
499 "Restore the mock object to its initial state."
500 self.called = False
501 self.call_args = None
502 self.call_count = 0
503 self.mock_calls = _CallList()
504 self.call_args_list = _CallList()
505 self.method_calls = _CallList()
506
507 for child in self._mock_children.values():
Michael Foord75963642012-06-09 17:31:59 +0100508 if isinstance(child, _SpecState):
509 continue
Michael Foord345266a2012-03-14 12:24:34 -0700510 child.reset_mock()
511
512 ret = self._mock_return_value
513 if _is_instance_mock(ret) and ret is not self:
514 ret.reset_mock()
515
516
517 def configure_mock(self, **kwargs):
518 """Set attributes on the mock through keyword arguments.
519
520 Attributes plus return values and side effects can be set on child
521 mocks using standard dot notation and unpacking a dictionary in the
522 method call:
523
524 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
525 >>> mock.configure_mock(**attrs)"""
526 for arg, val in sorted(kwargs.items(),
527 # we sort on the number of dots so that
528 # attributes are set before we set attributes on
529 # attributes
530 key=lambda entry: entry[0].count('.')):
531 args = arg.split('.')
532 final = args.pop()
533 obj = self
534 for entry in args:
535 obj = getattr(obj, entry)
536 setattr(obj, final, val)
537
538
539 def __getattr__(self, name):
540 if name == '_mock_methods':
541 raise AttributeError(name)
542 elif self._mock_methods is not None:
543 if name not in self._mock_methods or name in _all_magics:
544 raise AttributeError("Mock object has no attribute %r" % name)
545 elif _is_magic(name):
546 raise AttributeError(name)
547
548 result = self._mock_children.get(name)
549 if result is _deleted:
550 raise AttributeError(name)
551 elif result is None:
552 wraps = None
553 if self._mock_wraps is not None:
554 # XXXX should we get the attribute without triggering code
555 # execution?
556 wraps = getattr(self._mock_wraps, name)
557
558 result = self._get_child_mock(
559 parent=self, name=name, wraps=wraps, _new_name=name,
560 _new_parent=self
561 )
562 self._mock_children[name] = result
563
564 elif isinstance(result, _SpecState):
565 result = create_autospec(
566 result.spec, result.spec_set, result.instance,
567 result.parent, result.name
568 )
569 self._mock_children[name] = result
570
571 return result
572
573
574 def __repr__(self):
575 _name_list = [self._mock_new_name]
576 _parent = self._mock_new_parent
577 last = self
578
579 dot = '.'
580 if _name_list == ['()']:
581 dot = ''
582 seen = set()
583 while _parent is not None:
584 last = _parent
585
586 _name_list.append(_parent._mock_new_name + dot)
587 dot = '.'
588 if _parent._mock_new_name == '()':
589 dot = ''
590
591 _parent = _parent._mock_new_parent
592
593 # use ids here so as not to call __hash__ on the mocks
594 if id(_parent) in seen:
595 break
596 seen.add(id(_parent))
597
598 _name_list = list(reversed(_name_list))
599 _first = last._mock_name or 'mock'
600 if len(_name_list) > 1:
601 if _name_list[1] not in ('()', '().'):
602 _first += '.'
603 _name_list[0] = _first
604 name = ''.join(_name_list)
605
606 name_string = ''
607 if name not in ('mock', 'mock.'):
608 name_string = ' name=%r' % name
609
610 spec_string = ''
611 if self._spec_class is not None:
612 spec_string = ' spec=%r'
613 if self._spec_set:
614 spec_string = ' spec_set=%r'
615 spec_string = spec_string % self._spec_class.__name__
616 return "<%s%s%s id='%s'>" % (
617 type(self).__name__,
618 name_string,
619 spec_string,
620 id(self)
621 )
622
623
624 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700625 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100626 if not FILTER_DIR:
627 return object.__dir__(self)
628
Michael Foord345266a2012-03-14 12:24:34 -0700629 extras = self._mock_methods or []
630 from_type = dir(type(self))
631 from_dict = list(self.__dict__)
632
Michael Foord313f85f2012-03-25 18:16:07 +0100633 from_type = [e for e in from_type if not e.startswith('_')]
634 from_dict = [e for e in from_dict if not e.startswith('_') or
635 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700636 return sorted(set(extras + from_type + from_dict +
637 list(self._mock_children)))
638
639
640 def __setattr__(self, name, value):
641 if name in _allowed_names:
642 # property setters go through here
643 return object.__setattr__(self, name, value)
644 elif (self._spec_set and self._mock_methods is not None and
645 name not in self._mock_methods and
646 name not in self.__dict__):
647 raise AttributeError("Mock object has no attribute '%s'" % name)
648 elif name in _unsupported_magics:
649 msg = 'Attempting to set unsupported magic method %r.' % name
650 raise AttributeError(msg)
651 elif name in _all_magics:
652 if self._mock_methods is not None and name not in self._mock_methods:
653 raise AttributeError("Mock object has no attribute '%s'" % name)
654
655 if not _is_instance_mock(value):
656 setattr(type(self), name, _get_method(name, value))
657 original = value
658 value = lambda *args, **kw: original(self, *args, **kw)
659 else:
660 # only set _new_name and not name so that mock_calls is tracked
661 # but not method calls
662 _check_and_set_parent(self, value, None, name)
663 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100664 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700665 elif name == '__class__':
666 self._spec_class = value
667 return
668 else:
669 if _check_and_set_parent(self, value, name, name):
670 self._mock_children[name] = value
671 return object.__setattr__(self, name, value)
672
673
674 def __delattr__(self, name):
675 if name in _all_magics and name in type(self).__dict__:
676 delattr(type(self), name)
677 if name not in self.__dict__:
678 # for magic methods that are still MagicProxy objects and
679 # not set on the instance itself
680 return
681
682 if name in self.__dict__:
683 object.__delattr__(self, name)
684
685 obj = self._mock_children.get(name, _missing)
686 if obj is _deleted:
687 raise AttributeError(name)
688 if obj is not _missing:
689 del self._mock_children[name]
690 self._mock_children[name] = _deleted
691
692
Michael Foord345266a2012-03-14 12:24:34 -0700693 def _format_mock_call_signature(self, args, kwargs):
694 name = self._mock_name or 'mock'
695 return _format_call_signature(name, args, kwargs)
696
697
698 def _format_mock_failure_message(self, args, kwargs):
699 message = 'Expected call: %s\nActual call: %s'
700 expected_string = self._format_mock_call_signature(args, kwargs)
701 call_args = self.call_args
702 if len(call_args) == 3:
703 call_args = call_args[1:]
704 actual_string = self._format_mock_call_signature(*call_args)
705 return message % (expected_string, actual_string)
706
707
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100708 def _call_matcher(self, _call):
709 """
710 Given a call (or simply a (args, kwargs) tuple), return a
711 comparison key suitable for matching with other calls.
712 This is a best effort method which relies on the spec's signature,
713 if available, or falls back on the arguments themselves.
714 """
715 sig = self._spec_signature
716 if sig is not None:
717 if len(_call) == 2:
718 name = ''
719 args, kwargs = _call
720 else:
721 name, args, kwargs = _call
722 try:
723 return name, sig.bind(*args, **kwargs)
724 except TypeError as e:
725 return e.with_traceback(None)
726 else:
727 return _call
728
729
Michael Foord345266a2012-03-14 12:24:34 -0700730 def assert_called_with(_mock_self, *args, **kwargs):
731 """assert that the mock was called with the specified arguments.
732
733 Raises an AssertionError if the args and keyword args passed in are
734 different to the last call to the mock."""
735 self = _mock_self
736 if self.call_args is None:
737 expected = self._format_mock_call_signature(args, kwargs)
738 raise AssertionError('Expected call: %s\nNot called' % (expected,))
739
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100740 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700741 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100742 return msg
743 expected = self._call_matcher((args, kwargs))
744 actual = self._call_matcher(self.call_args)
745 if expected != actual:
746 cause = expected if isinstance(expected, Exception) else None
747 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700748
749
750 def assert_called_once_with(_mock_self, *args, **kwargs):
751 """assert that the mock was called exactly once and with the specified
752 arguments."""
753 self = _mock_self
754 if not self.call_count == 1:
Michael Foord28d591c2012-09-28 16:15:22 +0100755 msg = ("Expected '%s' to be called once. Called %s times." %
756 (self._mock_name or 'mock', self.call_count))
Michael Foord345266a2012-03-14 12:24:34 -0700757 raise AssertionError(msg)
758 return self.assert_called_with(*args, **kwargs)
759
760
761 def assert_has_calls(self, calls, any_order=False):
762 """assert the mock has been called with the specified calls.
763 The `mock_calls` list is checked for the calls.
764
765 If `any_order` is False (the default) then the calls must be
766 sequential. There can be extra calls before or after the
767 specified calls.
768
769 If `any_order` is True then the calls can be in any order, but
770 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100771 expected = [self._call_matcher(c) for c in calls]
772 cause = expected if isinstance(expected, Exception) else None
773 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700774 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100775 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700776 raise AssertionError(
777 'Calls not found.\nExpected: %r\n'
778 'Actual: %r' % (calls, self.mock_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100779 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700780 return
781
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100782 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700783
784 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100785 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700786 try:
787 all_calls.remove(kall)
788 except ValueError:
789 not_found.append(kall)
790 if not_found:
791 raise AssertionError(
792 '%r not all found in call list' % (tuple(not_found),)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100793 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700794
795
796 def assert_any_call(self, *args, **kwargs):
797 """assert the mock has been called with the specified arguments.
798
799 The assert passes if the mock has *ever* been called, unlike
800 `assert_called_with` and `assert_called_once_with` that only pass if
801 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100802 expected = self._call_matcher((args, kwargs))
803 actual = [self._call_matcher(c) for c in self.call_args_list]
804 if expected not in actual:
805 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700806 expected_string = self._format_mock_call_signature(args, kwargs)
807 raise AssertionError(
808 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100809 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700810
811
812 def _get_child_mock(self, **kw):
813 """Create the child mocks for attributes and return value.
814 By default child mocks will be the same type as the parent.
815 Subclasses of Mock may want to override this to customize the way
816 child mocks are made.
817
818 For non-callable mocks the callable variant will be used (rather than
819 any custom subclass)."""
820 _type = type(self)
821 if not issubclass(_type, CallableMixin):
822 if issubclass(_type, NonCallableMagicMock):
823 klass = MagicMock
824 elif issubclass(_type, NonCallableMock) :
825 klass = Mock
826 else:
827 klass = _type.__mro__[1]
828 return klass(**kw)
829
830
831
832def _try_iter(obj):
833 if obj is None:
834 return obj
835 if _is_exception(obj):
836 return obj
837 if _callable(obj):
838 return obj
839 try:
840 return iter(obj)
841 except TypeError:
842 # XXXX backwards compatibility
843 # but this will blow up on first call - so maybe we should fail early?
844 return obj
845
846
847
848class CallableMixin(Base):
849
850 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
851 wraps=None, name=None, spec_set=None, parent=None,
852 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
853 self.__dict__['_mock_return_value'] = return_value
854
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000855 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700856 spec, wraps, name, spec_set, parent,
857 _spec_state, _new_name, _new_parent, **kwargs
858 )
859
860 self.side_effect = side_effect
861
862
863 def _mock_check_sig(self, *args, **kwargs):
864 # stub method that can be replaced with one with a specific signature
865 pass
866
867
868 def __call__(_mock_self, *args, **kwargs):
869 # can't use self in-case a function / method we are mocking uses self
870 # in the signature
871 _mock_self._mock_check_sig(*args, **kwargs)
872 return _mock_self._mock_call(*args, **kwargs)
873
874
875 def _mock_call(_mock_self, *args, **kwargs):
876 self = _mock_self
877 self.called = True
878 self.call_count += 1
Michael Foord345266a2012-03-14 12:24:34 -0700879 _new_name = self._mock_new_name
880 _new_parent = self._mock_new_parent
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100881
882 _call = _Call((args, kwargs), two=True)
883 self.call_args = _call
884 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700885 self.mock_calls.append(_Call(('', args, kwargs)))
886
887 seen = set()
888 skip_next_dot = _new_name == '()'
889 do_method_calls = self._mock_parent is not None
890 name = self._mock_name
891 while _new_parent is not None:
892 this_mock_call = _Call((_new_name, args, kwargs))
893 if _new_parent._mock_new_name:
894 dot = '.'
895 if skip_next_dot:
896 dot = ''
897
898 skip_next_dot = False
899 if _new_parent._mock_new_name == '()':
900 skip_next_dot = True
901
902 _new_name = _new_parent._mock_new_name + dot + _new_name
903
904 if do_method_calls:
905 if _new_name == name:
906 this_method_call = this_mock_call
907 else:
908 this_method_call = _Call((name, args, kwargs))
909 _new_parent.method_calls.append(this_method_call)
910
911 do_method_calls = _new_parent._mock_parent is not None
912 if do_method_calls:
913 name = _new_parent._mock_name + '.' + name
914
915 _new_parent.mock_calls.append(this_mock_call)
916 _new_parent = _new_parent._mock_new_parent
917
918 # use ids here so as not to call __hash__ on the mocks
919 _new_parent_id = id(_new_parent)
920 if _new_parent_id in seen:
921 break
922 seen.add(_new_parent_id)
923
924 ret_val = DEFAULT
925 effect = self.side_effect
926 if effect is not None:
927 if _is_exception(effect):
928 raise effect
929
930 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +0100931 result = next(effect)
932 if _is_exception(result):
933 raise result
934 return result
Michael Foord345266a2012-03-14 12:24:34 -0700935
936 ret_val = effect(*args, **kwargs)
937 if ret_val is DEFAULT:
938 ret_val = self.return_value
939
940 if (self._mock_wraps is not None and
941 self._mock_return_value is DEFAULT):
942 return self._mock_wraps(*args, **kwargs)
943 if ret_val is DEFAULT:
944 ret_val = self.return_value
945 return ret_val
946
947
948
949class Mock(CallableMixin, NonCallableMock):
950 """
951 Create a new `Mock` object. `Mock` takes several optional arguments
952 that specify the behaviour of the Mock object:
953
954 * `spec`: This can be either a list of strings or an existing object (a
955 class or instance) that acts as the specification for the mock object. If
956 you pass in an object then a list of strings is formed by calling dir on
957 the object (excluding unsupported magic attributes and methods). Accessing
958 any attribute not in this list will raise an `AttributeError`.
959
960 If `spec` is an object (rather than a list of strings) then
961 `mock.__class__` returns the class of the spec object. This allows mocks
962 to pass `isinstance` tests.
963
964 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
965 or get an attribute on the mock that isn't on the object passed as
966 `spec_set` will raise an `AttributeError`.
967
968 * `side_effect`: A function to be called whenever the Mock is called. See
969 the `side_effect` attribute. Useful for raising exceptions or
970 dynamically changing return values. The function is called with the same
971 arguments as the mock, and unless it returns `DEFAULT`, the return
972 value of this function is used as the return value.
973
Michael Foord2cd48732012-04-21 15:52:11 +0100974 If `side_effect` is an iterable then each call to the mock will return
975 the next value from the iterable. If any of the members of the iterable
976 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -0700977
978 If `side_effect` is an iterable then each call to the mock will return
979 the next value from the iterable.
980
981 * `return_value`: The value returned when the mock is called. By default
982 this is a new Mock (created on first access). See the
983 `return_value` attribute.
984
Michael Foord0682a0c2012-04-13 20:51:20 +0100985 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
986 calling the Mock will pass the call through to the wrapped object
987 (returning the real result). Attribute access on the mock will return a
988 Mock object that wraps the corresponding attribute of the wrapped object
989 (so attempting to access an attribute that doesn't exist will raise an
990 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -0700991
992 If the mock has an explicit `return_value` set then calls are not passed
993 to the wrapped object and the `return_value` is returned instead.
994
995 * `name`: If the mock has a name then it will be used in the repr of the
996 mock. This can be useful for debugging. The name is propagated to child
997 mocks.
998
999 Mocks can also be called with arbitrary keyword arguments. These will be
1000 used to set attributes on the mock after it is created.
1001 """
1002
1003
1004
1005def _dot_lookup(thing, comp, import_path):
1006 try:
1007 return getattr(thing, comp)
1008 except AttributeError:
1009 __import__(import_path)
1010 return getattr(thing, comp)
1011
1012
1013def _importer(target):
1014 components = target.split('.')
1015 import_path = components.pop(0)
1016 thing = __import__(import_path)
1017
1018 for comp in components:
1019 import_path += ".%s" % comp
1020 thing = _dot_lookup(thing, comp, import_path)
1021 return thing
1022
1023
1024def _is_started(patcher):
1025 # XXXX horrible
1026 return hasattr(patcher, 'is_local')
1027
1028
1029class _patch(object):
1030
1031 attribute_name = None
Michael Foordf7c41582012-06-10 20:36:32 +01001032 _active_patches = set()
Michael Foord345266a2012-03-14 12:24:34 -07001033
1034 def __init__(
1035 self, getter, attribute, new, spec, create,
1036 spec_set, autospec, new_callable, kwargs
1037 ):
1038 if new_callable is not None:
1039 if new is not DEFAULT:
1040 raise ValueError(
1041 "Cannot use 'new' and 'new_callable' together"
1042 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001043 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001044 raise ValueError(
1045 "Cannot use 'autospec' and 'new_callable' together"
1046 )
1047
1048 self.getter = getter
1049 self.attribute = attribute
1050 self.new = new
1051 self.new_callable = new_callable
1052 self.spec = spec
1053 self.create = create
1054 self.has_local = False
1055 self.spec_set = spec_set
1056 self.autospec = autospec
1057 self.kwargs = kwargs
1058 self.additional_patchers = []
1059
1060
1061 def copy(self):
1062 patcher = _patch(
1063 self.getter, self.attribute, self.new, self.spec,
1064 self.create, self.spec_set,
1065 self.autospec, self.new_callable, self.kwargs
1066 )
1067 patcher.attribute_name = self.attribute_name
1068 patcher.additional_patchers = [
1069 p.copy() for p in self.additional_patchers
1070 ]
1071 return patcher
1072
1073
1074 def __call__(self, func):
1075 if isinstance(func, type):
1076 return self.decorate_class(func)
1077 return self.decorate_callable(func)
1078
1079
1080 def decorate_class(self, klass):
1081 for attr in dir(klass):
1082 if not attr.startswith(patch.TEST_PREFIX):
1083 continue
1084
1085 attr_value = getattr(klass, attr)
1086 if not hasattr(attr_value, "__call__"):
1087 continue
1088
1089 patcher = self.copy()
1090 setattr(klass, attr, patcher(attr_value))
1091 return klass
1092
1093
1094 def decorate_callable(self, func):
1095 if hasattr(func, 'patchings'):
1096 func.patchings.append(self)
1097 return func
1098
1099 @wraps(func)
1100 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001101 extra_args = []
1102 entered_patchers = []
1103
Michael Foord50a8c0e2012-03-25 18:57:58 +01001104 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001105 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001106 for patching in patched.patchings:
1107 arg = patching.__enter__()
1108 entered_patchers.append(patching)
1109 if patching.attribute_name is not None:
1110 keywargs.update(arg)
1111 elif patching.new is DEFAULT:
1112 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001113
Michael Foordd7c65e22012-03-14 14:56:54 -07001114 args += tuple(extra_args)
1115 return func(*args, **keywargs)
1116 except:
1117 if (patching not in entered_patchers and
1118 _is_started(patching)):
1119 # the patcher may have been started, but an exception
1120 # raised whilst entering one of its additional_patchers
1121 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001122 # Pass the exception to __exit__
1123 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001124 # re-raise the exception
1125 raise
Michael Foord345266a2012-03-14 12:24:34 -07001126 finally:
1127 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001128 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001129
1130 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001131 return patched
1132
1133
1134 def get_original(self):
1135 target = self.getter()
1136 name = self.attribute
1137
1138 original = DEFAULT
1139 local = False
1140
1141 try:
1142 original = target.__dict__[name]
1143 except (AttributeError, KeyError):
1144 original = getattr(target, name, DEFAULT)
1145 else:
1146 local = True
1147
1148 if not self.create and original is DEFAULT:
1149 raise AttributeError(
1150 "%s does not have the attribute %r" % (target, name)
1151 )
1152 return original, local
1153
1154
1155 def __enter__(self):
1156 """Perform the patch."""
1157 new, spec, spec_set = self.new, self.spec, self.spec_set
1158 autospec, kwargs = self.autospec, self.kwargs
1159 new_callable = self.new_callable
1160 self.target = self.getter()
1161
Michael Foord50a8c0e2012-03-25 18:57:58 +01001162 # normalise False to None
1163 if spec is False:
1164 spec = None
1165 if spec_set is False:
1166 spec_set = None
1167 if autospec is False:
1168 autospec = None
1169
1170 if spec is not None and autospec is not None:
1171 raise TypeError("Can't specify spec and autospec")
1172 if ((spec is not None or autospec is not None) and
1173 spec_set not in (True, None)):
1174 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1175
Michael Foord345266a2012-03-14 12:24:34 -07001176 original, local = self.get_original()
1177
Michael Foord50a8c0e2012-03-25 18:57:58 +01001178 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001179 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001180 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001181 # set spec to the object we are replacing
1182 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001183 if spec_set is True:
1184 spec_set = original
1185 spec = None
1186 elif spec is not None:
1187 if spec_set is True:
1188 spec_set = spec
1189 spec = None
1190 elif spec_set is True:
1191 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001192
Michael Foord50a8c0e2012-03-25 18:57:58 +01001193 if spec is not None or spec_set is not None:
1194 if original is DEFAULT:
1195 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001196 if isinstance(original, type):
1197 # If we're patching out a class and there is a spec
1198 inherit = True
1199
1200 Klass = MagicMock
1201 _kwargs = {}
1202 if new_callable is not None:
1203 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001204 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001205 this_spec = spec
1206 if spec_set is not None:
1207 this_spec = spec_set
1208 if _is_list(this_spec):
1209 not_callable = '__call__' not in this_spec
1210 else:
1211 not_callable = not callable(this_spec)
1212 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001213 Klass = NonCallableMagicMock
1214
1215 if spec is not None:
1216 _kwargs['spec'] = spec
1217 if spec_set is not None:
1218 _kwargs['spec_set'] = spec_set
1219
1220 # add a name to mocks
1221 if (isinstance(Klass, type) and
1222 issubclass(Klass, NonCallableMock) and self.attribute):
1223 _kwargs['name'] = self.attribute
1224
1225 _kwargs.update(kwargs)
1226 new = Klass(**_kwargs)
1227
1228 if inherit and _is_instance_mock(new):
1229 # we can only tell if the instance should be callable if the
1230 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001231 this_spec = spec
1232 if spec_set is not None:
1233 this_spec = spec_set
1234 if (not _is_list(this_spec) and not
1235 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001236 Klass = NonCallableMagicMock
1237
1238 _kwargs.pop('name')
1239 new.return_value = Klass(_new_parent=new, _new_name='()',
1240 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001241 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001242 # spec is ignored, new *must* be default, spec_set is treated
1243 # as a boolean. Should we check spec is not None and that spec_set
1244 # is a bool?
1245 if new is not DEFAULT:
1246 raise TypeError(
1247 "autospec creates the mock for you. Can't specify "
1248 "autospec and new."
1249 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001250 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001251 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001252 spec_set = bool(spec_set)
1253 if autospec is True:
1254 autospec = original
1255
1256 new = create_autospec(autospec, spec_set=spec_set,
1257 _name=self.attribute, **kwargs)
1258 elif kwargs:
1259 # can't set keyword args when we aren't creating the mock
1260 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1261 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1262
1263 new_attr = new
1264
1265 self.temp_original = original
1266 self.is_local = local
1267 setattr(self.target, self.attribute, new_attr)
1268 if self.attribute_name is not None:
1269 extra_args = {}
1270 if self.new is DEFAULT:
1271 extra_args[self.attribute_name] = new
1272 for patching in self.additional_patchers:
1273 arg = patching.__enter__()
1274 if patching.new is DEFAULT:
1275 extra_args.update(arg)
1276 return extra_args
1277
1278 return new
1279
1280
Michael Foord50a8c0e2012-03-25 18:57:58 +01001281 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001282 """Undo the patch."""
1283 if not _is_started(self):
1284 raise RuntimeError('stop called on unstarted patcher')
1285
1286 if self.is_local and self.temp_original is not DEFAULT:
1287 setattr(self.target, self.attribute, self.temp_original)
1288 else:
1289 delattr(self.target, self.attribute)
1290 if not self.create and not hasattr(self.target, self.attribute):
1291 # needed for proxy objects like django settings
1292 setattr(self.target, self.attribute, self.temp_original)
1293
1294 del self.temp_original
1295 del self.is_local
1296 del self.target
1297 for patcher in reversed(self.additional_patchers):
1298 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001299 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001300
Michael Foordf7c41582012-06-10 20:36:32 +01001301
1302 def start(self):
1303 """Activate a patch, returning any created mock."""
1304 result = self.__enter__()
1305 self._active_patches.add(self)
1306 return result
1307
1308
1309 def stop(self):
1310 """Stop an active patch."""
1311 self._active_patches.discard(self)
1312 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001313
1314
1315
1316def _get_target(target):
1317 try:
1318 target, attribute = target.rsplit('.', 1)
1319 except (TypeError, ValueError):
1320 raise TypeError("Need a valid target to patch. You supplied: %r" %
1321 (target,))
1322 getter = lambda: _importer(target)
1323 return getter, attribute
1324
1325
1326def _patch_object(
1327 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001328 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001329 new_callable=None, **kwargs
1330 ):
1331 """
Michael Foord345266a2012-03-14 12:24:34 -07001332 patch the named member (`attribute`) on an object (`target`) with a mock
1333 object.
1334
1335 `patch.object` can be used as a decorator, class decorator or a context
1336 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1337 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1338 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1339 the mock object it creates.
1340
1341 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1342 for choosing which methods to wrap.
1343 """
1344 getter = lambda: target
1345 return _patch(
1346 getter, attribute, new, spec, create,
1347 spec_set, autospec, new_callable, kwargs
1348 )
1349
1350
Michael Foord50a8c0e2012-03-25 18:57:58 +01001351def _patch_multiple(target, spec=None, create=False, spec_set=None,
1352 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001353 """Perform multiple patches in a single call. It takes the object to be
1354 patched (either as an object or a string to fetch the object by importing)
1355 and keyword arguments for the patches::
1356
1357 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1358 ...
1359
1360 Use `DEFAULT` as the value if you want `patch.multiple` to create
1361 mocks for you. In this case the created mocks are passed into a decorated
1362 function by keyword, and a dictionary is returned when `patch.multiple` is
1363 used as a context manager.
1364
1365 `patch.multiple` can be used as a decorator, class decorator or a context
1366 manager. The arguments `spec`, `spec_set`, `create`,
1367 `autospec` and `new_callable` have the same meaning as for `patch`. These
1368 arguments will be applied to *all* patches done by `patch.multiple`.
1369
1370 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1371 for choosing which methods to wrap.
1372 """
1373 if type(target) is str:
1374 getter = lambda: _importer(target)
1375 else:
1376 getter = lambda: target
1377
1378 if not kwargs:
1379 raise ValueError(
1380 'Must supply at least one keyword argument with patch.multiple'
1381 )
1382 # need to wrap in a list for python 3, where items is a view
1383 items = list(kwargs.items())
1384 attribute, new = items[0]
1385 patcher = _patch(
1386 getter, attribute, new, spec, create, spec_set,
1387 autospec, new_callable, {}
1388 )
1389 patcher.attribute_name = attribute
1390 for attribute, new in items[1:]:
1391 this_patcher = _patch(
1392 getter, attribute, new, spec, create, spec_set,
1393 autospec, new_callable, {}
1394 )
1395 this_patcher.attribute_name = attribute
1396 patcher.additional_patchers.append(this_patcher)
1397 return patcher
1398
1399
1400def patch(
1401 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001402 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001403 ):
1404 """
1405 `patch` acts as a function decorator, class decorator or a context
1406 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001407 is patched with a `new` object. When the function/with statement exits
1408 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001409
Michael Foord54b3db82012-03-28 15:08:08 +01001410 If `new` is omitted, then the target is replaced with a
1411 `MagicMock`. If `patch` is used as a decorator and `new` is
1412 omitted, the created mock is passed in as an extra argument to the
1413 decorated function. If `patch` is used as a context manager the created
1414 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001415
Michael Foord54b3db82012-03-28 15:08:08 +01001416 `target` should be a string in the form `'package.module.ClassName'`. The
1417 `target` is imported and the specified object replaced with the `new`
1418 object, so the `target` must be importable from the environment you are
1419 calling `patch` from. The target is imported when the decorated function
1420 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001421
1422 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1423 if patch is creating one for you.
1424
1425 In addition you can pass `spec=True` or `spec_set=True`, which causes
1426 patch to pass in the object being mocked as the spec/spec_set object.
1427
1428 `new_callable` allows you to specify a different class, or callable object,
1429 that will be called to create the `new` object. By default `MagicMock` is
1430 used.
1431
1432 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1433 then the mock with be created with a spec from the object being replaced.
1434 All attributes of the mock will also have the spec of the corresponding
1435 attribute of the object being replaced. Methods and functions being
1436 mocked will have their arguments checked and will raise a `TypeError` if
1437 they are called with the wrong signature. For mocks replacing a class,
1438 their return value (the 'instance') will have the same spec as the class.
1439
1440 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1441 arbitrary object as the spec instead of the one being replaced.
1442
1443 By default `patch` will fail to replace attributes that don't exist. If
1444 you pass in `create=True`, and the attribute doesn't exist, patch will
1445 create the attribute for you when the patched function is called, and
1446 delete it again afterwards. This is useful for writing tests against
1447 attributes that your production code creates at runtime. It is off by by
1448 default because it can be dangerous. With it switched on you can write
1449 passing tests against APIs that don't actually exist!
1450
1451 Patch can be used as a `TestCase` class decorator. It works by
1452 decorating each test method in the class. This reduces the boilerplate
1453 code when your test methods share a common patchings set. `patch` finds
1454 tests by looking for method names that start with `patch.TEST_PREFIX`.
1455 By default this is `test`, which matches the way `unittest` finds tests.
1456 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1457
1458 Patch can be used as a context manager, with the with statement. Here the
1459 patching applies to the indented block after the with statement. If you
1460 use "as" then the patched object will be bound to the name after the
1461 "as"; very useful if `patch` is creating a mock object for you.
1462
1463 `patch` takes arbitrary keyword arguments. These will be passed to
1464 the `Mock` (or `new_callable`) on construction.
1465
1466 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1467 available for alternate use-cases.
1468 """
1469 getter, attribute = _get_target(target)
1470 return _patch(
1471 getter, attribute, new, spec, create,
1472 spec_set, autospec, new_callable, kwargs
1473 )
1474
1475
1476class _patch_dict(object):
1477 """
1478 Patch a dictionary, or dictionary like object, and restore the dictionary
1479 to its original state after the test.
1480
1481 `in_dict` can be a dictionary or a mapping like container. If it is a
1482 mapping then it must at least support getting, setting and deleting items
1483 plus iterating over keys.
1484
1485 `in_dict` can also be a string specifying the name of the dictionary, which
1486 will then be fetched by importing it.
1487
1488 `values` can be a dictionary of values to set in the dictionary. `values`
1489 can also be an iterable of `(key, value)` pairs.
1490
1491 If `clear` is True then the dictionary will be cleared before the new
1492 values are set.
1493
1494 `patch.dict` can also be called with arbitrary keyword arguments to set
1495 values in the dictionary::
1496
1497 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1498 ...
1499
1500 `patch.dict` can be used as a context manager, decorator or class
1501 decorator. When used as a class decorator `patch.dict` honours
1502 `patch.TEST_PREFIX` for choosing which methods to wrap.
1503 """
1504
1505 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1506 if isinstance(in_dict, str):
1507 in_dict = _importer(in_dict)
1508 self.in_dict = in_dict
1509 # support any argument supported by dict(...) constructor
1510 self.values = dict(values)
1511 self.values.update(kwargs)
1512 self.clear = clear
1513 self._original = None
1514
1515
1516 def __call__(self, f):
1517 if isinstance(f, type):
1518 return self.decorate_class(f)
1519 @wraps(f)
1520 def _inner(*args, **kw):
1521 self._patch_dict()
1522 try:
1523 return f(*args, **kw)
1524 finally:
1525 self._unpatch_dict()
1526
1527 return _inner
1528
1529
1530 def decorate_class(self, klass):
1531 for attr in dir(klass):
1532 attr_value = getattr(klass, attr)
1533 if (attr.startswith(patch.TEST_PREFIX) and
1534 hasattr(attr_value, "__call__")):
1535 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1536 decorated = decorator(attr_value)
1537 setattr(klass, attr, decorated)
1538 return klass
1539
1540
1541 def __enter__(self):
1542 """Patch the dict."""
1543 self._patch_dict()
1544
1545
1546 def _patch_dict(self):
1547 values = self.values
1548 in_dict = self.in_dict
1549 clear = self.clear
1550
1551 try:
1552 original = in_dict.copy()
1553 except AttributeError:
1554 # dict like object with no copy method
1555 # must support iteration over keys
1556 original = {}
1557 for key in in_dict:
1558 original[key] = in_dict[key]
1559 self._original = original
1560
1561 if clear:
1562 _clear_dict(in_dict)
1563
1564 try:
1565 in_dict.update(values)
1566 except AttributeError:
1567 # dict like object with no update method
1568 for key in values:
1569 in_dict[key] = values[key]
1570
1571
1572 def _unpatch_dict(self):
1573 in_dict = self.in_dict
1574 original = self._original
1575
1576 _clear_dict(in_dict)
1577
1578 try:
1579 in_dict.update(original)
1580 except AttributeError:
1581 for key in original:
1582 in_dict[key] = original[key]
1583
1584
1585 def __exit__(self, *args):
1586 """Unpatch the dict."""
1587 self._unpatch_dict()
1588 return False
1589
1590 start = __enter__
1591 stop = __exit__
1592
1593
1594def _clear_dict(in_dict):
1595 try:
1596 in_dict.clear()
1597 except AttributeError:
1598 keys = list(in_dict)
1599 for key in keys:
1600 del in_dict[key]
1601
1602
Michael Foordf7c41582012-06-10 20:36:32 +01001603def _patch_stopall():
1604 """Stop all active patches."""
1605 for patch in list(_patch._active_patches):
1606 patch.stop()
1607
1608
Michael Foord345266a2012-03-14 12:24:34 -07001609patch.object = _patch_object
1610patch.dict = _patch_dict
1611patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001612patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001613patch.TEST_PREFIX = 'test'
1614
1615magic_methods = (
1616 "lt le gt ge eq ne "
1617 "getitem setitem delitem "
1618 "len contains iter "
1619 "hash str sizeof "
1620 "enter exit "
1621 "divmod neg pos abs invert "
1622 "complex int float index "
1623 "trunc floor ceil "
1624 "bool next "
1625)
1626
1627numerics = "add sub mul div floordiv mod lshift rshift and xor or pow "
1628inplace = ' '.join('i%s' % n for n in numerics.split())
1629right = ' '.join('r%s' % n for n in numerics.split())
1630
1631# not including __prepare__, __instancecheck__, __subclasscheck__
1632# (as they are metaclass methods)
1633# __del__ is not supported at all as it causes problems if it exists
1634
1635_non_defaults = set('__%s__' % method for method in [
Michael Foord944e02d2012-03-25 23:12:55 +01001636 'get', 'set', 'delete', 'reversed', 'missing', 'reduce', 'reduce_ex',
1637 'getinitargs', 'getnewargs', 'getstate', 'setstate', 'getformat',
1638 'setformat', 'repr', 'dir', 'subclasses', 'format',
Michael Foord345266a2012-03-14 12:24:34 -07001639])
1640
1641
1642def _get_method(name, func):
1643 "Turns a callable object (like a mock) into a real function"
1644 def method(self, *args, **kw):
1645 return func(self, *args, **kw)
1646 method.__name__ = name
1647 return method
1648
1649
1650_magics = set(
1651 '__%s__' % method for method in
1652 ' '.join([magic_methods, numerics, inplace, right]).split()
1653)
1654
1655_all_magics = _magics | _non_defaults
1656
1657_unsupported_magics = set([
1658 '__getattr__', '__setattr__',
1659 '__init__', '__new__', '__prepare__'
1660 '__instancecheck__', '__subclasscheck__',
1661 '__del__'
1662])
1663
1664_calculate_return_value = {
1665 '__hash__': lambda self: object.__hash__(self),
1666 '__str__': lambda self: object.__str__(self),
1667 '__sizeof__': lambda self: object.__sizeof__(self),
1668}
1669
1670_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001671 '__lt__': NotImplemented,
1672 '__gt__': NotImplemented,
1673 '__le__': NotImplemented,
1674 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001675 '__int__': 1,
1676 '__contains__': False,
1677 '__len__': 0,
1678 '__exit__': False,
1679 '__complex__': 1j,
1680 '__float__': 1.0,
1681 '__bool__': True,
1682 '__index__': 1,
1683}
1684
1685
1686def _get_eq(self):
1687 def __eq__(other):
1688 ret_val = self.__eq__._mock_return_value
1689 if ret_val is not DEFAULT:
1690 return ret_val
1691 return self is other
1692 return __eq__
1693
1694def _get_ne(self):
1695 def __ne__(other):
1696 if self.__ne__._mock_return_value is not DEFAULT:
1697 return DEFAULT
1698 return self is not other
1699 return __ne__
1700
1701def _get_iter(self):
1702 def __iter__():
1703 ret_val = self.__iter__._mock_return_value
1704 if ret_val is DEFAULT:
1705 return iter([])
1706 # if ret_val was already an iterator, then calling iter on it should
1707 # return the iterator unchanged
1708 return iter(ret_val)
1709 return __iter__
1710
1711_side_effect_methods = {
1712 '__eq__': _get_eq,
1713 '__ne__': _get_ne,
1714 '__iter__': _get_iter,
1715}
1716
1717
1718
1719def _set_return_value(mock, method, name):
1720 fixed = _return_values.get(name, DEFAULT)
1721 if fixed is not DEFAULT:
1722 method.return_value = fixed
1723 return
1724
1725 return_calulator = _calculate_return_value.get(name)
1726 if return_calulator is not None:
1727 try:
1728 return_value = return_calulator(mock)
1729 except AttributeError:
1730 # XXXX why do we return AttributeError here?
1731 # set it as a side_effect instead?
1732 return_value = AttributeError(name)
1733 method.return_value = return_value
1734 return
1735
1736 side_effector = _side_effect_methods.get(name)
1737 if side_effector is not None:
1738 method.side_effect = side_effector(mock)
1739
1740
1741
1742class MagicMixin(object):
1743 def __init__(self, *args, **kw):
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001744 _safe_super(MagicMixin, self).__init__(*args, **kw)
Michael Foord345266a2012-03-14 12:24:34 -07001745 self._mock_set_magics()
1746
1747
1748 def _mock_set_magics(self):
1749 these_magics = _magics
1750
1751 if self._mock_methods is not None:
1752 these_magics = _magics.intersection(self._mock_methods)
1753
1754 remove_magics = set()
1755 remove_magics = _magics - these_magics
1756
1757 for entry in remove_magics:
1758 if entry in type(self).__dict__:
1759 # remove unneeded magic methods
1760 delattr(self, entry)
1761
1762 # don't overwrite existing attributes if called a second time
1763 these_magics = these_magics - set(type(self).__dict__)
1764
1765 _type = type(self)
1766 for entry in these_magics:
1767 setattr(_type, entry, MagicProxy(entry, self))
1768
1769
1770
1771class NonCallableMagicMock(MagicMixin, NonCallableMock):
1772 """A version of `MagicMock` that isn't callable."""
1773 def mock_add_spec(self, spec, spec_set=False):
1774 """Add a spec to a mock. `spec` can either be an object or a
1775 list of strings. Only attributes on the `spec` can be fetched as
1776 attributes from the mock.
1777
1778 If `spec_set` is True then only attributes on the spec can be set."""
1779 self._mock_add_spec(spec, spec_set)
1780 self._mock_set_magics()
1781
1782
1783
1784class MagicMock(MagicMixin, Mock):
1785 """
1786 MagicMock is a subclass of Mock with default implementations
1787 of most of the magic methods. You can use MagicMock without having to
1788 configure the magic methods yourself.
1789
1790 If you use the `spec` or `spec_set` arguments then *only* magic
1791 methods that exist in the spec will be created.
1792
1793 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1794 """
1795 def mock_add_spec(self, spec, spec_set=False):
1796 """Add a spec to a mock. `spec` can either be an object or a
1797 list of strings. Only attributes on the `spec` can be fetched as
1798 attributes from the mock.
1799
1800 If `spec_set` is True then only attributes on the spec can be set."""
1801 self._mock_add_spec(spec, spec_set)
1802 self._mock_set_magics()
1803
1804
1805
1806class MagicProxy(object):
1807 def __init__(self, name, parent):
1808 self.name = name
1809 self.parent = parent
1810
1811 def __call__(self, *args, **kwargs):
1812 m = self.create_mock()
1813 return m(*args, **kwargs)
1814
1815 def create_mock(self):
1816 entry = self.name
1817 parent = self.parent
1818 m = parent._get_child_mock(name=entry, _new_name=entry,
1819 _new_parent=parent)
1820 setattr(parent, entry, m)
1821 _set_return_value(parent, m, entry)
1822 return m
1823
1824 def __get__(self, obj, _type=None):
1825 return self.create_mock()
1826
1827
1828
1829class _ANY(object):
1830 "A helper object that compares equal to everything."
1831
1832 def __eq__(self, other):
1833 return True
1834
1835 def __ne__(self, other):
1836 return False
1837
1838 def __repr__(self):
1839 return '<ANY>'
1840
1841ANY = _ANY()
1842
1843
1844
1845def _format_call_signature(name, args, kwargs):
1846 message = '%s(%%s)' % name
1847 formatted_args = ''
1848 args_string = ', '.join([repr(arg) for arg in args])
1849 kwargs_string = ', '.join([
1850 '%s=%r' % (key, value) for key, value in kwargs.items()
1851 ])
1852 if args_string:
1853 formatted_args = args_string
1854 if kwargs_string:
1855 if formatted_args:
1856 formatted_args += ', '
1857 formatted_args += kwargs_string
1858
1859 return message % formatted_args
1860
1861
1862
1863class _Call(tuple):
1864 """
1865 A tuple for holding the results of a call to a mock, either in the form
1866 `(args, kwargs)` or `(name, args, kwargs)`.
1867
1868 If args or kwargs are empty then a call tuple will compare equal to
1869 a tuple without those values. This makes comparisons less verbose::
1870
1871 _Call(('name', (), {})) == ('name',)
1872 _Call(('name', (1,), {})) == ('name', (1,))
1873 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1874
1875 The `_Call` object provides a useful shortcut for comparing with call::
1876
1877 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1878 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1879
1880 If the _Call has no name then it will match any name.
1881 """
1882 def __new__(cls, value=(), name=None, parent=None, two=False,
1883 from_kall=True):
1884 name = ''
1885 args = ()
1886 kwargs = {}
1887 _len = len(value)
1888 if _len == 3:
1889 name, args, kwargs = value
1890 elif _len == 2:
1891 first, second = value
1892 if isinstance(first, str):
1893 name = first
1894 if isinstance(second, tuple):
1895 args = second
1896 else:
1897 kwargs = second
1898 else:
1899 args, kwargs = first, second
1900 elif _len == 1:
1901 value, = value
1902 if isinstance(value, str):
1903 name = value
1904 elif isinstance(value, tuple):
1905 args = value
1906 else:
1907 kwargs = value
1908
1909 if two:
1910 return tuple.__new__(cls, (args, kwargs))
1911
1912 return tuple.__new__(cls, (name, args, kwargs))
1913
1914
1915 def __init__(self, value=(), name=None, parent=None, two=False,
1916 from_kall=True):
1917 self.name = name
1918 self.parent = parent
1919 self.from_kall = from_kall
1920
1921
1922 def __eq__(self, other):
1923 if other is ANY:
1924 return True
1925 try:
1926 len_other = len(other)
1927 except TypeError:
1928 return False
1929
1930 self_name = ''
1931 if len(self) == 2:
1932 self_args, self_kwargs = self
1933 else:
1934 self_name, self_args, self_kwargs = self
1935
1936 other_name = ''
1937 if len_other == 0:
1938 other_args, other_kwargs = (), {}
1939 elif len_other == 3:
1940 other_name, other_args, other_kwargs = other
1941 elif len_other == 1:
1942 value, = other
1943 if isinstance(value, tuple):
1944 other_args = value
1945 other_kwargs = {}
1946 elif isinstance(value, str):
1947 other_name = value
1948 other_args, other_kwargs = (), {}
1949 else:
1950 other_args = ()
1951 other_kwargs = value
1952 else:
1953 # len 2
1954 # could be (name, args) or (name, kwargs) or (args, kwargs)
1955 first, second = other
1956 if isinstance(first, str):
1957 other_name = first
1958 if isinstance(second, tuple):
1959 other_args, other_kwargs = second, {}
1960 else:
1961 other_args, other_kwargs = (), second
1962 else:
1963 other_args, other_kwargs = first, second
1964
1965 if self_name and other_name != self_name:
1966 return False
1967
1968 # this order is important for ANY to work!
1969 return (other_args, other_kwargs) == (self_args, self_kwargs)
1970
1971
1972 def __ne__(self, other):
1973 return not self.__eq__(other)
1974
1975
1976 def __call__(self, *args, **kwargs):
1977 if self.name is None:
1978 return _Call(('', args, kwargs), name='()')
1979
1980 name = self.name + '()'
1981 return _Call((self.name, args, kwargs), name=name, parent=self)
1982
1983
1984 def __getattr__(self, attr):
1985 if self.name is None:
1986 return _Call(name=attr, from_kall=False)
1987 name = '%s.%s' % (self.name, attr)
1988 return _Call(name=name, parent=self, from_kall=False)
1989
1990
1991 def __repr__(self):
1992 if not self.from_kall:
1993 name = self.name or 'call'
1994 if name.startswith('()'):
1995 name = 'call%s' % name
1996 return name
1997
1998 if len(self) == 2:
1999 name = 'call'
2000 args, kwargs = self
2001 else:
2002 name, args, kwargs = self
2003 if not name:
2004 name = 'call'
2005 elif not name.startswith('()'):
2006 name = 'call.%s' % name
2007 else:
2008 name = 'call%s' % name
2009 return _format_call_signature(name, args, kwargs)
2010
2011
2012 def call_list(self):
2013 """For a call object that represents multiple calls, `call_list`
2014 returns a list of all the intermediate calls as well as the
2015 final call."""
2016 vals = []
2017 thing = self
2018 while thing is not None:
2019 if thing.from_kall:
2020 vals.append(thing)
2021 thing = thing.parent
2022 return _CallList(reversed(vals))
2023
2024
2025call = _Call(from_kall=False)
2026
2027
2028
2029def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2030 _name=None, **kwargs):
2031 """Create a mock object using another object as a spec. Attributes on the
2032 mock will use the corresponding attribute on the `spec` object as their
2033 spec.
2034
2035 Functions or methods being mocked will have their arguments checked
2036 to check that they are called with the correct signature.
2037
2038 If `spec_set` is True then attempting to set attributes that don't exist
2039 on the spec object will raise an `AttributeError`.
2040
2041 If a class is used as a spec then the return value of the mock (the
2042 instance of the class) will have the same spec. You can use a class as the
2043 spec for an instance object by passing `instance=True`. The returned mock
2044 will only be callable if instances of the mock are callable.
2045
2046 `create_autospec` also takes arbitrary keyword arguments that are passed to
2047 the constructor of the created mock."""
2048 if _is_list(spec):
2049 # can't pass a list instance to the mock constructor as it will be
2050 # interpreted as a list of strings
2051 spec = type(spec)
2052
2053 is_type = isinstance(spec, type)
2054
2055 _kwargs = {'spec': spec}
2056 if spec_set:
2057 _kwargs = {'spec_set': spec}
2058 elif spec is None:
2059 # None we mock with a normal mock without a spec
2060 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002061 if _kwargs and instance:
2062 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002063
2064 _kwargs.update(kwargs)
2065
2066 Klass = MagicMock
2067 if type(spec) in DescriptorTypes:
2068 # descriptors don't have a spec
2069 # because we don't know what type they return
2070 _kwargs = {}
2071 elif not _callable(spec):
2072 Klass = NonCallableMagicMock
2073 elif is_type and instance and not _instance_callable(spec):
2074 Klass = NonCallableMagicMock
2075
2076 _new_name = _name
2077 if _parent is None:
2078 # for a top level object no _new_name should be set
2079 _new_name = ''
2080
2081 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2082 name=_name, **_kwargs)
2083
2084 if isinstance(spec, FunctionTypes):
2085 # should only happen at the top level because we don't
2086 # recurse for functions
2087 mock = _set_signature(mock, spec)
2088 else:
2089 _check_signature(spec, mock, is_type, instance)
2090
2091 if _parent is not None and not instance:
2092 _parent._mock_children[_name] = mock
2093
2094 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002095 mock.return_value = create_autospec(spec, spec_set, instance=True,
2096 _name='()', _parent=mock)
2097
2098 for entry in dir(spec):
2099 if _is_magic(entry):
2100 # MagicMock already does the useful magic methods for us
2101 continue
2102
Michael Foord345266a2012-03-14 12:24:34 -07002103 # XXXX do we need a better way of getting attributes without
2104 # triggering code execution (?) Probably not - we need the actual
2105 # object to mock it so we would rather trigger a property than mock
2106 # the property descriptor. Likewise we want to mock out dynamically
2107 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002108 # XXXX what about attributes that raise exceptions other than
2109 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002110 # we could be resilient against it, or catch and propagate the
2111 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002112 try:
2113 original = getattr(spec, entry)
2114 except AttributeError:
2115 continue
Michael Foord345266a2012-03-14 12:24:34 -07002116
2117 kwargs = {'spec': original}
2118 if spec_set:
2119 kwargs = {'spec_set': original}
2120
2121 if not isinstance(original, FunctionTypes):
2122 new = _SpecState(original, spec_set, mock, entry, instance)
2123 mock._mock_children[entry] = new
2124 else:
2125 parent = mock
2126 if isinstance(spec, FunctionTypes):
2127 parent = mock.mock
2128
Michael Foord345266a2012-03-14 12:24:34 -07002129 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002130 kwargs['_eat_self'] = skipfirst
2131 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2132 _new_parent=parent,
2133 **kwargs)
2134 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002135 _check_signature(original, new, skipfirst=skipfirst)
2136
2137 # so functions created with _set_signature become instance attributes,
2138 # *plus* their underlying mock exists in _mock_children of the parent
2139 # mock. Adding to _mock_children may be unnecessary where we are also
2140 # setting as an instance attribute?
2141 if isinstance(new, FunctionTypes):
2142 setattr(mock, entry, new)
2143
2144 return mock
2145
2146
2147def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002148 """
2149 Return whether we should skip the first argument on spec's `entry`
2150 attribute.
2151 """
Michael Foord345266a2012-03-14 12:24:34 -07002152 if not isinstance(spec, type):
2153 if entry in getattr(spec, '__dict__', {}):
2154 # instance attribute - shouldn't skip
2155 return False
Michael Foord345266a2012-03-14 12:24:34 -07002156 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002157
2158 for klass in spec.__mro__:
2159 result = klass.__dict__.get(entry, DEFAULT)
2160 if result is DEFAULT:
2161 continue
2162 if isinstance(result, (staticmethod, classmethod)):
2163 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002164 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2165 # Normal method => skip if looked up on type
2166 # (if looked up on instance, self is already skipped)
2167 return is_type
2168 else:
2169 return False
Michael Foord345266a2012-03-14 12:24:34 -07002170
2171 # shouldn't get here unless function is a dynamically provided attribute
2172 # XXXX untested behaviour
2173 return is_type
2174
2175
2176def _get_class(obj):
2177 try:
2178 return obj.__class__
2179 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002180 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002181 return type(obj)
2182
2183
2184class _SpecState(object):
2185
2186 def __init__(self, spec, spec_set=False, parent=None,
2187 name=None, ids=None, instance=False):
2188 self.spec = spec
2189 self.ids = ids
2190 self.spec_set = spec_set
2191 self.parent = parent
2192 self.instance = instance
2193 self.name = name
2194
2195
2196FunctionTypes = (
2197 # python function
2198 type(create_autospec),
2199 # instance method
2200 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002201)
2202
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002203MethodWrapperTypes = (
2204 type(ANY.__eq__.__get__),
2205)
2206
Michael Foord345266a2012-03-14 12:24:34 -07002207
Michael Foorda74561a2012-03-25 19:03:13 +01002208file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002209
Michael Foord0dccf652012-03-25 19:11:50 +01002210
2211def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002212 """
2213 A helper function to create a mock to replace the use of `open`. It works
2214 for `open` called directly or used as a context manager.
2215
2216 The `mock` argument is the mock object to configure. If `None` (the
2217 default) then a `MagicMock` will be created for you, with the API limited
2218 to methods or attributes available on standard file handles.
2219
2220 `read_data` is a string for the `read` method of the file handle to return.
2221 This is an empty string by default.
2222 """
Michael Foorda74561a2012-03-25 19:03:13 +01002223 global file_spec
2224 if file_spec is None:
2225 import _io
2226 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2227
Michael Foord345266a2012-03-14 12:24:34 -07002228 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002229 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002230
2231 handle = MagicMock(spec=file_spec)
2232 handle.write.return_value = None
2233 handle.__enter__.return_value = handle
Michael Foord0dccf652012-03-25 19:11:50 +01002234 handle.read.return_value = read_data
Michael Foord345266a2012-03-14 12:24:34 -07002235
2236 mock.return_value = handle
2237 return mock
2238
2239
2240class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002241 """
2242 A mock intended to be used as a property, or other descriptor, on a class.
2243 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2244 a return value when it is fetched.
2245
2246 Fetching a `PropertyMock` instance from an object calls the mock, with
2247 no args. Setting it calls the mock with the value being set.
2248 """
Michael Foordc2870622012-04-13 16:57:22 +01002249 def _get_child_mock(self, **kwargs):
2250 return MagicMock(**kwargs)
2251
Michael Foord345266a2012-03-14 12:24:34 -07002252 def __get__(self, obj, obj_type):
2253 return self()
2254 def __set__(self, obj, val):
2255 self(val)