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