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