blob: 36be0fd0381e3aeb3de0a88ea6a392ef04952c33 [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():
513 child.reset_mock()
514
515 ret = self._mock_return_value
516 if _is_instance_mock(ret) and ret is not self:
517 ret.reset_mock()
518
519
520 def configure_mock(self, **kwargs):
521 """Set attributes on the mock through keyword arguments.
522
523 Attributes plus return values and side effects can be set on child
524 mocks using standard dot notation and unpacking a dictionary in the
525 method call:
526
527 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
528 >>> mock.configure_mock(**attrs)"""
529 for arg, val in sorted(kwargs.items(),
530 # we sort on the number of dots so that
531 # attributes are set before we set attributes on
532 # attributes
533 key=lambda entry: entry[0].count('.')):
534 args = arg.split('.')
535 final = args.pop()
536 obj = self
537 for entry in args:
538 obj = getattr(obj, entry)
539 setattr(obj, final, val)
540
541
542 def __getattr__(self, name):
543 if name == '_mock_methods':
544 raise AttributeError(name)
545 elif self._mock_methods is not None:
546 if name not in self._mock_methods or name in _all_magics:
547 raise AttributeError("Mock object has no attribute %r" % name)
548 elif _is_magic(name):
549 raise AttributeError(name)
550
551 result = self._mock_children.get(name)
552 if result is _deleted:
553 raise AttributeError(name)
554 elif result is None:
555 wraps = None
556 if self._mock_wraps is not None:
557 # XXXX should we get the attribute without triggering code
558 # execution?
559 wraps = getattr(self._mock_wraps, name)
560
561 result = self._get_child_mock(
562 parent=self, name=name, wraps=wraps, _new_name=name,
563 _new_parent=self
564 )
565 self._mock_children[name] = result
566
567 elif isinstance(result, _SpecState):
568 result = create_autospec(
569 result.spec, result.spec_set, result.instance,
570 result.parent, result.name
571 )
572 self._mock_children[name] = result
573
574 return result
575
576
577 def __repr__(self):
578 _name_list = [self._mock_new_name]
579 _parent = self._mock_new_parent
580 last = self
581
582 dot = '.'
583 if _name_list == ['()']:
584 dot = ''
585 seen = set()
586 while _parent is not None:
587 last = _parent
588
589 _name_list.append(_parent._mock_new_name + dot)
590 dot = '.'
591 if _parent._mock_new_name == '()':
592 dot = ''
593
594 _parent = _parent._mock_new_parent
595
596 # use ids here so as not to call __hash__ on the mocks
597 if id(_parent) in seen:
598 break
599 seen.add(id(_parent))
600
601 _name_list = list(reversed(_name_list))
602 _first = last._mock_name or 'mock'
603 if len(_name_list) > 1:
604 if _name_list[1] not in ('()', '().'):
605 _first += '.'
606 _name_list[0] = _first
607 name = ''.join(_name_list)
608
609 name_string = ''
610 if name not in ('mock', 'mock.'):
611 name_string = ' name=%r' % name
612
613 spec_string = ''
614 if self._spec_class is not None:
615 spec_string = ' spec=%r'
616 if self._spec_set:
617 spec_string = ' spec_set=%r'
618 spec_string = spec_string % self._spec_class.__name__
619 return "<%s%s%s id='%s'>" % (
620 type(self).__name__,
621 name_string,
622 spec_string,
623 id(self)
624 )
625
626
627 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700628 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100629 if not FILTER_DIR:
630 return object.__dir__(self)
631
Michael Foord345266a2012-03-14 12:24:34 -0700632 extras = self._mock_methods or []
633 from_type = dir(type(self))
634 from_dict = list(self.__dict__)
635
Michael Foord313f85f2012-03-25 18:16:07 +0100636 from_type = [e for e in from_type if not e.startswith('_')]
637 from_dict = [e for e in from_dict if not e.startswith('_') or
638 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700639 return sorted(set(extras + from_type + from_dict +
640 list(self._mock_children)))
641
642
643 def __setattr__(self, name, value):
644 if name in _allowed_names:
645 # property setters go through here
646 return object.__setattr__(self, name, value)
647 elif (self._spec_set and self._mock_methods is not None and
648 name not in self._mock_methods and
649 name not in self.__dict__):
650 raise AttributeError("Mock object has no attribute '%s'" % name)
651 elif name in _unsupported_magics:
652 msg = 'Attempting to set unsupported magic method %r.' % name
653 raise AttributeError(msg)
654 elif name in _all_magics:
655 if self._mock_methods is not None and name not in self._mock_methods:
656 raise AttributeError("Mock object has no attribute '%s'" % name)
657
658 if not _is_instance_mock(value):
659 setattr(type(self), name, _get_method(name, value))
660 original = value
661 value = lambda *args, **kw: original(self, *args, **kw)
662 else:
663 # only set _new_name and not name so that mock_calls is tracked
664 # but not method calls
665 _check_and_set_parent(self, value, None, name)
666 setattr(type(self), name, value)
667 elif name == '__class__':
668 self._spec_class = value
669 return
670 else:
671 if _check_and_set_parent(self, value, name, name):
672 self._mock_children[name] = value
673 return object.__setattr__(self, name, value)
674
675
676 def __delattr__(self, name):
677 if name in _all_magics and name in type(self).__dict__:
678 delattr(type(self), name)
679 if name not in self.__dict__:
680 # for magic methods that are still MagicProxy objects and
681 # not set on the instance itself
682 return
683
684 if name in self.__dict__:
685 object.__delattr__(self, name)
686
687 obj = self._mock_children.get(name, _missing)
688 if obj is _deleted:
689 raise AttributeError(name)
690 if obj is not _missing:
691 del self._mock_children[name]
692 self._mock_children[name] = _deleted
693
694
695
696 def _format_mock_call_signature(self, args, kwargs):
697 name = self._mock_name or 'mock'
698 return _format_call_signature(name, args, kwargs)
699
700
701 def _format_mock_failure_message(self, args, kwargs):
702 message = 'Expected call: %s\nActual call: %s'
703 expected_string = self._format_mock_call_signature(args, kwargs)
704 call_args = self.call_args
705 if len(call_args) == 3:
706 call_args = call_args[1:]
707 actual_string = self._format_mock_call_signature(*call_args)
708 return message % (expected_string, actual_string)
709
710
711 def assert_called_with(_mock_self, *args, **kwargs):
712 """assert that the mock was called with the specified arguments.
713
714 Raises an AssertionError if the args and keyword args passed in are
715 different to the last call to the mock."""
716 self = _mock_self
717 if self.call_args is None:
718 expected = self._format_mock_call_signature(args, kwargs)
719 raise AssertionError('Expected call: %s\nNot called' % (expected,))
720
721 if self.call_args != (args, kwargs):
722 msg = self._format_mock_failure_message(args, kwargs)
723 raise AssertionError(msg)
724
725
726 def assert_called_once_with(_mock_self, *args, **kwargs):
727 """assert that the mock was called exactly once and with the specified
728 arguments."""
729 self = _mock_self
730 if not self.call_count == 1:
731 msg = ("Expected to be called once. Called %s times." %
732 self.call_count)
733 raise AssertionError(msg)
734 return self.assert_called_with(*args, **kwargs)
735
736
737 def assert_has_calls(self, calls, any_order=False):
738 """assert the mock has been called with the specified calls.
739 The `mock_calls` list is checked for the calls.
740
741 If `any_order` is False (the default) then the calls must be
742 sequential. There can be extra calls before or after the
743 specified calls.
744
745 If `any_order` is True then the calls can be in any order, but
746 they must all appear in `mock_calls`."""
747 if not any_order:
748 if calls not in self.mock_calls:
749 raise AssertionError(
750 'Calls not found.\nExpected: %r\n'
751 'Actual: %r' % (calls, self.mock_calls)
752 )
753 return
754
755 all_calls = list(self.mock_calls)
756
757 not_found = []
758 for kall in calls:
759 try:
760 all_calls.remove(kall)
761 except ValueError:
762 not_found.append(kall)
763 if not_found:
764 raise AssertionError(
765 '%r not all found in call list' % (tuple(not_found),)
766 )
767
768
769 def assert_any_call(self, *args, **kwargs):
770 """assert the mock has been called with the specified arguments.
771
772 The assert passes if the mock has *ever* been called, unlike
773 `assert_called_with` and `assert_called_once_with` that only pass if
774 the call is the most recent one."""
775 kall = call(*args, **kwargs)
776 if kall not in self.call_args_list:
777 expected_string = self._format_mock_call_signature(args, kwargs)
778 raise AssertionError(
779 '%s call not found' % expected_string
780 )
781
782
783 def _get_child_mock(self, **kw):
784 """Create the child mocks for attributes and return value.
785 By default child mocks will be the same type as the parent.
786 Subclasses of Mock may want to override this to customize the way
787 child mocks are made.
788
789 For non-callable mocks the callable variant will be used (rather than
790 any custom subclass)."""
791 _type = type(self)
792 if not issubclass(_type, CallableMixin):
793 if issubclass(_type, NonCallableMagicMock):
794 klass = MagicMock
795 elif issubclass(_type, NonCallableMock) :
796 klass = Mock
797 else:
798 klass = _type.__mro__[1]
799 return klass(**kw)
800
801
802
803def _try_iter(obj):
804 if obj is None:
805 return obj
806 if _is_exception(obj):
807 return obj
808 if _callable(obj):
809 return obj
810 try:
811 return iter(obj)
812 except TypeError:
813 # XXXX backwards compatibility
814 # but this will blow up on first call - so maybe we should fail early?
815 return obj
816
817
818
819class CallableMixin(Base):
820
821 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
822 wraps=None, name=None, spec_set=None, parent=None,
823 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
824 self.__dict__['_mock_return_value'] = return_value
825
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000826 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700827 spec, wraps, name, spec_set, parent,
828 _spec_state, _new_name, _new_parent, **kwargs
829 )
830
831 self.side_effect = side_effect
832
833
834 def _mock_check_sig(self, *args, **kwargs):
835 # stub method that can be replaced with one with a specific signature
836 pass
837
838
839 def __call__(_mock_self, *args, **kwargs):
840 # can't use self in-case a function / method we are mocking uses self
841 # in the signature
842 _mock_self._mock_check_sig(*args, **kwargs)
843 return _mock_self._mock_call(*args, **kwargs)
844
845
846 def _mock_call(_mock_self, *args, **kwargs):
847 self = _mock_self
848 self.called = True
849 self.call_count += 1
850 self.call_args = _Call((args, kwargs), two=True)
851 self.call_args_list.append(_Call((args, kwargs), two=True))
852
853 _new_name = self._mock_new_name
854 _new_parent = self._mock_new_parent
855 self.mock_calls.append(_Call(('', args, kwargs)))
856
857 seen = set()
858 skip_next_dot = _new_name == '()'
859 do_method_calls = self._mock_parent is not None
860 name = self._mock_name
861 while _new_parent is not None:
862 this_mock_call = _Call((_new_name, args, kwargs))
863 if _new_parent._mock_new_name:
864 dot = '.'
865 if skip_next_dot:
866 dot = ''
867
868 skip_next_dot = False
869 if _new_parent._mock_new_name == '()':
870 skip_next_dot = True
871
872 _new_name = _new_parent._mock_new_name + dot + _new_name
873
874 if do_method_calls:
875 if _new_name == name:
876 this_method_call = this_mock_call
877 else:
878 this_method_call = _Call((name, args, kwargs))
879 _new_parent.method_calls.append(this_method_call)
880
881 do_method_calls = _new_parent._mock_parent is not None
882 if do_method_calls:
883 name = _new_parent._mock_name + '.' + name
884
885 _new_parent.mock_calls.append(this_mock_call)
886 _new_parent = _new_parent._mock_new_parent
887
888 # use ids here so as not to call __hash__ on the mocks
889 _new_parent_id = id(_new_parent)
890 if _new_parent_id in seen:
891 break
892 seen.add(_new_parent_id)
893
894 ret_val = DEFAULT
895 effect = self.side_effect
896 if effect is not None:
897 if _is_exception(effect):
898 raise effect
899
900 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +0100901 result = next(effect)
902 if _is_exception(result):
903 raise result
904 return result
Michael Foord345266a2012-03-14 12:24:34 -0700905
906 ret_val = effect(*args, **kwargs)
907 if ret_val is DEFAULT:
908 ret_val = self.return_value
909
910 if (self._mock_wraps is not None and
911 self._mock_return_value is DEFAULT):
912 return self._mock_wraps(*args, **kwargs)
913 if ret_val is DEFAULT:
914 ret_val = self.return_value
915 return ret_val
916
917
918
919class Mock(CallableMixin, NonCallableMock):
920 """
921 Create a new `Mock` object. `Mock` takes several optional arguments
922 that specify the behaviour of the Mock object:
923
924 * `spec`: This can be either a list of strings or an existing object (a
925 class or instance) that acts as the specification for the mock object. If
926 you pass in an object then a list of strings is formed by calling dir on
927 the object (excluding unsupported magic attributes and methods). Accessing
928 any attribute not in this list will raise an `AttributeError`.
929
930 If `spec` is an object (rather than a list of strings) then
931 `mock.__class__` returns the class of the spec object. This allows mocks
932 to pass `isinstance` tests.
933
934 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
935 or get an attribute on the mock that isn't on the object passed as
936 `spec_set` will raise an `AttributeError`.
937
938 * `side_effect`: A function to be called whenever the Mock is called. See
939 the `side_effect` attribute. Useful for raising exceptions or
940 dynamically changing return values. The function is called with the same
941 arguments as the mock, and unless it returns `DEFAULT`, the return
942 value of this function is used as the return value.
943
Michael Foord2cd48732012-04-21 15:52:11 +0100944 If `side_effect` is an iterable then each call to the mock will return
945 the next value from the iterable. If any of the members of the iterable
946 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -0700947
948 If `side_effect` is an iterable then each call to the mock will return
949 the next value from the iterable.
950
951 * `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
1002
1003 def __init__(
1004 self, getter, attribute, new, spec, create,
1005 spec_set, autospec, new_callable, kwargs
1006 ):
1007 if new_callable is not None:
1008 if new is not DEFAULT:
1009 raise ValueError(
1010 "Cannot use 'new' and 'new_callable' together"
1011 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001012 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001013 raise ValueError(
1014 "Cannot use 'autospec' and 'new_callable' together"
1015 )
1016
1017 self.getter = getter
1018 self.attribute = attribute
1019 self.new = new
1020 self.new_callable = new_callable
1021 self.spec = spec
1022 self.create = create
1023 self.has_local = False
1024 self.spec_set = spec_set
1025 self.autospec = autospec
1026 self.kwargs = kwargs
1027 self.additional_patchers = []
1028
1029
1030 def copy(self):
1031 patcher = _patch(
1032 self.getter, self.attribute, self.new, self.spec,
1033 self.create, self.spec_set,
1034 self.autospec, self.new_callable, self.kwargs
1035 )
1036 patcher.attribute_name = self.attribute_name
1037 patcher.additional_patchers = [
1038 p.copy() for p in self.additional_patchers
1039 ]
1040 return patcher
1041
1042
1043 def __call__(self, func):
1044 if isinstance(func, type):
1045 return self.decorate_class(func)
1046 return self.decorate_callable(func)
1047
1048
1049 def decorate_class(self, klass):
1050 for attr in dir(klass):
1051 if not attr.startswith(patch.TEST_PREFIX):
1052 continue
1053
1054 attr_value = getattr(klass, attr)
1055 if not hasattr(attr_value, "__call__"):
1056 continue
1057
1058 patcher = self.copy()
1059 setattr(klass, attr, patcher(attr_value))
1060 return klass
1061
1062
1063 def decorate_callable(self, func):
1064 if hasattr(func, 'patchings'):
1065 func.patchings.append(self)
1066 return func
1067
1068 @wraps(func)
1069 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001070 extra_args = []
1071 entered_patchers = []
1072
Michael Foord50a8c0e2012-03-25 18:57:58 +01001073 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001074 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001075 for patching in patched.patchings:
1076 arg = patching.__enter__()
1077 entered_patchers.append(patching)
1078 if patching.attribute_name is not None:
1079 keywargs.update(arg)
1080 elif patching.new is DEFAULT:
1081 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001082
Michael Foordd7c65e22012-03-14 14:56:54 -07001083 args += tuple(extra_args)
1084 return func(*args, **keywargs)
1085 except:
1086 if (patching not in entered_patchers and
1087 _is_started(patching)):
1088 # the patcher may have been started, but an exception
1089 # raised whilst entering one of its additional_patchers
1090 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001091 # Pass the exception to __exit__
1092 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001093 # re-raise the exception
1094 raise
Michael Foord345266a2012-03-14 12:24:34 -07001095 finally:
1096 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001097 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001098
1099 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001100 return patched
1101
1102
1103 def get_original(self):
1104 target = self.getter()
1105 name = self.attribute
1106
1107 original = DEFAULT
1108 local = False
1109
1110 try:
1111 original = target.__dict__[name]
1112 except (AttributeError, KeyError):
1113 original = getattr(target, name, DEFAULT)
1114 else:
1115 local = True
1116
1117 if not self.create and original is DEFAULT:
1118 raise AttributeError(
1119 "%s does not have the attribute %r" % (target, name)
1120 )
1121 return original, local
1122
1123
1124 def __enter__(self):
1125 """Perform the patch."""
1126 new, spec, spec_set = self.new, self.spec, self.spec_set
1127 autospec, kwargs = self.autospec, self.kwargs
1128 new_callable = self.new_callable
1129 self.target = self.getter()
1130
Michael Foord50a8c0e2012-03-25 18:57:58 +01001131 # normalise False to None
1132 if spec is False:
1133 spec = None
1134 if spec_set is False:
1135 spec_set = None
1136 if autospec is False:
1137 autospec = None
1138
1139 if spec is not None and autospec is not None:
1140 raise TypeError("Can't specify spec and autospec")
1141 if ((spec is not None or autospec is not None) and
1142 spec_set not in (True, None)):
1143 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1144
Michael Foord345266a2012-03-14 12:24:34 -07001145 original, local = self.get_original()
1146
Michael Foord50a8c0e2012-03-25 18:57:58 +01001147 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001148 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001149 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001150 # set spec to the object we are replacing
1151 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001152 if spec_set is True:
1153 spec_set = original
1154 spec = None
1155 elif spec is not None:
1156 if spec_set is True:
1157 spec_set = spec
1158 spec = None
1159 elif spec_set is True:
1160 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001161
Michael Foord50a8c0e2012-03-25 18:57:58 +01001162 if spec is not None or spec_set is not None:
1163 if original is DEFAULT:
1164 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001165 if isinstance(original, type):
1166 # If we're patching out a class and there is a spec
1167 inherit = True
1168
1169 Klass = MagicMock
1170 _kwargs = {}
1171 if new_callable is not None:
1172 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001173 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001174 this_spec = spec
1175 if spec_set is not None:
1176 this_spec = spec_set
1177 if _is_list(this_spec):
1178 not_callable = '__call__' not in this_spec
1179 else:
1180 not_callable = not callable(this_spec)
1181 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001182 Klass = NonCallableMagicMock
1183
1184 if spec is not None:
1185 _kwargs['spec'] = spec
1186 if spec_set is not None:
1187 _kwargs['spec_set'] = spec_set
1188
1189 # add a name to mocks
1190 if (isinstance(Klass, type) and
1191 issubclass(Klass, NonCallableMock) and self.attribute):
1192 _kwargs['name'] = self.attribute
1193
1194 _kwargs.update(kwargs)
1195 new = Klass(**_kwargs)
1196
1197 if inherit and _is_instance_mock(new):
1198 # we can only tell if the instance should be callable if the
1199 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001200 this_spec = spec
1201 if spec_set is not None:
1202 this_spec = spec_set
1203 if (not _is_list(this_spec) and not
1204 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001205 Klass = NonCallableMagicMock
1206
1207 _kwargs.pop('name')
1208 new.return_value = Klass(_new_parent=new, _new_name='()',
1209 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001210 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001211 # spec is ignored, new *must* be default, spec_set is treated
1212 # as a boolean. Should we check spec is not None and that spec_set
1213 # is a bool?
1214 if new is not DEFAULT:
1215 raise TypeError(
1216 "autospec creates the mock for you. Can't specify "
1217 "autospec and new."
1218 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001219 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001220 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001221 spec_set = bool(spec_set)
1222 if autospec is True:
1223 autospec = original
1224
1225 new = create_autospec(autospec, spec_set=spec_set,
1226 _name=self.attribute, **kwargs)
1227 elif kwargs:
1228 # can't set keyword args when we aren't creating the mock
1229 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1230 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1231
1232 new_attr = new
1233
1234 self.temp_original = original
1235 self.is_local = local
1236 setattr(self.target, self.attribute, new_attr)
1237 if self.attribute_name is not None:
1238 extra_args = {}
1239 if self.new is DEFAULT:
1240 extra_args[self.attribute_name] = new
1241 for patching in self.additional_patchers:
1242 arg = patching.__enter__()
1243 if patching.new is DEFAULT:
1244 extra_args.update(arg)
1245 return extra_args
1246
1247 return new
1248
1249
Michael Foord50a8c0e2012-03-25 18:57:58 +01001250 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001251 """Undo the patch."""
1252 if not _is_started(self):
1253 raise RuntimeError('stop called on unstarted patcher')
1254
1255 if self.is_local and self.temp_original is not DEFAULT:
1256 setattr(self.target, self.attribute, self.temp_original)
1257 else:
1258 delattr(self.target, self.attribute)
1259 if not self.create and not hasattr(self.target, self.attribute):
1260 # needed for proxy objects like django settings
1261 setattr(self.target, self.attribute, self.temp_original)
1262
1263 del self.temp_original
1264 del self.is_local
1265 del self.target
1266 for patcher in reversed(self.additional_patchers):
1267 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001268 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001269
1270 start = __enter__
1271 stop = __exit__
1272
1273
1274
1275def _get_target(target):
1276 try:
1277 target, attribute = target.rsplit('.', 1)
1278 except (TypeError, ValueError):
1279 raise TypeError("Need a valid target to patch. You supplied: %r" %
1280 (target,))
1281 getter = lambda: _importer(target)
1282 return getter, attribute
1283
1284
1285def _patch_object(
1286 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001287 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001288 new_callable=None, **kwargs
1289 ):
1290 """
Michael Foord345266a2012-03-14 12:24:34 -07001291 patch the named member (`attribute`) on an object (`target`) with a mock
1292 object.
1293
1294 `patch.object` can be used as a decorator, class decorator or a context
1295 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1296 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1297 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1298 the mock object it creates.
1299
1300 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1301 for choosing which methods to wrap.
1302 """
1303 getter = lambda: target
1304 return _patch(
1305 getter, attribute, new, spec, create,
1306 spec_set, autospec, new_callable, kwargs
1307 )
1308
1309
Michael Foord50a8c0e2012-03-25 18:57:58 +01001310def _patch_multiple(target, spec=None, create=False, spec_set=None,
1311 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001312 """Perform multiple patches in a single call. It takes the object to be
1313 patched (either as an object or a string to fetch the object by importing)
1314 and keyword arguments for the patches::
1315
1316 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1317 ...
1318
1319 Use `DEFAULT` as the value if you want `patch.multiple` to create
1320 mocks for you. In this case the created mocks are passed into a decorated
1321 function by keyword, and a dictionary is returned when `patch.multiple` is
1322 used as a context manager.
1323
1324 `patch.multiple` can be used as a decorator, class decorator or a context
1325 manager. The arguments `spec`, `spec_set`, `create`,
1326 `autospec` and `new_callable` have the same meaning as for `patch`. These
1327 arguments will be applied to *all* patches done by `patch.multiple`.
1328
1329 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1330 for choosing which methods to wrap.
1331 """
1332 if type(target) is str:
1333 getter = lambda: _importer(target)
1334 else:
1335 getter = lambda: target
1336
1337 if not kwargs:
1338 raise ValueError(
1339 'Must supply at least one keyword argument with patch.multiple'
1340 )
1341 # need to wrap in a list for python 3, where items is a view
1342 items = list(kwargs.items())
1343 attribute, new = items[0]
1344 patcher = _patch(
1345 getter, attribute, new, spec, create, spec_set,
1346 autospec, new_callable, {}
1347 )
1348 patcher.attribute_name = attribute
1349 for attribute, new in items[1:]:
1350 this_patcher = _patch(
1351 getter, attribute, new, spec, create, spec_set,
1352 autospec, new_callable, {}
1353 )
1354 this_patcher.attribute_name = attribute
1355 patcher.additional_patchers.append(this_patcher)
1356 return patcher
1357
1358
1359def patch(
1360 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001361 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001362 ):
1363 """
1364 `patch` acts as a function decorator, class decorator or a context
1365 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001366 is patched with a `new` object. When the function/with statement exits
1367 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001368
Michael Foord54b3db82012-03-28 15:08:08 +01001369 If `new` is omitted, then the target is replaced with a
1370 `MagicMock`. If `patch` is used as a decorator and `new` is
1371 omitted, the created mock is passed in as an extra argument to the
1372 decorated function. If `patch` is used as a context manager the created
1373 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001374
Michael Foord54b3db82012-03-28 15:08:08 +01001375 `target` should be a string in the form `'package.module.ClassName'`. The
1376 `target` is imported and the specified object replaced with the `new`
1377 object, so the `target` must be importable from the environment you are
1378 calling `patch` from. The target is imported when the decorated function
1379 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001380
1381 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1382 if patch is creating one for you.
1383
1384 In addition you can pass `spec=True` or `spec_set=True`, which causes
1385 patch to pass in the object being mocked as the spec/spec_set object.
1386
1387 `new_callable` allows you to specify a different class, or callable object,
1388 that will be called to create the `new` object. By default `MagicMock` is
1389 used.
1390
1391 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1392 then the mock with be created with a spec from the object being replaced.
1393 All attributes of the mock will also have the spec of the corresponding
1394 attribute of the object being replaced. Methods and functions being
1395 mocked will have their arguments checked and will raise a `TypeError` if
1396 they are called with the wrong signature. For mocks replacing a class,
1397 their return value (the 'instance') will have the same spec as the class.
1398
1399 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1400 arbitrary object as the spec instead of the one being replaced.
1401
1402 By default `patch` will fail to replace attributes that don't exist. If
1403 you pass in `create=True`, and the attribute doesn't exist, patch will
1404 create the attribute for you when the patched function is called, and
1405 delete it again afterwards. This is useful for writing tests against
1406 attributes that your production code creates at runtime. It is off by by
1407 default because it can be dangerous. With it switched on you can write
1408 passing tests against APIs that don't actually exist!
1409
1410 Patch can be used as a `TestCase` class decorator. It works by
1411 decorating each test method in the class. This reduces the boilerplate
1412 code when your test methods share a common patchings set. `patch` finds
1413 tests by looking for method names that start with `patch.TEST_PREFIX`.
1414 By default this is `test`, which matches the way `unittest` finds tests.
1415 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1416
1417 Patch can be used as a context manager, with the with statement. Here the
1418 patching applies to the indented block after the with statement. If you
1419 use "as" then the patched object will be bound to the name after the
1420 "as"; very useful if `patch` is creating a mock object for you.
1421
1422 `patch` takes arbitrary keyword arguments. These will be passed to
1423 the `Mock` (or `new_callable`) on construction.
1424
1425 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1426 available for alternate use-cases.
1427 """
1428 getter, attribute = _get_target(target)
1429 return _patch(
1430 getter, attribute, new, spec, create,
1431 spec_set, autospec, new_callable, kwargs
1432 )
1433
1434
1435class _patch_dict(object):
1436 """
1437 Patch a dictionary, or dictionary like object, and restore the dictionary
1438 to its original state after the test.
1439
1440 `in_dict` can be a dictionary or a mapping like container. If it is a
1441 mapping then it must at least support getting, setting and deleting items
1442 plus iterating over keys.
1443
1444 `in_dict` can also be a string specifying the name of the dictionary, which
1445 will then be fetched by importing it.
1446
1447 `values` can be a dictionary of values to set in the dictionary. `values`
1448 can also be an iterable of `(key, value)` pairs.
1449
1450 If `clear` is True then the dictionary will be cleared before the new
1451 values are set.
1452
1453 `patch.dict` can also be called with arbitrary keyword arguments to set
1454 values in the dictionary::
1455
1456 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1457 ...
1458
1459 `patch.dict` can be used as a context manager, decorator or class
1460 decorator. When used as a class decorator `patch.dict` honours
1461 `patch.TEST_PREFIX` for choosing which methods to wrap.
1462 """
1463
1464 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1465 if isinstance(in_dict, str):
1466 in_dict = _importer(in_dict)
1467 self.in_dict = in_dict
1468 # support any argument supported by dict(...) constructor
1469 self.values = dict(values)
1470 self.values.update(kwargs)
1471 self.clear = clear
1472 self._original = None
1473
1474
1475 def __call__(self, f):
1476 if isinstance(f, type):
1477 return self.decorate_class(f)
1478 @wraps(f)
1479 def _inner(*args, **kw):
1480 self._patch_dict()
1481 try:
1482 return f(*args, **kw)
1483 finally:
1484 self._unpatch_dict()
1485
1486 return _inner
1487
1488
1489 def decorate_class(self, klass):
1490 for attr in dir(klass):
1491 attr_value = getattr(klass, attr)
1492 if (attr.startswith(patch.TEST_PREFIX) and
1493 hasattr(attr_value, "__call__")):
1494 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1495 decorated = decorator(attr_value)
1496 setattr(klass, attr, decorated)
1497 return klass
1498
1499
1500 def __enter__(self):
1501 """Patch the dict."""
1502 self._patch_dict()
1503
1504
1505 def _patch_dict(self):
1506 values = self.values
1507 in_dict = self.in_dict
1508 clear = self.clear
1509
1510 try:
1511 original = in_dict.copy()
1512 except AttributeError:
1513 # dict like object with no copy method
1514 # must support iteration over keys
1515 original = {}
1516 for key in in_dict:
1517 original[key] = in_dict[key]
1518 self._original = original
1519
1520 if clear:
1521 _clear_dict(in_dict)
1522
1523 try:
1524 in_dict.update(values)
1525 except AttributeError:
1526 # dict like object with no update method
1527 for key in values:
1528 in_dict[key] = values[key]
1529
1530
1531 def _unpatch_dict(self):
1532 in_dict = self.in_dict
1533 original = self._original
1534
1535 _clear_dict(in_dict)
1536
1537 try:
1538 in_dict.update(original)
1539 except AttributeError:
1540 for key in original:
1541 in_dict[key] = original[key]
1542
1543
1544 def __exit__(self, *args):
1545 """Unpatch the dict."""
1546 self._unpatch_dict()
1547 return False
1548
1549 start = __enter__
1550 stop = __exit__
1551
1552
1553def _clear_dict(in_dict):
1554 try:
1555 in_dict.clear()
1556 except AttributeError:
1557 keys = list(in_dict)
1558 for key in keys:
1559 del in_dict[key]
1560
1561
1562patch.object = _patch_object
1563patch.dict = _patch_dict
1564patch.multiple = _patch_multiple
1565patch.TEST_PREFIX = 'test'
1566
1567magic_methods = (
1568 "lt le gt ge eq ne "
1569 "getitem setitem delitem "
1570 "len contains iter "
1571 "hash str sizeof "
1572 "enter exit "
1573 "divmod neg pos abs invert "
1574 "complex int float index "
1575 "trunc floor ceil "
1576 "bool next "
1577)
1578
1579numerics = "add sub mul div floordiv mod lshift rshift and xor or pow "
1580inplace = ' '.join('i%s' % n for n in numerics.split())
1581right = ' '.join('r%s' % n for n in numerics.split())
1582
1583# not including __prepare__, __instancecheck__, __subclasscheck__
1584# (as they are metaclass methods)
1585# __del__ is not supported at all as it causes problems if it exists
1586
1587_non_defaults = set('__%s__' % method for method in [
Michael Foord944e02d2012-03-25 23:12:55 +01001588 'get', 'set', 'delete', 'reversed', 'missing', 'reduce', 'reduce_ex',
1589 'getinitargs', 'getnewargs', 'getstate', 'setstate', 'getformat',
1590 'setformat', 'repr', 'dir', 'subclasses', 'format',
Michael Foord345266a2012-03-14 12:24:34 -07001591])
1592
1593
1594def _get_method(name, func):
1595 "Turns a callable object (like a mock) into a real function"
1596 def method(self, *args, **kw):
1597 return func(self, *args, **kw)
1598 method.__name__ = name
1599 return method
1600
1601
1602_magics = set(
1603 '__%s__' % method for method in
1604 ' '.join([magic_methods, numerics, inplace, right]).split()
1605)
1606
1607_all_magics = _magics | _non_defaults
1608
1609_unsupported_magics = set([
1610 '__getattr__', '__setattr__',
1611 '__init__', '__new__', '__prepare__'
1612 '__instancecheck__', '__subclasscheck__',
1613 '__del__'
1614])
1615
1616_calculate_return_value = {
1617 '__hash__': lambda self: object.__hash__(self),
1618 '__str__': lambda self: object.__str__(self),
1619 '__sizeof__': lambda self: object.__sizeof__(self),
1620}
1621
1622_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001623 '__lt__': NotImplemented,
1624 '__gt__': NotImplemented,
1625 '__le__': NotImplemented,
1626 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001627 '__int__': 1,
1628 '__contains__': False,
1629 '__len__': 0,
1630 '__exit__': False,
1631 '__complex__': 1j,
1632 '__float__': 1.0,
1633 '__bool__': True,
1634 '__index__': 1,
1635}
1636
1637
1638def _get_eq(self):
1639 def __eq__(other):
1640 ret_val = self.__eq__._mock_return_value
1641 if ret_val is not DEFAULT:
1642 return ret_val
1643 return self is other
1644 return __eq__
1645
1646def _get_ne(self):
1647 def __ne__(other):
1648 if self.__ne__._mock_return_value is not DEFAULT:
1649 return DEFAULT
1650 return self is not other
1651 return __ne__
1652
1653def _get_iter(self):
1654 def __iter__():
1655 ret_val = self.__iter__._mock_return_value
1656 if ret_val is DEFAULT:
1657 return iter([])
1658 # if ret_val was already an iterator, then calling iter on it should
1659 # return the iterator unchanged
1660 return iter(ret_val)
1661 return __iter__
1662
1663_side_effect_methods = {
1664 '__eq__': _get_eq,
1665 '__ne__': _get_ne,
1666 '__iter__': _get_iter,
1667}
1668
1669
1670
1671def _set_return_value(mock, method, name):
1672 fixed = _return_values.get(name, DEFAULT)
1673 if fixed is not DEFAULT:
1674 method.return_value = fixed
1675 return
1676
1677 return_calulator = _calculate_return_value.get(name)
1678 if return_calulator is not None:
1679 try:
1680 return_value = return_calulator(mock)
1681 except AttributeError:
1682 # XXXX why do we return AttributeError here?
1683 # set it as a side_effect instead?
1684 return_value = AttributeError(name)
1685 method.return_value = return_value
1686 return
1687
1688 side_effector = _side_effect_methods.get(name)
1689 if side_effector is not None:
1690 method.side_effect = side_effector(mock)
1691
1692
1693
1694class MagicMixin(object):
1695 def __init__(self, *args, **kw):
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001696 _safe_super(MagicMixin, self).__init__(*args, **kw)
Michael Foord345266a2012-03-14 12:24:34 -07001697 self._mock_set_magics()
1698
1699
1700 def _mock_set_magics(self):
1701 these_magics = _magics
1702
1703 if self._mock_methods is not None:
1704 these_magics = _magics.intersection(self._mock_methods)
1705
1706 remove_magics = set()
1707 remove_magics = _magics - these_magics
1708
1709 for entry in remove_magics:
1710 if entry in type(self).__dict__:
1711 # remove unneeded magic methods
1712 delattr(self, entry)
1713
1714 # don't overwrite existing attributes if called a second time
1715 these_magics = these_magics - set(type(self).__dict__)
1716
1717 _type = type(self)
1718 for entry in these_magics:
1719 setattr(_type, entry, MagicProxy(entry, self))
1720
1721
1722
1723class NonCallableMagicMock(MagicMixin, NonCallableMock):
1724 """A version of `MagicMock` that isn't callable."""
1725 def mock_add_spec(self, spec, spec_set=False):
1726 """Add a spec to a mock. `spec` can either be an object or a
1727 list of strings. Only attributes on the `spec` can be fetched as
1728 attributes from the mock.
1729
1730 If `spec_set` is True then only attributes on the spec can be set."""
1731 self._mock_add_spec(spec, spec_set)
1732 self._mock_set_magics()
1733
1734
1735
1736class MagicMock(MagicMixin, Mock):
1737 """
1738 MagicMock is a subclass of Mock with default implementations
1739 of most of the magic methods. You can use MagicMock without having to
1740 configure the magic methods yourself.
1741
1742 If you use the `spec` or `spec_set` arguments then *only* magic
1743 methods that exist in the spec will be created.
1744
1745 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1746 """
1747 def mock_add_spec(self, spec, spec_set=False):
1748 """Add a spec to a mock. `spec` can either be an object or a
1749 list of strings. Only attributes on the `spec` can be fetched as
1750 attributes from the mock.
1751
1752 If `spec_set` is True then only attributes on the spec can be set."""
1753 self._mock_add_spec(spec, spec_set)
1754 self._mock_set_magics()
1755
1756
1757
1758class MagicProxy(object):
1759 def __init__(self, name, parent):
1760 self.name = name
1761 self.parent = parent
1762
1763 def __call__(self, *args, **kwargs):
1764 m = self.create_mock()
1765 return m(*args, **kwargs)
1766
1767 def create_mock(self):
1768 entry = self.name
1769 parent = self.parent
1770 m = parent._get_child_mock(name=entry, _new_name=entry,
1771 _new_parent=parent)
1772 setattr(parent, entry, m)
1773 _set_return_value(parent, m, entry)
1774 return m
1775
1776 def __get__(self, obj, _type=None):
1777 return self.create_mock()
1778
1779
1780
1781class _ANY(object):
1782 "A helper object that compares equal to everything."
1783
1784 def __eq__(self, other):
1785 return True
1786
1787 def __ne__(self, other):
1788 return False
1789
1790 def __repr__(self):
1791 return '<ANY>'
1792
1793ANY = _ANY()
1794
1795
1796
1797def _format_call_signature(name, args, kwargs):
1798 message = '%s(%%s)' % name
1799 formatted_args = ''
1800 args_string = ', '.join([repr(arg) for arg in args])
1801 kwargs_string = ', '.join([
1802 '%s=%r' % (key, value) for key, value in kwargs.items()
1803 ])
1804 if args_string:
1805 formatted_args = args_string
1806 if kwargs_string:
1807 if formatted_args:
1808 formatted_args += ', '
1809 formatted_args += kwargs_string
1810
1811 return message % formatted_args
1812
1813
1814
1815class _Call(tuple):
1816 """
1817 A tuple for holding the results of a call to a mock, either in the form
1818 `(args, kwargs)` or `(name, args, kwargs)`.
1819
1820 If args or kwargs are empty then a call tuple will compare equal to
1821 a tuple without those values. This makes comparisons less verbose::
1822
1823 _Call(('name', (), {})) == ('name',)
1824 _Call(('name', (1,), {})) == ('name', (1,))
1825 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1826
1827 The `_Call` object provides a useful shortcut for comparing with call::
1828
1829 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1830 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1831
1832 If the _Call has no name then it will match any name.
1833 """
1834 def __new__(cls, value=(), name=None, parent=None, two=False,
1835 from_kall=True):
1836 name = ''
1837 args = ()
1838 kwargs = {}
1839 _len = len(value)
1840 if _len == 3:
1841 name, args, kwargs = value
1842 elif _len == 2:
1843 first, second = value
1844 if isinstance(first, str):
1845 name = first
1846 if isinstance(second, tuple):
1847 args = second
1848 else:
1849 kwargs = second
1850 else:
1851 args, kwargs = first, second
1852 elif _len == 1:
1853 value, = value
1854 if isinstance(value, str):
1855 name = value
1856 elif isinstance(value, tuple):
1857 args = value
1858 else:
1859 kwargs = value
1860
1861 if two:
1862 return tuple.__new__(cls, (args, kwargs))
1863
1864 return tuple.__new__(cls, (name, args, kwargs))
1865
1866
1867 def __init__(self, value=(), name=None, parent=None, two=False,
1868 from_kall=True):
1869 self.name = name
1870 self.parent = parent
1871 self.from_kall = from_kall
1872
1873
1874 def __eq__(self, other):
1875 if other is ANY:
1876 return True
1877 try:
1878 len_other = len(other)
1879 except TypeError:
1880 return False
1881
1882 self_name = ''
1883 if len(self) == 2:
1884 self_args, self_kwargs = self
1885 else:
1886 self_name, self_args, self_kwargs = self
1887
1888 other_name = ''
1889 if len_other == 0:
1890 other_args, other_kwargs = (), {}
1891 elif len_other == 3:
1892 other_name, other_args, other_kwargs = other
1893 elif len_other == 1:
1894 value, = other
1895 if isinstance(value, tuple):
1896 other_args = value
1897 other_kwargs = {}
1898 elif isinstance(value, str):
1899 other_name = value
1900 other_args, other_kwargs = (), {}
1901 else:
1902 other_args = ()
1903 other_kwargs = value
1904 else:
1905 # len 2
1906 # could be (name, args) or (name, kwargs) or (args, kwargs)
1907 first, second = other
1908 if isinstance(first, str):
1909 other_name = first
1910 if isinstance(second, tuple):
1911 other_args, other_kwargs = second, {}
1912 else:
1913 other_args, other_kwargs = (), second
1914 else:
1915 other_args, other_kwargs = first, second
1916
1917 if self_name and other_name != self_name:
1918 return False
1919
1920 # this order is important for ANY to work!
1921 return (other_args, other_kwargs) == (self_args, self_kwargs)
1922
1923
1924 def __ne__(self, other):
1925 return not self.__eq__(other)
1926
1927
1928 def __call__(self, *args, **kwargs):
1929 if self.name is None:
1930 return _Call(('', args, kwargs), name='()')
1931
1932 name = self.name + '()'
1933 return _Call((self.name, args, kwargs), name=name, parent=self)
1934
1935
1936 def __getattr__(self, attr):
1937 if self.name is None:
1938 return _Call(name=attr, from_kall=False)
1939 name = '%s.%s' % (self.name, attr)
1940 return _Call(name=name, parent=self, from_kall=False)
1941
1942
1943 def __repr__(self):
1944 if not self.from_kall:
1945 name = self.name or 'call'
1946 if name.startswith('()'):
1947 name = 'call%s' % name
1948 return name
1949
1950 if len(self) == 2:
1951 name = 'call'
1952 args, kwargs = self
1953 else:
1954 name, args, kwargs = self
1955 if not name:
1956 name = 'call'
1957 elif not name.startswith('()'):
1958 name = 'call.%s' % name
1959 else:
1960 name = 'call%s' % name
1961 return _format_call_signature(name, args, kwargs)
1962
1963
1964 def call_list(self):
1965 """For a call object that represents multiple calls, `call_list`
1966 returns a list of all the intermediate calls as well as the
1967 final call."""
1968 vals = []
1969 thing = self
1970 while thing is not None:
1971 if thing.from_kall:
1972 vals.append(thing)
1973 thing = thing.parent
1974 return _CallList(reversed(vals))
1975
1976
1977call = _Call(from_kall=False)
1978
1979
1980
1981def create_autospec(spec, spec_set=False, instance=False, _parent=None,
1982 _name=None, **kwargs):
1983 """Create a mock object using another object as a spec. Attributes on the
1984 mock will use the corresponding attribute on the `spec` object as their
1985 spec.
1986
1987 Functions or methods being mocked will have their arguments checked
1988 to check that they are called with the correct signature.
1989
1990 If `spec_set` is True then attempting to set attributes that don't exist
1991 on the spec object will raise an `AttributeError`.
1992
1993 If a class is used as a spec then the return value of the mock (the
1994 instance of the class) will have the same spec. You can use a class as the
1995 spec for an instance object by passing `instance=True`. The returned mock
1996 will only be callable if instances of the mock are callable.
1997
1998 `create_autospec` also takes arbitrary keyword arguments that are passed to
1999 the constructor of the created mock."""
2000 if _is_list(spec):
2001 # can't pass a list instance to the mock constructor as it will be
2002 # interpreted as a list of strings
2003 spec = type(spec)
2004
2005 is_type = isinstance(spec, type)
2006
2007 _kwargs = {'spec': spec}
2008 if spec_set:
2009 _kwargs = {'spec_set': spec}
2010 elif spec is None:
2011 # None we mock with a normal mock without a spec
2012 _kwargs = {}
2013
2014 _kwargs.update(kwargs)
2015
2016 Klass = MagicMock
2017 if type(spec) in DescriptorTypes:
2018 # descriptors don't have a spec
2019 # because we don't know what type they return
2020 _kwargs = {}
2021 elif not _callable(spec):
2022 Klass = NonCallableMagicMock
2023 elif is_type and instance and not _instance_callable(spec):
2024 Klass = NonCallableMagicMock
2025
2026 _new_name = _name
2027 if _parent is None:
2028 # for a top level object no _new_name should be set
2029 _new_name = ''
2030
2031 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2032 name=_name, **_kwargs)
2033
2034 if isinstance(spec, FunctionTypes):
2035 # should only happen at the top level because we don't
2036 # recurse for functions
2037 mock = _set_signature(mock, spec)
2038 else:
2039 _check_signature(spec, mock, is_type, instance)
2040
2041 if _parent is not None and not instance:
2042 _parent._mock_children[_name] = mock
2043
2044 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002045 mock.return_value = create_autospec(spec, spec_set, instance=True,
2046 _name='()', _parent=mock)
2047
2048 for entry in dir(spec):
2049 if _is_magic(entry):
2050 # MagicMock already does the useful magic methods for us
2051 continue
2052
Michael Foord345266a2012-03-14 12:24:34 -07002053 # XXXX do we need a better way of getting attributes without
2054 # triggering code execution (?) Probably not - we need the actual
2055 # object to mock it so we would rather trigger a property than mock
2056 # the property descriptor. Likewise we want to mock out dynamically
2057 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002058 # XXXX what about attributes that raise exceptions other than
2059 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002060 # we could be resilient against it, or catch and propagate the
2061 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002062 try:
2063 original = getattr(spec, entry)
2064 except AttributeError:
2065 continue
Michael Foord345266a2012-03-14 12:24:34 -07002066
2067 kwargs = {'spec': original}
2068 if spec_set:
2069 kwargs = {'spec_set': original}
2070
2071 if not isinstance(original, FunctionTypes):
2072 new = _SpecState(original, spec_set, mock, entry, instance)
2073 mock._mock_children[entry] = new
2074 else:
2075 parent = mock
2076 if isinstance(spec, FunctionTypes):
2077 parent = mock.mock
2078
2079 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2080 _new_parent=parent, **kwargs)
2081 mock._mock_children[entry] = new
2082 skipfirst = _must_skip(spec, entry, is_type)
2083 _check_signature(original, new, skipfirst=skipfirst)
2084
2085 # so functions created with _set_signature become instance attributes,
2086 # *plus* their underlying mock exists in _mock_children of the parent
2087 # mock. Adding to _mock_children may be unnecessary where we are also
2088 # setting as an instance attribute?
2089 if isinstance(new, FunctionTypes):
2090 setattr(mock, entry, new)
2091
2092 return mock
2093
2094
2095def _must_skip(spec, entry, is_type):
2096 if not isinstance(spec, type):
2097 if entry in getattr(spec, '__dict__', {}):
2098 # instance attribute - shouldn't skip
2099 return False
Michael Foord345266a2012-03-14 12:24:34 -07002100 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002101
2102 for klass in spec.__mro__:
2103 result = klass.__dict__.get(entry, DEFAULT)
2104 if result is DEFAULT:
2105 continue
2106 if isinstance(result, (staticmethod, classmethod)):
2107 return False
2108 return is_type
2109
2110 # shouldn't get here unless function is a dynamically provided attribute
2111 # XXXX untested behaviour
2112 return is_type
2113
2114
2115def _get_class(obj):
2116 try:
2117 return obj.__class__
2118 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002119 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002120 return type(obj)
2121
2122
2123class _SpecState(object):
2124
2125 def __init__(self, spec, spec_set=False, parent=None,
2126 name=None, ids=None, instance=False):
2127 self.spec = spec
2128 self.ids = ids
2129 self.spec_set = spec_set
2130 self.parent = parent
2131 self.instance = instance
2132 self.name = name
2133
2134
2135FunctionTypes = (
2136 # python function
2137 type(create_autospec),
2138 # instance method
2139 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002140)
2141
Michael Foord345266a2012-03-14 12:24:34 -07002142
Michael Foorda74561a2012-03-25 19:03:13 +01002143file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002144
Michael Foord0dccf652012-03-25 19:11:50 +01002145
2146def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002147 """
2148 A helper function to create a mock to replace the use of `open`. It works
2149 for `open` called directly or used as a context manager.
2150
2151 The `mock` argument is the mock object to configure. If `None` (the
2152 default) then a `MagicMock` will be created for you, with the API limited
2153 to methods or attributes available on standard file handles.
2154
2155 `read_data` is a string for the `read` method of the file handle to return.
2156 This is an empty string by default.
2157 """
Michael Foorda74561a2012-03-25 19:03:13 +01002158 global file_spec
2159 if file_spec is None:
2160 import _io
2161 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2162
Michael Foord345266a2012-03-14 12:24:34 -07002163 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002164 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002165
2166 handle = MagicMock(spec=file_spec)
2167 handle.write.return_value = None
2168 handle.__enter__.return_value = handle
Michael Foord0dccf652012-03-25 19:11:50 +01002169 handle.read.return_value = read_data
Michael Foord345266a2012-03-14 12:24:34 -07002170
2171 mock.return_value = handle
2172 return mock
2173
2174
2175class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002176 """
2177 A mock intended to be used as a property, or other descriptor, on a class.
2178 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2179 a return value when it is fetched.
2180
2181 Fetching a `PropertyMock` instance from an object calls the mock, with
2182 no args. Setting it calls the mock with the value being set.
2183 """
Michael Foordc2870622012-04-13 16:57:22 +01002184 def _get_child_mock(self, **kwargs):
2185 return MagicMock(**kwargs)
2186
Michael Foord345266a2012-03-14 12:24:34 -07002187 def __get__(self, obj, obj_type):
2188 return self()
2189 def __set__(self, obj, val):
2190 self(val)