blob: 4ae3d16139e27d4fc99765a632404ca4d289e819 [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:
734 msg = ("Expected to be called once. Called %s times." %
735 self.call_count)
736 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
951 If `side_effect` is an iterable then each call to the mock will return
952 the next value from the iterable.
953
954 * `return_value`: The value returned when the mock is called. By default
955 this is a new Mock (created on first access). See the
956 `return_value` attribute.
957
Michael Foord0682a0c2012-04-13 20:51:20 +0100958 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
959 calling the Mock will pass the call through to the wrapped object
960 (returning the real result). Attribute access on the mock will return a
961 Mock object that wraps the corresponding attribute of the wrapped object
962 (so attempting to access an attribute that doesn't exist will raise an
963 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -0700964
965 If the mock has an explicit `return_value` set then calls are not passed
966 to the wrapped object and the `return_value` is returned instead.
967
968 * `name`: If the mock has a name then it will be used in the repr of the
969 mock. This can be useful for debugging. The name is propagated to child
970 mocks.
971
972 Mocks can also be called with arbitrary keyword arguments. These will be
973 used to set attributes on the mock after it is created.
974 """
975
976
977
978def _dot_lookup(thing, comp, import_path):
979 try:
980 return getattr(thing, comp)
981 except AttributeError:
982 __import__(import_path)
983 return getattr(thing, comp)
984
985
986def _importer(target):
987 components = target.split('.')
988 import_path = components.pop(0)
989 thing = __import__(import_path)
990
991 for comp in components:
992 import_path += ".%s" % comp
993 thing = _dot_lookup(thing, comp, import_path)
994 return thing
995
996
997def _is_started(patcher):
998 # XXXX horrible
999 return hasattr(patcher, 'is_local')
1000
1001
1002class _patch(object):
1003
1004 attribute_name = None
1005
1006 def __init__(
1007 self, getter, attribute, new, spec, create,
1008 spec_set, autospec, new_callable, kwargs
1009 ):
1010 if new_callable is not None:
1011 if new is not DEFAULT:
1012 raise ValueError(
1013 "Cannot use 'new' and 'new_callable' together"
1014 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001015 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001016 raise ValueError(
1017 "Cannot use 'autospec' and 'new_callable' together"
1018 )
1019
1020 self.getter = getter
1021 self.attribute = attribute
1022 self.new = new
1023 self.new_callable = new_callable
1024 self.spec = spec
1025 self.create = create
1026 self.has_local = False
1027 self.spec_set = spec_set
1028 self.autospec = autospec
1029 self.kwargs = kwargs
1030 self.additional_patchers = []
1031
1032
1033 def copy(self):
1034 patcher = _patch(
1035 self.getter, self.attribute, self.new, self.spec,
1036 self.create, self.spec_set,
1037 self.autospec, self.new_callable, self.kwargs
1038 )
1039 patcher.attribute_name = self.attribute_name
1040 patcher.additional_patchers = [
1041 p.copy() for p in self.additional_patchers
1042 ]
1043 return patcher
1044
1045
1046 def __call__(self, func):
1047 if isinstance(func, type):
1048 return self.decorate_class(func)
1049 return self.decorate_callable(func)
1050
1051
1052 def decorate_class(self, klass):
1053 for attr in dir(klass):
1054 if not attr.startswith(patch.TEST_PREFIX):
1055 continue
1056
1057 attr_value = getattr(klass, attr)
1058 if not hasattr(attr_value, "__call__"):
1059 continue
1060
1061 patcher = self.copy()
1062 setattr(klass, attr, patcher(attr_value))
1063 return klass
1064
1065
1066 def decorate_callable(self, func):
1067 if hasattr(func, 'patchings'):
1068 func.patchings.append(self)
1069 return func
1070
1071 @wraps(func)
1072 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001073 extra_args = []
1074 entered_patchers = []
1075
Michael Foord50a8c0e2012-03-25 18:57:58 +01001076 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001077 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001078 for patching in patched.patchings:
1079 arg = patching.__enter__()
1080 entered_patchers.append(patching)
1081 if patching.attribute_name is not None:
1082 keywargs.update(arg)
1083 elif patching.new is DEFAULT:
1084 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001085
Michael Foordd7c65e22012-03-14 14:56:54 -07001086 args += tuple(extra_args)
1087 return func(*args, **keywargs)
1088 except:
1089 if (patching not in entered_patchers and
1090 _is_started(patching)):
1091 # the patcher may have been started, but an exception
1092 # raised whilst entering one of its additional_patchers
1093 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001094 # Pass the exception to __exit__
1095 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001096 # re-raise the exception
1097 raise
Michael Foord345266a2012-03-14 12:24:34 -07001098 finally:
1099 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001100 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001101
1102 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001103 return patched
1104
1105
1106 def get_original(self):
1107 target = self.getter()
1108 name = self.attribute
1109
1110 original = DEFAULT
1111 local = False
1112
1113 try:
1114 original = target.__dict__[name]
1115 except (AttributeError, KeyError):
1116 original = getattr(target, name, DEFAULT)
1117 else:
1118 local = True
1119
1120 if not self.create and original is DEFAULT:
1121 raise AttributeError(
1122 "%s does not have the attribute %r" % (target, name)
1123 )
1124 return original, local
1125
1126
1127 def __enter__(self):
1128 """Perform the patch."""
1129 new, spec, spec_set = self.new, self.spec, self.spec_set
1130 autospec, kwargs = self.autospec, self.kwargs
1131 new_callable = self.new_callable
1132 self.target = self.getter()
1133
Michael Foord50a8c0e2012-03-25 18:57:58 +01001134 # normalise False to None
1135 if spec is False:
1136 spec = None
1137 if spec_set is False:
1138 spec_set = None
1139 if autospec is False:
1140 autospec = None
1141
1142 if spec is not None and autospec is not None:
1143 raise TypeError("Can't specify spec and autospec")
1144 if ((spec is not None or autospec is not None) and
1145 spec_set not in (True, None)):
1146 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1147
Michael Foord345266a2012-03-14 12:24:34 -07001148 original, local = self.get_original()
1149
Michael Foord50a8c0e2012-03-25 18:57:58 +01001150 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001151 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001152 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001153 # set spec to the object we are replacing
1154 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001155 if spec_set is True:
1156 spec_set = original
1157 spec = None
1158 elif spec is not None:
1159 if spec_set is True:
1160 spec_set = spec
1161 spec = None
1162 elif spec_set is True:
1163 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001164
Michael Foord50a8c0e2012-03-25 18:57:58 +01001165 if spec is not None or spec_set is not None:
1166 if original is DEFAULT:
1167 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001168 if isinstance(original, type):
1169 # If we're patching out a class and there is a spec
1170 inherit = True
1171
1172 Klass = MagicMock
1173 _kwargs = {}
1174 if new_callable is not None:
1175 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001176 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001177 this_spec = spec
1178 if spec_set is not None:
1179 this_spec = spec_set
1180 if _is_list(this_spec):
1181 not_callable = '__call__' not in this_spec
1182 else:
1183 not_callable = not callable(this_spec)
1184 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001185 Klass = NonCallableMagicMock
1186
1187 if spec is not None:
1188 _kwargs['spec'] = spec
1189 if spec_set is not None:
1190 _kwargs['spec_set'] = spec_set
1191
1192 # add a name to mocks
1193 if (isinstance(Klass, type) and
1194 issubclass(Klass, NonCallableMock) and self.attribute):
1195 _kwargs['name'] = self.attribute
1196
1197 _kwargs.update(kwargs)
1198 new = Klass(**_kwargs)
1199
1200 if inherit and _is_instance_mock(new):
1201 # we can only tell if the instance should be callable if the
1202 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001203 this_spec = spec
1204 if spec_set is not None:
1205 this_spec = spec_set
1206 if (not _is_list(this_spec) and not
1207 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001208 Klass = NonCallableMagicMock
1209
1210 _kwargs.pop('name')
1211 new.return_value = Klass(_new_parent=new, _new_name='()',
1212 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001213 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001214 # spec is ignored, new *must* be default, spec_set is treated
1215 # as a boolean. Should we check spec is not None and that spec_set
1216 # is a bool?
1217 if new is not DEFAULT:
1218 raise TypeError(
1219 "autospec creates the mock for you. Can't specify "
1220 "autospec and new."
1221 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001222 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001223 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001224 spec_set = bool(spec_set)
1225 if autospec is True:
1226 autospec = original
1227
1228 new = create_autospec(autospec, spec_set=spec_set,
1229 _name=self.attribute, **kwargs)
1230 elif kwargs:
1231 # can't set keyword args when we aren't creating the mock
1232 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1233 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1234
1235 new_attr = new
1236
1237 self.temp_original = original
1238 self.is_local = local
1239 setattr(self.target, self.attribute, new_attr)
1240 if self.attribute_name is not None:
1241 extra_args = {}
1242 if self.new is DEFAULT:
1243 extra_args[self.attribute_name] = new
1244 for patching in self.additional_patchers:
1245 arg = patching.__enter__()
1246 if patching.new is DEFAULT:
1247 extra_args.update(arg)
1248 return extra_args
1249
1250 return new
1251
1252
Michael Foord50a8c0e2012-03-25 18:57:58 +01001253 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001254 """Undo the patch."""
1255 if not _is_started(self):
1256 raise RuntimeError('stop called on unstarted patcher')
1257
1258 if self.is_local and self.temp_original is not DEFAULT:
1259 setattr(self.target, self.attribute, self.temp_original)
1260 else:
1261 delattr(self.target, self.attribute)
1262 if not self.create and not hasattr(self.target, self.attribute):
1263 # needed for proxy objects like django settings
1264 setattr(self.target, self.attribute, self.temp_original)
1265
1266 del self.temp_original
1267 del self.is_local
1268 del self.target
1269 for patcher in reversed(self.additional_patchers):
1270 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001271 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001272
1273 start = __enter__
1274 stop = __exit__
1275
1276
1277
1278def _get_target(target):
1279 try:
1280 target, attribute = target.rsplit('.', 1)
1281 except (TypeError, ValueError):
1282 raise TypeError("Need a valid target to patch. You supplied: %r" %
1283 (target,))
1284 getter = lambda: _importer(target)
1285 return getter, attribute
1286
1287
1288def _patch_object(
1289 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001290 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001291 new_callable=None, **kwargs
1292 ):
1293 """
Michael Foord345266a2012-03-14 12:24:34 -07001294 patch the named member (`attribute`) on an object (`target`) with a mock
1295 object.
1296
1297 `patch.object` can be used as a decorator, class decorator or a context
1298 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1299 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1300 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1301 the mock object it creates.
1302
1303 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1304 for choosing which methods to wrap.
1305 """
1306 getter = lambda: target
1307 return _patch(
1308 getter, attribute, new, spec, create,
1309 spec_set, autospec, new_callable, kwargs
1310 )
1311
1312
Michael Foord50a8c0e2012-03-25 18:57:58 +01001313def _patch_multiple(target, spec=None, create=False, spec_set=None,
1314 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001315 """Perform multiple patches in a single call. It takes the object to be
1316 patched (either as an object or a string to fetch the object by importing)
1317 and keyword arguments for the patches::
1318
1319 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1320 ...
1321
1322 Use `DEFAULT` as the value if you want `patch.multiple` to create
1323 mocks for you. In this case the created mocks are passed into a decorated
1324 function by keyword, and a dictionary is returned when `patch.multiple` is
1325 used as a context manager.
1326
1327 `patch.multiple` can be used as a decorator, class decorator or a context
1328 manager. The arguments `spec`, `spec_set`, `create`,
1329 `autospec` and `new_callable` have the same meaning as for `patch`. These
1330 arguments will be applied to *all* patches done by `patch.multiple`.
1331
1332 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1333 for choosing which methods to wrap.
1334 """
1335 if type(target) is str:
1336 getter = lambda: _importer(target)
1337 else:
1338 getter = lambda: target
1339
1340 if not kwargs:
1341 raise ValueError(
1342 'Must supply at least one keyword argument with patch.multiple'
1343 )
1344 # need to wrap in a list for python 3, where items is a view
1345 items = list(kwargs.items())
1346 attribute, new = items[0]
1347 patcher = _patch(
1348 getter, attribute, new, spec, create, spec_set,
1349 autospec, new_callable, {}
1350 )
1351 patcher.attribute_name = attribute
1352 for attribute, new in items[1:]:
1353 this_patcher = _patch(
1354 getter, attribute, new, spec, create, spec_set,
1355 autospec, new_callable, {}
1356 )
1357 this_patcher.attribute_name = attribute
1358 patcher.additional_patchers.append(this_patcher)
1359 return patcher
1360
1361
1362def patch(
1363 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001364 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001365 ):
1366 """
1367 `patch` acts as a function decorator, class decorator or a context
1368 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001369 is patched with a `new` object. When the function/with statement exits
1370 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001371
Michael Foord54b3db82012-03-28 15:08:08 +01001372 If `new` is omitted, then the target is replaced with a
1373 `MagicMock`. If `patch` is used as a decorator and `new` is
1374 omitted, the created mock is passed in as an extra argument to the
1375 decorated function. If `patch` is used as a context manager the created
1376 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001377
Michael Foord54b3db82012-03-28 15:08:08 +01001378 `target` should be a string in the form `'package.module.ClassName'`. The
1379 `target` is imported and the specified object replaced with the `new`
1380 object, so the `target` must be importable from the environment you are
1381 calling `patch` from. The target is imported when the decorated function
1382 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001383
1384 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1385 if patch is creating one for you.
1386
1387 In addition you can pass `spec=True` or `spec_set=True`, which causes
1388 patch to pass in the object being mocked as the spec/spec_set object.
1389
1390 `new_callable` allows you to specify a different class, or callable object,
1391 that will be called to create the `new` object. By default `MagicMock` is
1392 used.
1393
1394 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1395 then the mock with be created with a spec from the object being replaced.
1396 All attributes of the mock will also have the spec of the corresponding
1397 attribute of the object being replaced. Methods and functions being
1398 mocked will have their arguments checked and will raise a `TypeError` if
1399 they are called with the wrong signature. For mocks replacing a class,
1400 their return value (the 'instance') will have the same spec as the class.
1401
1402 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1403 arbitrary object as the spec instead of the one being replaced.
1404
1405 By default `patch` will fail to replace attributes that don't exist. If
1406 you pass in `create=True`, and the attribute doesn't exist, patch will
1407 create the attribute for you when the patched function is called, and
1408 delete it again afterwards. This is useful for writing tests against
1409 attributes that your production code creates at runtime. It is off by by
1410 default because it can be dangerous. With it switched on you can write
1411 passing tests against APIs that don't actually exist!
1412
1413 Patch can be used as a `TestCase` class decorator. It works by
1414 decorating each test method in the class. This reduces the boilerplate
1415 code when your test methods share a common patchings set. `patch` finds
1416 tests by looking for method names that start with `patch.TEST_PREFIX`.
1417 By default this is `test`, which matches the way `unittest` finds tests.
1418 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1419
1420 Patch can be used as a context manager, with the with statement. Here the
1421 patching applies to the indented block after the with statement. If you
1422 use "as" then the patched object will be bound to the name after the
1423 "as"; very useful if `patch` is creating a mock object for you.
1424
1425 `patch` takes arbitrary keyword arguments. These will be passed to
1426 the `Mock` (or `new_callable`) on construction.
1427
1428 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1429 available for alternate use-cases.
1430 """
1431 getter, attribute = _get_target(target)
1432 return _patch(
1433 getter, attribute, new, spec, create,
1434 spec_set, autospec, new_callable, kwargs
1435 )
1436
1437
1438class _patch_dict(object):
1439 """
1440 Patch a dictionary, or dictionary like object, and restore the dictionary
1441 to its original state after the test.
1442
1443 `in_dict` can be a dictionary or a mapping like container. If it is a
1444 mapping then it must at least support getting, setting and deleting items
1445 plus iterating over keys.
1446
1447 `in_dict` can also be a string specifying the name of the dictionary, which
1448 will then be fetched by importing it.
1449
1450 `values` can be a dictionary of values to set in the dictionary. `values`
1451 can also be an iterable of `(key, value)` pairs.
1452
1453 If `clear` is True then the dictionary will be cleared before the new
1454 values are set.
1455
1456 `patch.dict` can also be called with arbitrary keyword arguments to set
1457 values in the dictionary::
1458
1459 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1460 ...
1461
1462 `patch.dict` can be used as a context manager, decorator or class
1463 decorator. When used as a class decorator `patch.dict` honours
1464 `patch.TEST_PREFIX` for choosing which methods to wrap.
1465 """
1466
1467 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1468 if isinstance(in_dict, str):
1469 in_dict = _importer(in_dict)
1470 self.in_dict = in_dict
1471 # support any argument supported by dict(...) constructor
1472 self.values = dict(values)
1473 self.values.update(kwargs)
1474 self.clear = clear
1475 self._original = None
1476
1477
1478 def __call__(self, f):
1479 if isinstance(f, type):
1480 return self.decorate_class(f)
1481 @wraps(f)
1482 def _inner(*args, **kw):
1483 self._patch_dict()
1484 try:
1485 return f(*args, **kw)
1486 finally:
1487 self._unpatch_dict()
1488
1489 return _inner
1490
1491
1492 def decorate_class(self, klass):
1493 for attr in dir(klass):
1494 attr_value = getattr(klass, attr)
1495 if (attr.startswith(patch.TEST_PREFIX) and
1496 hasattr(attr_value, "__call__")):
1497 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1498 decorated = decorator(attr_value)
1499 setattr(klass, attr, decorated)
1500 return klass
1501
1502
1503 def __enter__(self):
1504 """Patch the dict."""
1505 self._patch_dict()
1506
1507
1508 def _patch_dict(self):
1509 values = self.values
1510 in_dict = self.in_dict
1511 clear = self.clear
1512
1513 try:
1514 original = in_dict.copy()
1515 except AttributeError:
1516 # dict like object with no copy method
1517 # must support iteration over keys
1518 original = {}
1519 for key in in_dict:
1520 original[key] = in_dict[key]
1521 self._original = original
1522
1523 if clear:
1524 _clear_dict(in_dict)
1525
1526 try:
1527 in_dict.update(values)
1528 except AttributeError:
1529 # dict like object with no update method
1530 for key in values:
1531 in_dict[key] = values[key]
1532
1533
1534 def _unpatch_dict(self):
1535 in_dict = self.in_dict
1536 original = self._original
1537
1538 _clear_dict(in_dict)
1539
1540 try:
1541 in_dict.update(original)
1542 except AttributeError:
1543 for key in original:
1544 in_dict[key] = original[key]
1545
1546
1547 def __exit__(self, *args):
1548 """Unpatch the dict."""
1549 self._unpatch_dict()
1550 return False
1551
1552 start = __enter__
1553 stop = __exit__
1554
1555
1556def _clear_dict(in_dict):
1557 try:
1558 in_dict.clear()
1559 except AttributeError:
1560 keys = list(in_dict)
1561 for key in keys:
1562 del in_dict[key]
1563
1564
1565patch.object = _patch_object
1566patch.dict = _patch_dict
1567patch.multiple = _patch_multiple
1568patch.TEST_PREFIX = 'test'
1569
1570magic_methods = (
1571 "lt le gt ge eq ne "
1572 "getitem setitem delitem "
1573 "len contains iter "
1574 "hash str sizeof "
1575 "enter exit "
1576 "divmod neg pos abs invert "
1577 "complex int float index "
1578 "trunc floor ceil "
1579 "bool next "
1580)
1581
1582numerics = "add sub mul div floordiv mod lshift rshift and xor or pow "
1583inplace = ' '.join('i%s' % n for n in numerics.split())
1584right = ' '.join('r%s' % n for n in numerics.split())
1585
1586# not including __prepare__, __instancecheck__, __subclasscheck__
1587# (as they are metaclass methods)
1588# __del__ is not supported at all as it causes problems if it exists
1589
1590_non_defaults = set('__%s__' % method for method in [
Michael Foord944e02d2012-03-25 23:12:55 +01001591 'get', 'set', 'delete', 'reversed', 'missing', 'reduce', 'reduce_ex',
1592 'getinitargs', 'getnewargs', 'getstate', 'setstate', 'getformat',
1593 'setformat', 'repr', 'dir', 'subclasses', 'format',
Michael Foord345266a2012-03-14 12:24:34 -07001594])
1595
1596
1597def _get_method(name, func):
1598 "Turns a callable object (like a mock) into a real function"
1599 def method(self, *args, **kw):
1600 return func(self, *args, **kw)
1601 method.__name__ = name
1602 return method
1603
1604
1605_magics = set(
1606 '__%s__' % method for method in
1607 ' '.join([magic_methods, numerics, inplace, right]).split()
1608)
1609
1610_all_magics = _magics | _non_defaults
1611
1612_unsupported_magics = set([
1613 '__getattr__', '__setattr__',
1614 '__init__', '__new__', '__prepare__'
1615 '__instancecheck__', '__subclasscheck__',
1616 '__del__'
1617])
1618
1619_calculate_return_value = {
1620 '__hash__': lambda self: object.__hash__(self),
1621 '__str__': lambda self: object.__str__(self),
1622 '__sizeof__': lambda self: object.__sizeof__(self),
1623}
1624
1625_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001626 '__lt__': NotImplemented,
1627 '__gt__': NotImplemented,
1628 '__le__': NotImplemented,
1629 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001630 '__int__': 1,
1631 '__contains__': False,
1632 '__len__': 0,
1633 '__exit__': False,
1634 '__complex__': 1j,
1635 '__float__': 1.0,
1636 '__bool__': True,
1637 '__index__': 1,
1638}
1639
1640
1641def _get_eq(self):
1642 def __eq__(other):
1643 ret_val = self.__eq__._mock_return_value
1644 if ret_val is not DEFAULT:
1645 return ret_val
1646 return self is other
1647 return __eq__
1648
1649def _get_ne(self):
1650 def __ne__(other):
1651 if self.__ne__._mock_return_value is not DEFAULT:
1652 return DEFAULT
1653 return self is not other
1654 return __ne__
1655
1656def _get_iter(self):
1657 def __iter__():
1658 ret_val = self.__iter__._mock_return_value
1659 if ret_val is DEFAULT:
1660 return iter([])
1661 # if ret_val was already an iterator, then calling iter on it should
1662 # return the iterator unchanged
1663 return iter(ret_val)
1664 return __iter__
1665
1666_side_effect_methods = {
1667 '__eq__': _get_eq,
1668 '__ne__': _get_ne,
1669 '__iter__': _get_iter,
1670}
1671
1672
1673
1674def _set_return_value(mock, method, name):
1675 fixed = _return_values.get(name, DEFAULT)
1676 if fixed is not DEFAULT:
1677 method.return_value = fixed
1678 return
1679
1680 return_calulator = _calculate_return_value.get(name)
1681 if return_calulator is not None:
1682 try:
1683 return_value = return_calulator(mock)
1684 except AttributeError:
1685 # XXXX why do we return AttributeError here?
1686 # set it as a side_effect instead?
1687 return_value = AttributeError(name)
1688 method.return_value = return_value
1689 return
1690
1691 side_effector = _side_effect_methods.get(name)
1692 if side_effector is not None:
1693 method.side_effect = side_effector(mock)
1694
1695
1696
1697class MagicMixin(object):
1698 def __init__(self, *args, **kw):
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001699 _safe_super(MagicMixin, self).__init__(*args, **kw)
Michael Foord345266a2012-03-14 12:24:34 -07001700 self._mock_set_magics()
1701
1702
1703 def _mock_set_magics(self):
1704 these_magics = _magics
1705
1706 if self._mock_methods is not None:
1707 these_magics = _magics.intersection(self._mock_methods)
1708
1709 remove_magics = set()
1710 remove_magics = _magics - these_magics
1711
1712 for entry in remove_magics:
1713 if entry in type(self).__dict__:
1714 # remove unneeded magic methods
1715 delattr(self, entry)
1716
1717 # don't overwrite existing attributes if called a second time
1718 these_magics = these_magics - set(type(self).__dict__)
1719
1720 _type = type(self)
1721 for entry in these_magics:
1722 setattr(_type, entry, MagicProxy(entry, self))
1723
1724
1725
1726class NonCallableMagicMock(MagicMixin, NonCallableMock):
1727 """A version of `MagicMock` that isn't callable."""
1728 def mock_add_spec(self, spec, spec_set=False):
1729 """Add a spec to a mock. `spec` can either be an object or a
1730 list of strings. Only attributes on the `spec` can be fetched as
1731 attributes from the mock.
1732
1733 If `spec_set` is True then only attributes on the spec can be set."""
1734 self._mock_add_spec(spec, spec_set)
1735 self._mock_set_magics()
1736
1737
1738
1739class MagicMock(MagicMixin, Mock):
1740 """
1741 MagicMock is a subclass of Mock with default implementations
1742 of most of the magic methods. You can use MagicMock without having to
1743 configure the magic methods yourself.
1744
1745 If you use the `spec` or `spec_set` arguments then *only* magic
1746 methods that exist in the spec will be created.
1747
1748 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1749 """
1750 def mock_add_spec(self, spec, spec_set=False):
1751 """Add a spec to a mock. `spec` can either be an object or a
1752 list of strings. Only attributes on the `spec` can be fetched as
1753 attributes from the mock.
1754
1755 If `spec_set` is True then only attributes on the spec can be set."""
1756 self._mock_add_spec(spec, spec_set)
1757 self._mock_set_magics()
1758
1759
1760
1761class MagicProxy(object):
1762 def __init__(self, name, parent):
1763 self.name = name
1764 self.parent = parent
1765
1766 def __call__(self, *args, **kwargs):
1767 m = self.create_mock()
1768 return m(*args, **kwargs)
1769
1770 def create_mock(self):
1771 entry = self.name
1772 parent = self.parent
1773 m = parent._get_child_mock(name=entry, _new_name=entry,
1774 _new_parent=parent)
1775 setattr(parent, entry, m)
1776 _set_return_value(parent, m, entry)
1777 return m
1778
1779 def __get__(self, obj, _type=None):
1780 return self.create_mock()
1781
1782
1783
1784class _ANY(object):
1785 "A helper object that compares equal to everything."
1786
1787 def __eq__(self, other):
1788 return True
1789
1790 def __ne__(self, other):
1791 return False
1792
1793 def __repr__(self):
1794 return '<ANY>'
1795
1796ANY = _ANY()
1797
1798
1799
1800def _format_call_signature(name, args, kwargs):
1801 message = '%s(%%s)' % name
1802 formatted_args = ''
1803 args_string = ', '.join([repr(arg) for arg in args])
1804 kwargs_string = ', '.join([
1805 '%s=%r' % (key, value) for key, value in kwargs.items()
1806 ])
1807 if args_string:
1808 formatted_args = args_string
1809 if kwargs_string:
1810 if formatted_args:
1811 formatted_args += ', '
1812 formatted_args += kwargs_string
1813
1814 return message % formatted_args
1815
1816
1817
1818class _Call(tuple):
1819 """
1820 A tuple for holding the results of a call to a mock, either in the form
1821 `(args, kwargs)` or `(name, args, kwargs)`.
1822
1823 If args or kwargs are empty then a call tuple will compare equal to
1824 a tuple without those values. This makes comparisons less verbose::
1825
1826 _Call(('name', (), {})) == ('name',)
1827 _Call(('name', (1,), {})) == ('name', (1,))
1828 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1829
1830 The `_Call` object provides a useful shortcut for comparing with call::
1831
1832 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1833 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1834
1835 If the _Call has no name then it will match any name.
1836 """
1837 def __new__(cls, value=(), name=None, parent=None, two=False,
1838 from_kall=True):
1839 name = ''
1840 args = ()
1841 kwargs = {}
1842 _len = len(value)
1843 if _len == 3:
1844 name, args, kwargs = value
1845 elif _len == 2:
1846 first, second = value
1847 if isinstance(first, str):
1848 name = first
1849 if isinstance(second, tuple):
1850 args = second
1851 else:
1852 kwargs = second
1853 else:
1854 args, kwargs = first, second
1855 elif _len == 1:
1856 value, = value
1857 if isinstance(value, str):
1858 name = value
1859 elif isinstance(value, tuple):
1860 args = value
1861 else:
1862 kwargs = value
1863
1864 if two:
1865 return tuple.__new__(cls, (args, kwargs))
1866
1867 return tuple.__new__(cls, (name, args, kwargs))
1868
1869
1870 def __init__(self, value=(), name=None, parent=None, two=False,
1871 from_kall=True):
1872 self.name = name
1873 self.parent = parent
1874 self.from_kall = from_kall
1875
1876
1877 def __eq__(self, other):
1878 if other is ANY:
1879 return True
1880 try:
1881 len_other = len(other)
1882 except TypeError:
1883 return False
1884
1885 self_name = ''
1886 if len(self) == 2:
1887 self_args, self_kwargs = self
1888 else:
1889 self_name, self_args, self_kwargs = self
1890
1891 other_name = ''
1892 if len_other == 0:
1893 other_args, other_kwargs = (), {}
1894 elif len_other == 3:
1895 other_name, other_args, other_kwargs = other
1896 elif len_other == 1:
1897 value, = other
1898 if isinstance(value, tuple):
1899 other_args = value
1900 other_kwargs = {}
1901 elif isinstance(value, str):
1902 other_name = value
1903 other_args, other_kwargs = (), {}
1904 else:
1905 other_args = ()
1906 other_kwargs = value
1907 else:
1908 # len 2
1909 # could be (name, args) or (name, kwargs) or (args, kwargs)
1910 first, second = other
1911 if isinstance(first, str):
1912 other_name = first
1913 if isinstance(second, tuple):
1914 other_args, other_kwargs = second, {}
1915 else:
1916 other_args, other_kwargs = (), second
1917 else:
1918 other_args, other_kwargs = first, second
1919
1920 if self_name and other_name != self_name:
1921 return False
1922
1923 # this order is important for ANY to work!
1924 return (other_args, other_kwargs) == (self_args, self_kwargs)
1925
1926
1927 def __ne__(self, other):
1928 return not self.__eq__(other)
1929
1930
1931 def __call__(self, *args, **kwargs):
1932 if self.name is None:
1933 return _Call(('', args, kwargs), name='()')
1934
1935 name = self.name + '()'
1936 return _Call((self.name, args, kwargs), name=name, parent=self)
1937
1938
1939 def __getattr__(self, attr):
1940 if self.name is None:
1941 return _Call(name=attr, from_kall=False)
1942 name = '%s.%s' % (self.name, attr)
1943 return _Call(name=name, parent=self, from_kall=False)
1944
1945
1946 def __repr__(self):
1947 if not self.from_kall:
1948 name = self.name or 'call'
1949 if name.startswith('()'):
1950 name = 'call%s' % name
1951 return name
1952
1953 if len(self) == 2:
1954 name = 'call'
1955 args, kwargs = self
1956 else:
1957 name, args, kwargs = self
1958 if not name:
1959 name = 'call'
1960 elif not name.startswith('()'):
1961 name = 'call.%s' % name
1962 else:
1963 name = 'call%s' % name
1964 return _format_call_signature(name, args, kwargs)
1965
1966
1967 def call_list(self):
1968 """For a call object that represents multiple calls, `call_list`
1969 returns a list of all the intermediate calls as well as the
1970 final call."""
1971 vals = []
1972 thing = self
1973 while thing is not None:
1974 if thing.from_kall:
1975 vals.append(thing)
1976 thing = thing.parent
1977 return _CallList(reversed(vals))
1978
1979
1980call = _Call(from_kall=False)
1981
1982
1983
1984def create_autospec(spec, spec_set=False, instance=False, _parent=None,
1985 _name=None, **kwargs):
1986 """Create a mock object using another object as a spec. Attributes on the
1987 mock will use the corresponding attribute on the `spec` object as their
1988 spec.
1989
1990 Functions or methods being mocked will have their arguments checked
1991 to check that they are called with the correct signature.
1992
1993 If `spec_set` is True then attempting to set attributes that don't exist
1994 on the spec object will raise an `AttributeError`.
1995
1996 If a class is used as a spec then the return value of the mock (the
1997 instance of the class) will have the same spec. You can use a class as the
1998 spec for an instance object by passing `instance=True`. The returned mock
1999 will only be callable if instances of the mock are callable.
2000
2001 `create_autospec` also takes arbitrary keyword arguments that are passed to
2002 the constructor of the created mock."""
2003 if _is_list(spec):
2004 # can't pass a list instance to the mock constructor as it will be
2005 # interpreted as a list of strings
2006 spec = type(spec)
2007
2008 is_type = isinstance(spec, type)
2009
2010 _kwargs = {'spec': spec}
2011 if spec_set:
2012 _kwargs = {'spec_set': spec}
2013 elif spec is None:
2014 # None we mock with a normal mock without a spec
2015 _kwargs = {}
2016
2017 _kwargs.update(kwargs)
2018
2019 Klass = MagicMock
2020 if type(spec) in DescriptorTypes:
2021 # descriptors don't have a spec
2022 # because we don't know what type they return
2023 _kwargs = {}
2024 elif not _callable(spec):
2025 Klass = NonCallableMagicMock
2026 elif is_type and instance and not _instance_callable(spec):
2027 Klass = NonCallableMagicMock
2028
2029 _new_name = _name
2030 if _parent is None:
2031 # for a top level object no _new_name should be set
2032 _new_name = ''
2033
2034 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2035 name=_name, **_kwargs)
2036
2037 if isinstance(spec, FunctionTypes):
2038 # should only happen at the top level because we don't
2039 # recurse for functions
2040 mock = _set_signature(mock, spec)
2041 else:
2042 _check_signature(spec, mock, is_type, instance)
2043
2044 if _parent is not None and not instance:
2045 _parent._mock_children[_name] = mock
2046
2047 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002048 mock.return_value = create_autospec(spec, spec_set, instance=True,
2049 _name='()', _parent=mock)
2050
2051 for entry in dir(spec):
2052 if _is_magic(entry):
2053 # MagicMock already does the useful magic methods for us
2054 continue
2055
Michael Foord345266a2012-03-14 12:24:34 -07002056 # XXXX do we need a better way of getting attributes without
2057 # triggering code execution (?) Probably not - we need the actual
2058 # object to mock it so we would rather trigger a property than mock
2059 # the property descriptor. Likewise we want to mock out dynamically
2060 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002061 # XXXX what about attributes that raise exceptions other than
2062 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002063 # we could be resilient against it, or catch and propagate the
2064 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002065 try:
2066 original = getattr(spec, entry)
2067 except AttributeError:
2068 continue
Michael Foord345266a2012-03-14 12:24:34 -07002069
2070 kwargs = {'spec': original}
2071 if spec_set:
2072 kwargs = {'spec_set': original}
2073
2074 if not isinstance(original, FunctionTypes):
2075 new = _SpecState(original, spec_set, mock, entry, instance)
2076 mock._mock_children[entry] = new
2077 else:
2078 parent = mock
2079 if isinstance(spec, FunctionTypes):
2080 parent = mock.mock
2081
2082 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2083 _new_parent=parent, **kwargs)
2084 mock._mock_children[entry] = new
2085 skipfirst = _must_skip(spec, entry, is_type)
2086 _check_signature(original, new, skipfirst=skipfirst)
2087
2088 # so functions created with _set_signature become instance attributes,
2089 # *plus* their underlying mock exists in _mock_children of the parent
2090 # mock. Adding to _mock_children may be unnecessary where we are also
2091 # setting as an instance attribute?
2092 if isinstance(new, FunctionTypes):
2093 setattr(mock, entry, new)
2094
2095 return mock
2096
2097
2098def _must_skip(spec, entry, is_type):
2099 if not isinstance(spec, type):
2100 if entry in getattr(spec, '__dict__', {}):
2101 # instance attribute - shouldn't skip
2102 return False
Michael Foord345266a2012-03-14 12:24:34 -07002103 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002104
2105 for klass in spec.__mro__:
2106 result = klass.__dict__.get(entry, DEFAULT)
2107 if result is DEFAULT:
2108 continue
2109 if isinstance(result, (staticmethod, classmethod)):
2110 return False
2111 return is_type
2112
2113 # shouldn't get here unless function is a dynamically provided attribute
2114 # XXXX untested behaviour
2115 return is_type
2116
2117
2118def _get_class(obj):
2119 try:
2120 return obj.__class__
2121 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002122 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002123 return type(obj)
2124
2125
2126class _SpecState(object):
2127
2128 def __init__(self, spec, spec_set=False, parent=None,
2129 name=None, ids=None, instance=False):
2130 self.spec = spec
2131 self.ids = ids
2132 self.spec_set = spec_set
2133 self.parent = parent
2134 self.instance = instance
2135 self.name = name
2136
2137
2138FunctionTypes = (
2139 # python function
2140 type(create_autospec),
2141 # instance method
2142 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002143)
2144
Michael Foord345266a2012-03-14 12:24:34 -07002145
Michael Foorda74561a2012-03-25 19:03:13 +01002146file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002147
Michael Foord0dccf652012-03-25 19:11:50 +01002148
2149def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002150 """
2151 A helper function to create a mock to replace the use of `open`. It works
2152 for `open` called directly or used as a context manager.
2153
2154 The `mock` argument is the mock object to configure. If `None` (the
2155 default) then a `MagicMock` will be created for you, with the API limited
2156 to methods or attributes available on standard file handles.
2157
2158 `read_data` is a string for the `read` method of the file handle to return.
2159 This is an empty string by default.
2160 """
Michael Foorda74561a2012-03-25 19:03:13 +01002161 global file_spec
2162 if file_spec is None:
2163 import _io
2164 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2165
Michael Foord345266a2012-03-14 12:24:34 -07002166 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002167 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002168
2169 handle = MagicMock(spec=file_spec)
2170 handle.write.return_value = None
2171 handle.__enter__.return_value = handle
Michael Foord0dccf652012-03-25 19:11:50 +01002172 handle.read.return_value = read_data
Michael Foord345266a2012-03-14 12:24:34 -07002173
2174 mock.return_value = handle
2175 return mock
2176
2177
2178class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002179 """
2180 A mock intended to be used as a property, or other descriptor, on a class.
2181 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2182 a return value when it is fetched.
2183
2184 Fetching a `PropertyMock` instance from an object calls the mock, with
2185 no args. Setting it calls the mock with the value being set.
2186 """
Michael Foordc2870622012-04-13 16:57:22 +01002187 def _get_child_mock(self, **kwargs):
2188 return MagicMock(**kwargs)
2189
Michael Foord345266a2012-03-14 12:24:34 -07002190 def __get__(self, obj, obj_type):
2191 return self()
2192 def __set__(self, obj, val):
2193 self(val)