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