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