blob: 2b1effb8b6bcf707c3e113dbbb4def3f8826bf9e [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)
Michael Foord345266a2012-03-14 12:24:34 -0700937
938 if (self._mock_wraps is not None and
939 self._mock_return_value is DEFAULT):
940 return self._mock_wraps(*args, **kwargs)
941 if ret_val is DEFAULT:
942 ret_val = self.return_value
943 return ret_val
944
945
946
947class Mock(CallableMixin, NonCallableMock):
948 """
949 Create a new `Mock` object. `Mock` takes several optional arguments
950 that specify the behaviour of the Mock object:
951
952 * `spec`: This can be either a list of strings or an existing object (a
953 class or instance) that acts as the specification for the mock object. If
954 you pass in an object then a list of strings is formed by calling dir on
955 the object (excluding unsupported magic attributes and methods). Accessing
956 any attribute not in this list will raise an `AttributeError`.
957
958 If `spec` is an object (rather than a list of strings) then
959 `mock.__class__` returns the class of the spec object. This allows mocks
960 to pass `isinstance` tests.
961
962 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
963 or get an attribute on the mock that isn't on the object passed as
964 `spec_set` will raise an `AttributeError`.
965
966 * `side_effect`: A function to be called whenever the Mock is called. See
967 the `side_effect` attribute. Useful for raising exceptions or
968 dynamically changing return values. The function is called with the same
969 arguments as the mock, and unless it returns `DEFAULT`, the return
970 value of this function is used as the return value.
971
Michael Foord2cd48732012-04-21 15:52:11 +0100972 If `side_effect` is an iterable then each call to the mock will return
973 the next value from the iterable. If any of the members of the iterable
974 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -0700975
976 If `side_effect` is an iterable then each call to the mock will return
977 the next value from the iterable.
978
979 * `return_value`: The value returned when the mock is called. By default
980 this is a new Mock (created on first access). See the
981 `return_value` attribute.
982
Michael Foord0682a0c2012-04-13 20:51:20 +0100983 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
984 calling the Mock will pass the call through to the wrapped object
985 (returning the real result). Attribute access on the mock will return a
986 Mock object that wraps the corresponding attribute of the wrapped object
987 (so attempting to access an attribute that doesn't exist will raise an
988 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -0700989
990 If the mock has an explicit `return_value` set then calls are not passed
991 to the wrapped object and the `return_value` is returned instead.
992
993 * `name`: If the mock has a name then it will be used in the repr of the
994 mock. This can be useful for debugging. The name is propagated to child
995 mocks.
996
997 Mocks can also be called with arbitrary keyword arguments. These will be
998 used to set attributes on the mock after it is created.
999 """
1000
1001
1002
1003def _dot_lookup(thing, comp, import_path):
1004 try:
1005 return getattr(thing, comp)
1006 except AttributeError:
1007 __import__(import_path)
1008 return getattr(thing, comp)
1009
1010
1011def _importer(target):
1012 components = target.split('.')
1013 import_path = components.pop(0)
1014 thing = __import__(import_path)
1015
1016 for comp in components:
1017 import_path += ".%s" % comp
1018 thing = _dot_lookup(thing, comp, import_path)
1019 return thing
1020
1021
1022def _is_started(patcher):
1023 # XXXX horrible
1024 return hasattr(patcher, 'is_local')
1025
1026
1027class _patch(object):
1028
1029 attribute_name = None
Michael Foordf7c41582012-06-10 20:36:32 +01001030 _active_patches = set()
Michael Foord345266a2012-03-14 12:24:34 -07001031
1032 def __init__(
1033 self, getter, attribute, new, spec, create,
1034 spec_set, autospec, new_callable, kwargs
1035 ):
1036 if new_callable is not None:
1037 if new is not DEFAULT:
1038 raise ValueError(
1039 "Cannot use 'new' and 'new_callable' together"
1040 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001041 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001042 raise ValueError(
1043 "Cannot use 'autospec' and 'new_callable' together"
1044 )
1045
1046 self.getter = getter
1047 self.attribute = attribute
1048 self.new = new
1049 self.new_callable = new_callable
1050 self.spec = spec
1051 self.create = create
1052 self.has_local = False
1053 self.spec_set = spec_set
1054 self.autospec = autospec
1055 self.kwargs = kwargs
1056 self.additional_patchers = []
1057
1058
1059 def copy(self):
1060 patcher = _patch(
1061 self.getter, self.attribute, self.new, self.spec,
1062 self.create, self.spec_set,
1063 self.autospec, self.new_callable, self.kwargs
1064 )
1065 patcher.attribute_name = self.attribute_name
1066 patcher.additional_patchers = [
1067 p.copy() for p in self.additional_patchers
1068 ]
1069 return patcher
1070
1071
1072 def __call__(self, func):
1073 if isinstance(func, type):
1074 return self.decorate_class(func)
1075 return self.decorate_callable(func)
1076
1077
1078 def decorate_class(self, klass):
1079 for attr in dir(klass):
1080 if not attr.startswith(patch.TEST_PREFIX):
1081 continue
1082
1083 attr_value = getattr(klass, attr)
1084 if not hasattr(attr_value, "__call__"):
1085 continue
1086
1087 patcher = self.copy()
1088 setattr(klass, attr, patcher(attr_value))
1089 return klass
1090
1091
1092 def decorate_callable(self, func):
1093 if hasattr(func, 'patchings'):
1094 func.patchings.append(self)
1095 return func
1096
1097 @wraps(func)
1098 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001099 extra_args = []
1100 entered_patchers = []
1101
Michael Foord50a8c0e2012-03-25 18:57:58 +01001102 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001103 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001104 for patching in patched.patchings:
1105 arg = patching.__enter__()
1106 entered_patchers.append(patching)
1107 if patching.attribute_name is not None:
1108 keywargs.update(arg)
1109 elif patching.new is DEFAULT:
1110 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001111
Michael Foordd7c65e22012-03-14 14:56:54 -07001112 args += tuple(extra_args)
1113 return func(*args, **keywargs)
1114 except:
1115 if (patching not in entered_patchers and
1116 _is_started(patching)):
1117 # the patcher may have been started, but an exception
1118 # raised whilst entering one of its additional_patchers
1119 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001120 # Pass the exception to __exit__
1121 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001122 # re-raise the exception
1123 raise
Michael Foord345266a2012-03-14 12:24:34 -07001124 finally:
1125 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001126 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001127
1128 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001129 return patched
1130
1131
1132 def get_original(self):
1133 target = self.getter()
1134 name = self.attribute
1135
1136 original = DEFAULT
1137 local = False
1138
1139 try:
1140 original = target.__dict__[name]
1141 except (AttributeError, KeyError):
1142 original = getattr(target, name, DEFAULT)
1143 else:
1144 local = True
1145
1146 if not self.create and original is DEFAULT:
1147 raise AttributeError(
1148 "%s does not have the attribute %r" % (target, name)
1149 )
1150 return original, local
1151
1152
1153 def __enter__(self):
1154 """Perform the patch."""
1155 new, spec, spec_set = self.new, self.spec, self.spec_set
1156 autospec, kwargs = self.autospec, self.kwargs
1157 new_callable = self.new_callable
1158 self.target = self.getter()
1159
Michael Foord50a8c0e2012-03-25 18:57:58 +01001160 # normalise False to None
1161 if spec is False:
1162 spec = None
1163 if spec_set is False:
1164 spec_set = None
1165 if autospec is False:
1166 autospec = None
1167
1168 if spec is not None and autospec is not None:
1169 raise TypeError("Can't specify spec and autospec")
1170 if ((spec is not None or autospec is not None) and
1171 spec_set not in (True, None)):
1172 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1173
Michael Foord345266a2012-03-14 12:24:34 -07001174 original, local = self.get_original()
1175
Michael Foord50a8c0e2012-03-25 18:57:58 +01001176 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001177 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001178 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001179 # set spec to the object we are replacing
1180 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001181 if spec_set is True:
1182 spec_set = original
1183 spec = None
1184 elif spec is not None:
1185 if spec_set is True:
1186 spec_set = spec
1187 spec = None
1188 elif spec_set is True:
1189 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001190
Michael Foord50a8c0e2012-03-25 18:57:58 +01001191 if spec is not None or spec_set is not None:
1192 if original is DEFAULT:
1193 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001194 if isinstance(original, type):
1195 # If we're patching out a class and there is a spec
1196 inherit = True
1197
1198 Klass = MagicMock
1199 _kwargs = {}
1200 if new_callable is not None:
1201 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001202 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001203 this_spec = spec
1204 if spec_set is not None:
1205 this_spec = spec_set
1206 if _is_list(this_spec):
1207 not_callable = '__call__' not in this_spec
1208 else:
1209 not_callable = not callable(this_spec)
1210 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001211 Klass = NonCallableMagicMock
1212
1213 if spec is not None:
1214 _kwargs['spec'] = spec
1215 if spec_set is not None:
1216 _kwargs['spec_set'] = spec_set
1217
1218 # add a name to mocks
1219 if (isinstance(Klass, type) and
1220 issubclass(Klass, NonCallableMock) and self.attribute):
1221 _kwargs['name'] = self.attribute
1222
1223 _kwargs.update(kwargs)
1224 new = Klass(**_kwargs)
1225
1226 if inherit and _is_instance_mock(new):
1227 # we can only tell if the instance should be callable if the
1228 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001229 this_spec = spec
1230 if spec_set is not None:
1231 this_spec = spec_set
1232 if (not _is_list(this_spec) and not
1233 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001234 Klass = NonCallableMagicMock
1235
1236 _kwargs.pop('name')
1237 new.return_value = Klass(_new_parent=new, _new_name='()',
1238 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001239 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001240 # spec is ignored, new *must* be default, spec_set is treated
1241 # as a boolean. Should we check spec is not None and that spec_set
1242 # is a bool?
1243 if new is not DEFAULT:
1244 raise TypeError(
1245 "autospec creates the mock for you. Can't specify "
1246 "autospec and new."
1247 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001248 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001249 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001250 spec_set = bool(spec_set)
1251 if autospec is True:
1252 autospec = original
1253
1254 new = create_autospec(autospec, spec_set=spec_set,
1255 _name=self.attribute, **kwargs)
1256 elif kwargs:
1257 # can't set keyword args when we aren't creating the mock
1258 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1259 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1260
1261 new_attr = new
1262
1263 self.temp_original = original
1264 self.is_local = local
1265 setattr(self.target, self.attribute, new_attr)
1266 if self.attribute_name is not None:
1267 extra_args = {}
1268 if self.new is DEFAULT:
1269 extra_args[self.attribute_name] = new
1270 for patching in self.additional_patchers:
1271 arg = patching.__enter__()
1272 if patching.new is DEFAULT:
1273 extra_args.update(arg)
1274 return extra_args
1275
1276 return new
1277
1278
Michael Foord50a8c0e2012-03-25 18:57:58 +01001279 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001280 """Undo the patch."""
1281 if not _is_started(self):
1282 raise RuntimeError('stop called on unstarted patcher')
1283
1284 if self.is_local and self.temp_original is not DEFAULT:
1285 setattr(self.target, self.attribute, self.temp_original)
1286 else:
1287 delattr(self.target, self.attribute)
1288 if not self.create and not hasattr(self.target, self.attribute):
1289 # needed for proxy objects like django settings
1290 setattr(self.target, self.attribute, self.temp_original)
1291
1292 del self.temp_original
1293 del self.is_local
1294 del self.target
1295 for patcher in reversed(self.additional_patchers):
1296 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001297 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001298
Michael Foordf7c41582012-06-10 20:36:32 +01001299
1300 def start(self):
1301 """Activate a patch, returning any created mock."""
1302 result = self.__enter__()
1303 self._active_patches.add(self)
1304 return result
1305
1306
1307 def stop(self):
1308 """Stop an active patch."""
1309 self._active_patches.discard(self)
1310 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001311
1312
1313
1314def _get_target(target):
1315 try:
1316 target, attribute = target.rsplit('.', 1)
1317 except (TypeError, ValueError):
1318 raise TypeError("Need a valid target to patch. You supplied: %r" %
1319 (target,))
1320 getter = lambda: _importer(target)
1321 return getter, attribute
1322
1323
1324def _patch_object(
1325 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001326 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001327 new_callable=None, **kwargs
1328 ):
1329 """
Michael Foord345266a2012-03-14 12:24:34 -07001330 patch the named member (`attribute`) on an object (`target`) with a mock
1331 object.
1332
1333 `patch.object` can be used as a decorator, class decorator or a context
1334 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1335 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1336 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1337 the mock object it creates.
1338
1339 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1340 for choosing which methods to wrap.
1341 """
1342 getter = lambda: target
1343 return _patch(
1344 getter, attribute, new, spec, create,
1345 spec_set, autospec, new_callable, kwargs
1346 )
1347
1348
Michael Foord50a8c0e2012-03-25 18:57:58 +01001349def _patch_multiple(target, spec=None, create=False, spec_set=None,
1350 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001351 """Perform multiple patches in a single call. It takes the object to be
1352 patched (either as an object or a string to fetch the object by importing)
1353 and keyword arguments for the patches::
1354
1355 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1356 ...
1357
1358 Use `DEFAULT` as the value if you want `patch.multiple` to create
1359 mocks for you. In this case the created mocks are passed into a decorated
1360 function by keyword, and a dictionary is returned when `patch.multiple` is
1361 used as a context manager.
1362
1363 `patch.multiple` can be used as a decorator, class decorator or a context
1364 manager. The arguments `spec`, `spec_set`, `create`,
1365 `autospec` and `new_callable` have the same meaning as for `patch`. These
1366 arguments will be applied to *all* patches done by `patch.multiple`.
1367
1368 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1369 for choosing which methods to wrap.
1370 """
1371 if type(target) is str:
1372 getter = lambda: _importer(target)
1373 else:
1374 getter = lambda: target
1375
1376 if not kwargs:
1377 raise ValueError(
1378 'Must supply at least one keyword argument with patch.multiple'
1379 )
1380 # need to wrap in a list for python 3, where items is a view
1381 items = list(kwargs.items())
1382 attribute, new = items[0]
1383 patcher = _patch(
1384 getter, attribute, new, spec, create, spec_set,
1385 autospec, new_callable, {}
1386 )
1387 patcher.attribute_name = attribute
1388 for attribute, new in items[1:]:
1389 this_patcher = _patch(
1390 getter, attribute, new, spec, create, spec_set,
1391 autospec, new_callable, {}
1392 )
1393 this_patcher.attribute_name = attribute
1394 patcher.additional_patchers.append(this_patcher)
1395 return patcher
1396
1397
1398def patch(
1399 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001400 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001401 ):
1402 """
1403 `patch` acts as a function decorator, class decorator or a context
1404 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001405 is patched with a `new` object. When the function/with statement exits
1406 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001407
Michael Foord54b3db82012-03-28 15:08:08 +01001408 If `new` is omitted, then the target is replaced with a
1409 `MagicMock`. If `patch` is used as a decorator and `new` is
1410 omitted, the created mock is passed in as an extra argument to the
1411 decorated function. If `patch` is used as a context manager the created
1412 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001413
Michael Foord54b3db82012-03-28 15:08:08 +01001414 `target` should be a string in the form `'package.module.ClassName'`. The
1415 `target` is imported and the specified object replaced with the `new`
1416 object, so the `target` must be importable from the environment you are
1417 calling `patch` from. The target is imported when the decorated function
1418 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001419
1420 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1421 if patch is creating one for you.
1422
1423 In addition you can pass `spec=True` or `spec_set=True`, which causes
1424 patch to pass in the object being mocked as the spec/spec_set object.
1425
1426 `new_callable` allows you to specify a different class, or callable object,
1427 that will be called to create the `new` object. By default `MagicMock` is
1428 used.
1429
1430 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1431 then the mock with be created with a spec from the object being replaced.
1432 All attributes of the mock will also have the spec of the corresponding
1433 attribute of the object being replaced. Methods and functions being
1434 mocked will have their arguments checked and will raise a `TypeError` if
1435 they are called with the wrong signature. For mocks replacing a class,
1436 their return value (the 'instance') will have the same spec as the class.
1437
1438 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1439 arbitrary object as the spec instead of the one being replaced.
1440
1441 By default `patch` will fail to replace attributes that don't exist. If
1442 you pass in `create=True`, and the attribute doesn't exist, patch will
1443 create the attribute for you when the patched function is called, and
1444 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001445 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001446 default because it can be dangerous. With it switched on you can write
1447 passing tests against APIs that don't actually exist!
1448
1449 Patch can be used as a `TestCase` class decorator. It works by
1450 decorating each test method in the class. This reduces the boilerplate
1451 code when your test methods share a common patchings set. `patch` finds
1452 tests by looking for method names that start with `patch.TEST_PREFIX`.
1453 By default this is `test`, which matches the way `unittest` finds tests.
1454 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1455
1456 Patch can be used as a context manager, with the with statement. Here the
1457 patching applies to the indented block after the with statement. If you
1458 use "as" then the patched object will be bound to the name after the
1459 "as"; very useful if `patch` is creating a mock object for you.
1460
1461 `patch` takes arbitrary keyword arguments. These will be passed to
1462 the `Mock` (or `new_callable`) on construction.
1463
1464 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1465 available for alternate use-cases.
1466 """
1467 getter, attribute = _get_target(target)
1468 return _patch(
1469 getter, attribute, new, spec, create,
1470 spec_set, autospec, new_callable, kwargs
1471 )
1472
1473
1474class _patch_dict(object):
1475 """
1476 Patch a dictionary, or dictionary like object, and restore the dictionary
1477 to its original state after the test.
1478
1479 `in_dict` can be a dictionary or a mapping like container. If it is a
1480 mapping then it must at least support getting, setting and deleting items
1481 plus iterating over keys.
1482
1483 `in_dict` can also be a string specifying the name of the dictionary, which
1484 will then be fetched by importing it.
1485
1486 `values` can be a dictionary of values to set in the dictionary. `values`
1487 can also be an iterable of `(key, value)` pairs.
1488
1489 If `clear` is True then the dictionary will be cleared before the new
1490 values are set.
1491
1492 `patch.dict` can also be called with arbitrary keyword arguments to set
1493 values in the dictionary::
1494
1495 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1496 ...
1497
1498 `patch.dict` can be used as a context manager, decorator or class
1499 decorator. When used as a class decorator `patch.dict` honours
1500 `patch.TEST_PREFIX` for choosing which methods to wrap.
1501 """
1502
1503 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1504 if isinstance(in_dict, str):
1505 in_dict = _importer(in_dict)
1506 self.in_dict = in_dict
1507 # support any argument supported by dict(...) constructor
1508 self.values = dict(values)
1509 self.values.update(kwargs)
1510 self.clear = clear
1511 self._original = None
1512
1513
1514 def __call__(self, f):
1515 if isinstance(f, type):
1516 return self.decorate_class(f)
1517 @wraps(f)
1518 def _inner(*args, **kw):
1519 self._patch_dict()
1520 try:
1521 return f(*args, **kw)
1522 finally:
1523 self._unpatch_dict()
1524
1525 return _inner
1526
1527
1528 def decorate_class(self, klass):
1529 for attr in dir(klass):
1530 attr_value = getattr(klass, attr)
1531 if (attr.startswith(patch.TEST_PREFIX) and
1532 hasattr(attr_value, "__call__")):
1533 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1534 decorated = decorator(attr_value)
1535 setattr(klass, attr, decorated)
1536 return klass
1537
1538
1539 def __enter__(self):
1540 """Patch the dict."""
1541 self._patch_dict()
1542
1543
1544 def _patch_dict(self):
1545 values = self.values
1546 in_dict = self.in_dict
1547 clear = self.clear
1548
1549 try:
1550 original = in_dict.copy()
1551 except AttributeError:
1552 # dict like object with no copy method
1553 # must support iteration over keys
1554 original = {}
1555 for key in in_dict:
1556 original[key] = in_dict[key]
1557 self._original = original
1558
1559 if clear:
1560 _clear_dict(in_dict)
1561
1562 try:
1563 in_dict.update(values)
1564 except AttributeError:
1565 # dict like object with no update method
1566 for key in values:
1567 in_dict[key] = values[key]
1568
1569
1570 def _unpatch_dict(self):
1571 in_dict = self.in_dict
1572 original = self._original
1573
1574 _clear_dict(in_dict)
1575
1576 try:
1577 in_dict.update(original)
1578 except AttributeError:
1579 for key in original:
1580 in_dict[key] = original[key]
1581
1582
1583 def __exit__(self, *args):
1584 """Unpatch the dict."""
1585 self._unpatch_dict()
1586 return False
1587
1588 start = __enter__
1589 stop = __exit__
1590
1591
1592def _clear_dict(in_dict):
1593 try:
1594 in_dict.clear()
1595 except AttributeError:
1596 keys = list(in_dict)
1597 for key in keys:
1598 del in_dict[key]
1599
1600
Michael Foordf7c41582012-06-10 20:36:32 +01001601def _patch_stopall():
1602 """Stop all active patches."""
1603 for patch in list(_patch._active_patches):
1604 patch.stop()
1605
1606
Michael Foord345266a2012-03-14 12:24:34 -07001607patch.object = _patch_object
1608patch.dict = _patch_dict
1609patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001610patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001611patch.TEST_PREFIX = 'test'
1612
1613magic_methods = (
1614 "lt le gt ge eq ne "
1615 "getitem setitem delitem "
1616 "len contains iter "
1617 "hash str sizeof "
1618 "enter exit "
1619 "divmod neg pos abs invert "
1620 "complex int float index "
1621 "trunc floor ceil "
1622 "bool next "
1623)
1624
1625numerics = "add sub mul div floordiv mod lshift rshift and xor or pow "
1626inplace = ' '.join('i%s' % n for n in numerics.split())
1627right = ' '.join('r%s' % n for n in numerics.split())
1628
1629# not including __prepare__, __instancecheck__, __subclasscheck__
1630# (as they are metaclass methods)
1631# __del__ is not supported at all as it causes problems if it exists
1632
1633_non_defaults = set('__%s__' % method for method in [
Michael Foord944e02d2012-03-25 23:12:55 +01001634 'get', 'set', 'delete', 'reversed', 'missing', 'reduce', 'reduce_ex',
1635 'getinitargs', 'getnewargs', 'getstate', 'setstate', 'getformat',
1636 'setformat', 'repr', 'dir', 'subclasses', 'format',
Michael Foord345266a2012-03-14 12:24:34 -07001637])
1638
1639
1640def _get_method(name, func):
1641 "Turns a callable object (like a mock) into a real function"
1642 def method(self, *args, **kw):
1643 return func(self, *args, **kw)
1644 method.__name__ = name
1645 return method
1646
1647
1648_magics = set(
1649 '__%s__' % method for method in
1650 ' '.join([magic_methods, numerics, inplace, right]).split()
1651)
1652
1653_all_magics = _magics | _non_defaults
1654
1655_unsupported_magics = set([
1656 '__getattr__', '__setattr__',
1657 '__init__', '__new__', '__prepare__'
1658 '__instancecheck__', '__subclasscheck__',
1659 '__del__'
1660])
1661
1662_calculate_return_value = {
1663 '__hash__': lambda self: object.__hash__(self),
1664 '__str__': lambda self: object.__str__(self),
1665 '__sizeof__': lambda self: object.__sizeof__(self),
1666}
1667
1668_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001669 '__lt__': NotImplemented,
1670 '__gt__': NotImplemented,
1671 '__le__': NotImplemented,
1672 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001673 '__int__': 1,
1674 '__contains__': False,
1675 '__len__': 0,
1676 '__exit__': False,
1677 '__complex__': 1j,
1678 '__float__': 1.0,
1679 '__bool__': True,
1680 '__index__': 1,
1681}
1682
1683
1684def _get_eq(self):
1685 def __eq__(other):
1686 ret_val = self.__eq__._mock_return_value
1687 if ret_val is not DEFAULT:
1688 return ret_val
1689 return self is other
1690 return __eq__
1691
1692def _get_ne(self):
1693 def __ne__(other):
1694 if self.__ne__._mock_return_value is not DEFAULT:
1695 return DEFAULT
1696 return self is not other
1697 return __ne__
1698
1699def _get_iter(self):
1700 def __iter__():
1701 ret_val = self.__iter__._mock_return_value
1702 if ret_val is DEFAULT:
1703 return iter([])
1704 # if ret_val was already an iterator, then calling iter on it should
1705 # return the iterator unchanged
1706 return iter(ret_val)
1707 return __iter__
1708
1709_side_effect_methods = {
1710 '__eq__': _get_eq,
1711 '__ne__': _get_ne,
1712 '__iter__': _get_iter,
1713}
1714
1715
1716
1717def _set_return_value(mock, method, name):
1718 fixed = _return_values.get(name, DEFAULT)
1719 if fixed is not DEFAULT:
1720 method.return_value = fixed
1721 return
1722
1723 return_calulator = _calculate_return_value.get(name)
1724 if return_calulator is not None:
1725 try:
1726 return_value = return_calulator(mock)
1727 except AttributeError:
1728 # XXXX why do we return AttributeError here?
1729 # set it as a side_effect instead?
1730 return_value = AttributeError(name)
1731 method.return_value = return_value
1732 return
1733
1734 side_effector = _side_effect_methods.get(name)
1735 if side_effector is not None:
1736 method.side_effect = side_effector(mock)
1737
1738
1739
1740class MagicMixin(object):
1741 def __init__(self, *args, **kw):
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001742 _safe_super(MagicMixin, self).__init__(*args, **kw)
Michael Foord345266a2012-03-14 12:24:34 -07001743 self._mock_set_magics()
1744
1745
1746 def _mock_set_magics(self):
1747 these_magics = _magics
1748
1749 if self._mock_methods is not None:
1750 these_magics = _magics.intersection(self._mock_methods)
1751
1752 remove_magics = set()
1753 remove_magics = _magics - these_magics
1754
1755 for entry in remove_magics:
1756 if entry in type(self).__dict__:
1757 # remove unneeded magic methods
1758 delattr(self, entry)
1759
1760 # don't overwrite existing attributes if called a second time
1761 these_magics = these_magics - set(type(self).__dict__)
1762
1763 _type = type(self)
1764 for entry in these_magics:
1765 setattr(_type, entry, MagicProxy(entry, self))
1766
1767
1768
1769class NonCallableMagicMock(MagicMixin, NonCallableMock):
1770 """A version of `MagicMock` that isn't callable."""
1771 def mock_add_spec(self, spec, spec_set=False):
1772 """Add a spec to a mock. `spec` can either be an object or a
1773 list of strings. Only attributes on the `spec` can be fetched as
1774 attributes from the mock.
1775
1776 If `spec_set` is True then only attributes on the spec can be set."""
1777 self._mock_add_spec(spec, spec_set)
1778 self._mock_set_magics()
1779
1780
1781
1782class MagicMock(MagicMixin, Mock):
1783 """
1784 MagicMock is a subclass of Mock with default implementations
1785 of most of the magic methods. You can use MagicMock without having to
1786 configure the magic methods yourself.
1787
1788 If you use the `spec` or `spec_set` arguments then *only* magic
1789 methods that exist in the spec will be created.
1790
1791 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1792 """
1793 def mock_add_spec(self, spec, spec_set=False):
1794 """Add a spec to a mock. `spec` can either be an object or a
1795 list of strings. Only attributes on the `spec` can be fetched as
1796 attributes from the mock.
1797
1798 If `spec_set` is True then only attributes on the spec can be set."""
1799 self._mock_add_spec(spec, spec_set)
1800 self._mock_set_magics()
1801
1802
1803
1804class MagicProxy(object):
1805 def __init__(self, name, parent):
1806 self.name = name
1807 self.parent = parent
1808
1809 def __call__(self, *args, **kwargs):
1810 m = self.create_mock()
1811 return m(*args, **kwargs)
1812
1813 def create_mock(self):
1814 entry = self.name
1815 parent = self.parent
1816 m = parent._get_child_mock(name=entry, _new_name=entry,
1817 _new_parent=parent)
1818 setattr(parent, entry, m)
1819 _set_return_value(parent, m, entry)
1820 return m
1821
1822 def __get__(self, obj, _type=None):
1823 return self.create_mock()
1824
1825
1826
1827class _ANY(object):
1828 "A helper object that compares equal to everything."
1829
1830 def __eq__(self, other):
1831 return True
1832
1833 def __ne__(self, other):
1834 return False
1835
1836 def __repr__(self):
1837 return '<ANY>'
1838
1839ANY = _ANY()
1840
1841
1842
1843def _format_call_signature(name, args, kwargs):
1844 message = '%s(%%s)' % name
1845 formatted_args = ''
1846 args_string = ', '.join([repr(arg) for arg in args])
1847 kwargs_string = ', '.join([
1848 '%s=%r' % (key, value) for key, value in kwargs.items()
1849 ])
1850 if args_string:
1851 formatted_args = args_string
1852 if kwargs_string:
1853 if formatted_args:
1854 formatted_args += ', '
1855 formatted_args += kwargs_string
1856
1857 return message % formatted_args
1858
1859
1860
1861class _Call(tuple):
1862 """
1863 A tuple for holding the results of a call to a mock, either in the form
1864 `(args, kwargs)` or `(name, args, kwargs)`.
1865
1866 If args or kwargs are empty then a call tuple will compare equal to
1867 a tuple without those values. This makes comparisons less verbose::
1868
1869 _Call(('name', (), {})) == ('name',)
1870 _Call(('name', (1,), {})) == ('name', (1,))
1871 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1872
1873 The `_Call` object provides a useful shortcut for comparing with call::
1874
1875 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1876 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1877
1878 If the _Call has no name then it will match any name.
1879 """
1880 def __new__(cls, value=(), name=None, parent=None, two=False,
1881 from_kall=True):
1882 name = ''
1883 args = ()
1884 kwargs = {}
1885 _len = len(value)
1886 if _len == 3:
1887 name, args, kwargs = value
1888 elif _len == 2:
1889 first, second = value
1890 if isinstance(first, str):
1891 name = first
1892 if isinstance(second, tuple):
1893 args = second
1894 else:
1895 kwargs = second
1896 else:
1897 args, kwargs = first, second
1898 elif _len == 1:
1899 value, = value
1900 if isinstance(value, str):
1901 name = value
1902 elif isinstance(value, tuple):
1903 args = value
1904 else:
1905 kwargs = value
1906
1907 if two:
1908 return tuple.__new__(cls, (args, kwargs))
1909
1910 return tuple.__new__(cls, (name, args, kwargs))
1911
1912
1913 def __init__(self, value=(), name=None, parent=None, two=False,
1914 from_kall=True):
1915 self.name = name
1916 self.parent = parent
1917 self.from_kall = from_kall
1918
1919
1920 def __eq__(self, other):
1921 if other is ANY:
1922 return True
1923 try:
1924 len_other = len(other)
1925 except TypeError:
1926 return False
1927
1928 self_name = ''
1929 if len(self) == 2:
1930 self_args, self_kwargs = self
1931 else:
1932 self_name, self_args, self_kwargs = self
1933
1934 other_name = ''
1935 if len_other == 0:
1936 other_args, other_kwargs = (), {}
1937 elif len_other == 3:
1938 other_name, other_args, other_kwargs = other
1939 elif len_other == 1:
1940 value, = other
1941 if isinstance(value, tuple):
1942 other_args = value
1943 other_kwargs = {}
1944 elif isinstance(value, str):
1945 other_name = value
1946 other_args, other_kwargs = (), {}
1947 else:
1948 other_args = ()
1949 other_kwargs = value
1950 else:
1951 # len 2
1952 # could be (name, args) or (name, kwargs) or (args, kwargs)
1953 first, second = other
1954 if isinstance(first, str):
1955 other_name = first
1956 if isinstance(second, tuple):
1957 other_args, other_kwargs = second, {}
1958 else:
1959 other_args, other_kwargs = (), second
1960 else:
1961 other_args, other_kwargs = first, second
1962
1963 if self_name and other_name != self_name:
1964 return False
1965
1966 # this order is important for ANY to work!
1967 return (other_args, other_kwargs) == (self_args, self_kwargs)
1968
1969
1970 def __ne__(self, other):
1971 return not self.__eq__(other)
1972
1973
1974 def __call__(self, *args, **kwargs):
1975 if self.name is None:
1976 return _Call(('', args, kwargs), name='()')
1977
1978 name = self.name + '()'
1979 return _Call((self.name, args, kwargs), name=name, parent=self)
1980
1981
1982 def __getattr__(self, attr):
1983 if self.name is None:
1984 return _Call(name=attr, from_kall=False)
1985 name = '%s.%s' % (self.name, attr)
1986 return _Call(name=name, parent=self, from_kall=False)
1987
1988
1989 def __repr__(self):
1990 if not self.from_kall:
1991 name = self.name or 'call'
1992 if name.startswith('()'):
1993 name = 'call%s' % name
1994 return name
1995
1996 if len(self) == 2:
1997 name = 'call'
1998 args, kwargs = self
1999 else:
2000 name, args, kwargs = self
2001 if not name:
2002 name = 'call'
2003 elif not name.startswith('()'):
2004 name = 'call.%s' % name
2005 else:
2006 name = 'call%s' % name
2007 return _format_call_signature(name, args, kwargs)
2008
2009
2010 def call_list(self):
2011 """For a call object that represents multiple calls, `call_list`
2012 returns a list of all the intermediate calls as well as the
2013 final call."""
2014 vals = []
2015 thing = self
2016 while thing is not None:
2017 if thing.from_kall:
2018 vals.append(thing)
2019 thing = thing.parent
2020 return _CallList(reversed(vals))
2021
2022
2023call = _Call(from_kall=False)
2024
2025
2026
2027def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2028 _name=None, **kwargs):
2029 """Create a mock object using another object as a spec. Attributes on the
2030 mock will use the corresponding attribute on the `spec` object as their
2031 spec.
2032
2033 Functions or methods being mocked will have their arguments checked
2034 to check that they are called with the correct signature.
2035
2036 If `spec_set` is True then attempting to set attributes that don't exist
2037 on the spec object will raise an `AttributeError`.
2038
2039 If a class is used as a spec then the return value of the mock (the
2040 instance of the class) will have the same spec. You can use a class as the
2041 spec for an instance object by passing `instance=True`. The returned mock
2042 will only be callable if instances of the mock are callable.
2043
2044 `create_autospec` also takes arbitrary keyword arguments that are passed to
2045 the constructor of the created mock."""
2046 if _is_list(spec):
2047 # can't pass a list instance to the mock constructor as it will be
2048 # interpreted as a list of strings
2049 spec = type(spec)
2050
2051 is_type = isinstance(spec, type)
2052
2053 _kwargs = {'spec': spec}
2054 if spec_set:
2055 _kwargs = {'spec_set': spec}
2056 elif spec is None:
2057 # None we mock with a normal mock without a spec
2058 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002059 if _kwargs and instance:
2060 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002061
2062 _kwargs.update(kwargs)
2063
2064 Klass = MagicMock
2065 if type(spec) in DescriptorTypes:
2066 # descriptors don't have a spec
2067 # because we don't know what type they return
2068 _kwargs = {}
2069 elif not _callable(spec):
2070 Klass = NonCallableMagicMock
2071 elif is_type and instance and not _instance_callable(spec):
2072 Klass = NonCallableMagicMock
2073
2074 _new_name = _name
2075 if _parent is None:
2076 # for a top level object no _new_name should be set
2077 _new_name = ''
2078
2079 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2080 name=_name, **_kwargs)
2081
2082 if isinstance(spec, FunctionTypes):
2083 # should only happen at the top level because we don't
2084 # recurse for functions
2085 mock = _set_signature(mock, spec)
2086 else:
2087 _check_signature(spec, mock, is_type, instance)
2088
2089 if _parent is not None and not instance:
2090 _parent._mock_children[_name] = mock
2091
2092 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002093 mock.return_value = create_autospec(spec, spec_set, instance=True,
2094 _name='()', _parent=mock)
2095
2096 for entry in dir(spec):
2097 if _is_magic(entry):
2098 # MagicMock already does the useful magic methods for us
2099 continue
2100
Michael Foord345266a2012-03-14 12:24:34 -07002101 # XXXX do we need a better way of getting attributes without
2102 # triggering code execution (?) Probably not - we need the actual
2103 # object to mock it so we would rather trigger a property than mock
2104 # the property descriptor. Likewise we want to mock out dynamically
2105 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002106 # XXXX what about attributes that raise exceptions other than
2107 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002108 # we could be resilient against it, or catch and propagate the
2109 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002110 try:
2111 original = getattr(spec, entry)
2112 except AttributeError:
2113 continue
Michael Foord345266a2012-03-14 12:24:34 -07002114
2115 kwargs = {'spec': original}
2116 if spec_set:
2117 kwargs = {'spec_set': original}
2118
2119 if not isinstance(original, FunctionTypes):
2120 new = _SpecState(original, spec_set, mock, entry, instance)
2121 mock._mock_children[entry] = new
2122 else:
2123 parent = mock
2124 if isinstance(spec, FunctionTypes):
2125 parent = mock.mock
2126
Michael Foord345266a2012-03-14 12:24:34 -07002127 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002128 kwargs['_eat_self'] = skipfirst
2129 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2130 _new_parent=parent,
2131 **kwargs)
2132 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002133 _check_signature(original, new, skipfirst=skipfirst)
2134
2135 # so functions created with _set_signature become instance attributes,
2136 # *plus* their underlying mock exists in _mock_children of the parent
2137 # mock. Adding to _mock_children may be unnecessary where we are also
2138 # setting as an instance attribute?
2139 if isinstance(new, FunctionTypes):
2140 setattr(mock, entry, new)
2141
2142 return mock
2143
2144
2145def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002146 """
2147 Return whether we should skip the first argument on spec's `entry`
2148 attribute.
2149 """
Michael Foord345266a2012-03-14 12:24:34 -07002150 if not isinstance(spec, type):
2151 if entry in getattr(spec, '__dict__', {}):
2152 # instance attribute - shouldn't skip
2153 return False
Michael Foord345266a2012-03-14 12:24:34 -07002154 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002155
2156 for klass in spec.__mro__:
2157 result = klass.__dict__.get(entry, DEFAULT)
2158 if result is DEFAULT:
2159 continue
2160 if isinstance(result, (staticmethod, classmethod)):
2161 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002162 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2163 # Normal method => skip if looked up on type
2164 # (if looked up on instance, self is already skipped)
2165 return is_type
2166 else:
2167 return False
Michael Foord345266a2012-03-14 12:24:34 -07002168
2169 # shouldn't get here unless function is a dynamically provided attribute
2170 # XXXX untested behaviour
2171 return is_type
2172
2173
2174def _get_class(obj):
2175 try:
2176 return obj.__class__
2177 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002178 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002179 return type(obj)
2180
2181
2182class _SpecState(object):
2183
2184 def __init__(self, spec, spec_set=False, parent=None,
2185 name=None, ids=None, instance=False):
2186 self.spec = spec
2187 self.ids = ids
2188 self.spec_set = spec_set
2189 self.parent = parent
2190 self.instance = instance
2191 self.name = name
2192
2193
2194FunctionTypes = (
2195 # python function
2196 type(create_autospec),
2197 # instance method
2198 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002199)
2200
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002201MethodWrapperTypes = (
2202 type(ANY.__eq__.__get__),
2203)
2204
Michael Foord345266a2012-03-14 12:24:34 -07002205
Michael Foorda74561a2012-03-25 19:03:13 +01002206file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002207
Michael Foord04cbe0c2013-03-19 17:22:51 -07002208def _iterate_read_data(read_data):
2209 # Helper for mock_open:
2210 # Retrieve lines from read_data via a generator so that separate calls to
2211 # readline, read, and readlines are properly interleaved
2212 data_as_list = ['{}\n'.format(l) for l in read_data.split('\n')]
2213
2214 if data_as_list[-1] == '\n':
2215 # If the last line ended in a newline, the list comprehension will have an
2216 # extra entry that's just a newline. Remove this.
2217 data_as_list = data_as_list[:-1]
2218 else:
2219 # If there wasn't an extra newline by itself, then the file being
2220 # emulated doesn't have a newline to end the last line remove the
2221 # newline that our naive format() added
2222 data_as_list[-1] = data_as_list[-1][:-1]
2223
2224 for line in data_as_list:
2225 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002226
2227def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002228 """
2229 A helper function to create a mock to replace the use of `open`. It works
2230 for `open` called directly or used as a context manager.
2231
2232 The `mock` argument is the mock object to configure. If `None` (the
2233 default) then a `MagicMock` will be created for you, with the API limited
2234 to methods or attributes available on standard file handles.
2235
Michael Foord04cbe0c2013-03-19 17:22:51 -07002236 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2237 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002238 """
Michael Foord04cbe0c2013-03-19 17:22:51 -07002239 def _readlines_side_effect(*args, **kwargs):
2240 if handle.readlines.return_value is not None:
2241 return handle.readlines.return_value
2242 return list(_data)
2243
2244 def _read_side_effect(*args, **kwargs):
2245 if handle.read.return_value is not None:
2246 return handle.read.return_value
2247 return ''.join(_data)
2248
2249 def _readline_side_effect():
2250 if handle.readline.return_value is not None:
2251 while True:
2252 yield handle.readline.return_value
2253 for line in _data:
2254 yield line
2255
2256
Michael Foorda74561a2012-03-25 19:03:13 +01002257 global file_spec
2258 if file_spec is None:
2259 import _io
2260 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2261
Michael Foord345266a2012-03-14 12:24:34 -07002262 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002263 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002264
2265 handle = MagicMock(spec=file_spec)
Michael Foord345266a2012-03-14 12:24:34 -07002266 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002267
2268 _data = _iterate_read_data(read_data)
2269
2270 handle.write.return_value = None
2271 handle.read.return_value = None
2272 handle.readline.return_value = None
2273 handle.readlines.return_value = None
2274
2275 handle.read.side_effect = _read_side_effect
2276 handle.readline.side_effect = _readline_side_effect()
2277 handle.readlines.side_effect = _readlines_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002278
2279 mock.return_value = handle
2280 return mock
2281
2282
2283class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002284 """
2285 A mock intended to be used as a property, or other descriptor, on a class.
2286 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2287 a return value when it is fetched.
2288
2289 Fetching a `PropertyMock` instance from an object calls the mock, with
2290 no args. Setting it calls the mock with the value being set.
2291 """
Michael Foordc2870622012-04-13 16:57:22 +01002292 def _get_child_mock(self, **kwargs):
2293 return MagicMock(**kwargs)
2294
Michael Foord345266a2012-03-14 12:24:34 -07002295 def __get__(self, obj, obj_type):
2296 return self()
2297 def __set__(self, obj, val):
2298 self(val)