blob: 8ab2b7c980c12bc6cf6045f5d295de6f173819b4 [file] [log] [blame]
Michael Foord1e68bec2012-03-03 22:24:30 +00001# mock.py
2# Test tools for mocking and patching.
Michael Foord1e68bec2012-03-03 22:24:30 +00003# E-mail: fuzzyman AT voidspace DOT org DOT uk
Michael Foord0d72ca92013-04-09 14:51:43 +01004#
Michael Foord320cfad2012-11-05 22:18:29 +00005# mock 1.0.1
Michael Foord1e68bec2012-03-03 22:24:30 +00006# http://www.voidspace.org.uk/python/mock/
Michael Foord0d72ca92013-04-09 14:51:43 +01007#
8# Copyright (c) 2007-2013, Michael Foord & the mock team
9# All rights reserved.
10#
11# Redistribution and use in source and binary forms, with or without
12# modification, are permitted provided that the following conditions are
13# met:
14#
15# * Redistributions of source code must retain the above copyright
16# notice, this list of conditions and the following disclaimer.
17#
18# * Redistributions in binary form must reproduce the above
19# copyright notice, this list of conditions and the following
20# disclaimer in the documentation and/or other materials provided
21# with the distribution.
22#
23# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Michael Foord1e68bec2012-03-03 22:24:30 +000034
Michael Foord1e68bec2012-03-03 22:24:30 +000035__all__ = (
36 'Mock',
37 'MagicMock',
Michael Foord1e68bec2012-03-03 22:24:30 +000038 'patch',
39 'sentinel',
40 'DEFAULT',
41 'ANY',
42 'call',
43 'create_autospec',
44 'FILTER_DIR',
45 'NonCallableMock',
46 'NonCallableMagicMock',
Michael Foordafc98d42012-03-13 16:38:50 -070047 'mock_open',
Michael Foord4b4c9152012-03-13 23:34:50 -070048 'PropertyMock',
Michael Foord1e68bec2012-03-03 22:24:30 +000049)
50
51
Michael Foord3860ed42012-11-05 21:38:05 +000052__version__ = '1.0.1'
Michael Foord1e68bec2012-03-03 22:24:30 +000053
54
55import pprint
56import sys
57
58try:
59 import inspect
60except ImportError:
61 # for alternative platforms that
62 # may not have inspect
63 inspect = None
64
65try:
Michael Foord3860ed42012-11-05 21:38:05 +000066 from functools import wraps as original_wraps
Michael Foord1e68bec2012-03-03 22:24:30 +000067except ImportError:
68 # Python 2.4 compatibility
69 def wraps(original):
70 def inner(f):
71 f.__name__ = original.__name__
72 f.__doc__ = original.__doc__
73 f.__module__ = original.__module__
Michael Foordb1079532012-11-07 17:08:38 +000074 wrapped = getattr(original, '__wrapped__', original)
75 f.__wrapped__ = wrapped
Michael Foord1e68bec2012-03-03 22:24:30 +000076 return f
77 return inner
Michael Foord3860ed42012-11-05 21:38:05 +000078else:
Michael Foord15725672012-11-05 22:30:02 +000079 if sys.version_info[:2] >= (3, 2):
Michael Foord3860ed42012-11-05 21:38:05 +000080 wraps = original_wraps
81 else:
82 def wraps(func):
83 def inner(f):
84 f = original_wraps(func)(f)
Michael Foordb1079532012-11-07 17:08:38 +000085 wrapped = getattr(func, '__wrapped__', func)
86 f.__wrapped__ = wrapped
Michael Foord3860ed42012-11-05 21:38:05 +000087 return f
88 return inner
Michael Foord1e68bec2012-03-03 22:24:30 +000089
90try:
91 unicode
92except NameError:
93 # Python 3
94 basestring = unicode = str
95
96try:
97 long
98except NameError:
99 # Python 3
100 long = int
101
102try:
103 BaseException
104except NameError:
105 # Python 2.4 compatibility
106 BaseException = Exception
107
108try:
109 next
110except NameError:
111 def next(obj):
112 return obj.next()
113
114
115BaseExceptions = (BaseException,)
116if 'java' in sys.platform:
117 # jython
118 import java
119 BaseExceptions = (BaseException, java.lang.Throwable)
120
121try:
122 _isidentifier = str.isidentifier
123except AttributeError:
124 # Python 2.X
125 import keyword
126 import re
127 regex = re.compile(r'^[a-z_][a-z0-9_]*$', re.I)
128 def _isidentifier(string):
129 if string in keyword.kwlist:
130 return False
131 return regex.match(string)
132
133
134inPy3k = sys.version_info[0] == 3
135
136# Needed to work around Python 3 bug where use of "super" interferes with
137# defining __class__ as a descriptor
138_super = super
139
140self = 'im_self'
141builtin = '__builtin__'
142if inPy3k:
143 self = '__self__'
144 builtin = 'builtins'
145
146FILTER_DIR = True
147
148
149def _is_instance_mock(obj):
150 # can't use isinstance on Mock objects because they override __class__
151 # The base class for all mocks is NonCallableMock
152 return issubclass(type(obj), NonCallableMock)
153
154
155def _is_exception(obj):
156 return (
157 isinstance(obj, BaseExceptions) or
158 isinstance(obj, ClassTypes) and issubclass(obj, BaseExceptions)
159 )
160
161
162class _slotted(object):
163 __slots__ = ['a']
164
165
166DescriptorTypes = (
167 type(_slotted.a),
168 property,
169)
170
171
Michael Foorda9a8bb92012-03-13 14:39:59 -0700172def _getsignature(func, skipfirst, instance=False):
Michael Foord1e68bec2012-03-03 22:24:30 +0000173 if inspect is None:
174 raise ImportError('inspect module not available')
175
176 if isinstance(func, ClassTypes) and not instance:
177 try:
178 func = func.__init__
179 except AttributeError:
180 return
181 skipfirst = True
182 elif not isinstance(func, FunctionTypes):
183 # for classes where instance is True we end up here too
184 try:
185 func = func.__call__
186 except AttributeError:
187 return
188
Michael Foordc8dddba2012-04-21 18:39:34 +0100189 if inPy3k:
190 try:
191 argspec = inspect.getfullargspec(func)
192 except TypeError:
193 # C function / method, possibly inherited object().__init__
194 return
195 regargs, varargs, varkw, defaults, kwonly, kwonlydef, ann = argspec
196 else:
197 try:
198 regargs, varargs, varkwargs, defaults = inspect.getargspec(func)
199 except TypeError:
200 # C function / method, possibly inherited object().__init__
201 return
Michael Foord1e68bec2012-03-03 22:24:30 +0000202
203 # instance methods and classmethods need to lose the self argument
204 if getattr(func, self, None) is not None:
205 regargs = regargs[1:]
206 if skipfirst:
207 # this condition and the above one are never both True - why?
208 regargs = regargs[1:]
209
Michael Foordc8dddba2012-04-21 18:39:34 +0100210 if inPy3k:
211 signature = inspect.formatargspec(
212 regargs, varargs, varkw, defaults,
213 kwonly, kwonlydef, ann, formatvalue=lambda value: "")
214 else:
215 signature = inspect.formatargspec(
216 regargs, varargs, varkwargs, defaults,
217 formatvalue=lambda value: "")
Michael Foord1e68bec2012-03-03 22:24:30 +0000218 return signature[1:-1], func
219
220
221def _check_signature(func, mock, skipfirst, instance=False):
222 if not _callable(func):
223 return
224
Michael Foorda9a8bb92012-03-13 14:39:59 -0700225 result = _getsignature(func, skipfirst, instance)
Michael Foord1e68bec2012-03-03 22:24:30 +0000226 if result is None:
227 return
228 signature, func = result
229
230 # can't use self because "self" is common as an argument name
231 # unfortunately even not in the first place
232 src = "lambda _mock_self, %s: None" % signature
233 checksig = eval(src, {})
234 _copy_func_details(func, checksig)
235 type(mock)._mock_check_sig = checksig
236
237
238def _copy_func_details(func, funcopy):
239 funcopy.__name__ = func.__name__
240 funcopy.__doc__ = func.__doc__
Robert Collins06587a52015-07-07 12:08:57 +1200241 try:
242 funcopy.__text_signature__ = func.__text_signature__
243 except AttributeError:
244 pass
245 # we explicitly don't copy func.__dict__ into this copy as it would
246 # expose original attributes that should be mocked
247 try:
248 funcopy.__module__ = func.__module__
249 except AttributeError:
250 pass
251 try:
252 funcopy.__defaults__ = func.__defaults__
253 except AttributeError:
254 pass
255 try:
256 funcopy.__kwdefaults__ = func.__kwdefaults__
257 except AttributeError:
258 pass
Michael Foord1e68bec2012-03-03 22:24:30 +0000259 if not inPy3k:
260 funcopy.func_defaults = func.func_defaults
261 return
Michael Foord1e68bec2012-03-03 22:24:30 +0000262
263
264def _callable(obj):
265 if isinstance(obj, ClassTypes):
266 return True
267 if getattr(obj, '__call__', None) is not None:
268 return True
269 return False
270
271
272def _is_list(obj):
273 # checks for list or tuples
274 # XXXX badly named!
275 return type(obj) in (list, tuple)
276
277
278def _instance_callable(obj):
279 """Given an object, return True if the object is callable.
280 For classes, return True if instances would be callable."""
281 if not isinstance(obj, ClassTypes):
282 # already an instance
283 return getattr(obj, '__call__', None) is not None
284
285 klass = obj
286 # uses __bases__ instead of __mro__ so that we work with old style classes
287 if klass.__dict__.get('__call__') is not None:
288 return True
289
290 for base in klass.__bases__:
291 if _instance_callable(base):
292 return True
293 return False
294
295
296def _set_signature(mock, original, instance=False):
297 # creates a function with signature (*args, **kwargs) that delegates to a
298 # mock. It still does signature checking by calling a lambda with the same
Michael Foorda9a8bb92012-03-13 14:39:59 -0700299 # signature as the original.
Michael Foord1e68bec2012-03-03 22:24:30 +0000300 if not _callable(original):
301 return
302
303 skipfirst = isinstance(original, ClassTypes)
Michael Foorda9a8bb92012-03-13 14:39:59 -0700304 result = _getsignature(original, skipfirst, instance)
Michael Foord1e68bec2012-03-03 22:24:30 +0000305 if result is None:
306 # was a C function (e.g. object().__init__ ) that can't be mocked
307 return
308
309 signature, func = result
310
311 src = "lambda %s: None" % signature
Michael Foordab5fef72012-03-15 19:16:12 -0700312 checksig = eval(src, {})
Michael Foord1e68bec2012-03-03 22:24:30 +0000313 _copy_func_details(func, checksig)
314
315 name = original.__name__
316 if not _isidentifier(name):
317 name = 'funcopy'
Michael Foordab5fef72012-03-15 19:16:12 -0700318 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord1e68bec2012-03-03 22:24:30 +0000319 src = """def %s(*args, **kwargs):
Michael Foordab5fef72012-03-15 19:16:12 -0700320 _checksig_(*args, **kwargs)
Michael Foord1e68bec2012-03-03 22:24:30 +0000321 return mock(*args, **kwargs)""" % name
322 exec (src, context)
323 funcopy = context[name]
324 _setup_func(funcopy, mock)
325 return funcopy
326
327
Michael Foord1e68bec2012-03-03 22:24:30 +0000328def _setup_func(funcopy, mock):
329 funcopy.mock = mock
330
331 # can't use isinstance with mocks
332 if not _is_instance_mock(mock):
333 return
334
335 def assert_called_with(*args, **kwargs):
336 return mock.assert_called_with(*args, **kwargs)
337 def assert_called_once_with(*args, **kwargs):
338 return mock.assert_called_once_with(*args, **kwargs)
339 def assert_has_calls(*args, **kwargs):
340 return mock.assert_has_calls(*args, **kwargs)
341 def assert_any_call(*args, **kwargs):
342 return mock.assert_any_call(*args, **kwargs)
343 def reset_mock():
344 funcopy.method_calls = _CallList()
345 funcopy.mock_calls = _CallList()
346 mock.reset_mock()
347 ret = funcopy.return_value
348 if _is_instance_mock(ret) and not ret is mock:
349 ret.reset_mock()
350
351 funcopy.called = False
352 funcopy.call_count = 0
353 funcopy.call_args = None
354 funcopy.call_args_list = _CallList()
355 funcopy.method_calls = _CallList()
356 funcopy.mock_calls = _CallList()
357
358 funcopy.return_value = mock.return_value
359 funcopy.side_effect = mock.side_effect
360 funcopy._mock_children = mock._mock_children
361
362 funcopy.assert_called_with = assert_called_with
363 funcopy.assert_called_once_with = assert_called_once_with
364 funcopy.assert_has_calls = assert_has_calls
365 funcopy.assert_any_call = assert_any_call
366 funcopy.reset_mock = reset_mock
367
Michael Foordab5fef72012-03-15 19:16:12 -0700368 mock._mock_delegate = funcopy
Michael Foord1e68bec2012-03-03 22:24:30 +0000369
370
371def _is_magic(name):
372 return '__%s__' % name[2:-2] == name
373
374
375class _SentinelObject(object):
376 "A unique, named, sentinel object."
377 def __init__(self, name):
378 self.name = name
379
380 def __repr__(self):
381 return 'sentinel.%s' % self.name
382
383
384class _Sentinel(object):
385 """Access attributes to return a named object, usable as a sentinel."""
386 def __init__(self):
387 self._sentinels = {}
388
389 def __getattr__(self, name):
390 if name == '__bases__':
391 # Without this help(mock) raises an exception
392 raise AttributeError
393 return self._sentinels.setdefault(name, _SentinelObject(name))
394
395
396sentinel = _Sentinel()
397
398DEFAULT = sentinel.DEFAULT
Michael Foordafc98d42012-03-13 16:38:50 -0700399_missing = sentinel.MISSING
400_deleted = sentinel.DELETED
Michael Foord1e68bec2012-03-03 22:24:30 +0000401
402
403class OldStyleClass:
404 pass
405ClassType = type(OldStyleClass)
406
407
408def _copy(value):
409 if type(value) in (dict, list, tuple, set):
410 return type(value)(value)
411 return value
412
413
414ClassTypes = (type,)
415if not inPy3k:
416 ClassTypes = (type, ClassType)
417
418_allowed_names = set(
419 [
420 'return_value', '_mock_return_value', 'side_effect',
421 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
422 '_mock_name', '_mock_new_name'
423 ]
424)
425
426
Michael Foordab5fef72012-03-15 19:16:12 -0700427def _delegating_property(name):
Michael Foord1e68bec2012-03-03 22:24:30 +0000428 _allowed_names.add(name)
429 _the_name = '_mock_' + name
430 def _get(self, name=name, _the_name=_the_name):
Michael Foordab5fef72012-03-15 19:16:12 -0700431 sig = self._mock_delegate
Michael Foord1e68bec2012-03-03 22:24:30 +0000432 if sig is None:
433 return getattr(self, _the_name)
434 return getattr(sig, name)
435 def _set(self, value, name=name, _the_name=_the_name):
Michael Foordab5fef72012-03-15 19:16:12 -0700436 sig = self._mock_delegate
Michael Foord1e68bec2012-03-03 22:24:30 +0000437 if sig is None:
438 self.__dict__[_the_name] = value
439 else:
440 setattr(sig, name, value)
441
442 return property(_get, _set)
443
444
445
446class _CallList(list):
447
448 def __contains__(self, value):
449 if not isinstance(value, list):
450 return list.__contains__(self, value)
451 len_value = len(value)
452 len_self = len(self)
453 if len_value > len_self:
454 return False
455
456 for i in range(0, len_self - len_value + 1):
457 sub_list = self[i:i+len_value]
458 if sub_list == value:
459 return True
460 return False
461
462 def __repr__(self):
463 return pprint.pformat(list(self))
464
465
466def _check_and_set_parent(parent, value, name, new_name):
467 if not _is_instance_mock(value):
468 return False
469 if ((value._mock_name or value._mock_new_name) or
470 (value._mock_parent is not None) or
471 (value._mock_new_parent is not None)):
472 return False
473
474 _parent = parent
475 while _parent is not None:
476 # setting a mock (value) as a child or return value of itself
477 # should not modify the mock
478 if _parent is value:
479 return False
480 _parent = _parent._mock_new_parent
481
482 if new_name:
483 value._mock_new_parent = parent
484 value._mock_new_name = new_name
485 if name:
486 value._mock_parent = parent
487 value._mock_name = name
488 return True
489
490
491
492class Base(object):
493 _mock_return_value = DEFAULT
494 _mock_side_effect = None
495 def __init__(self, *args, **kwargs):
496 pass
497
498
499
500class NonCallableMock(Base):
501 """A non-callable version of `Mock`"""
502
503 def __new__(cls, *args, **kw):
504 # every instance has its own class
505 # so we can create magic methods on the
506 # class without stomping on other mocks
507 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
508 instance = object.__new__(new)
509 return instance
510
511
512 def __init__(
513 self, spec=None, wraps=None, name=None, spec_set=None,
514 parent=None, _spec_state=None, _new_name='', _new_parent=None,
515 **kwargs
516 ):
517 if _new_parent is None:
518 _new_parent = parent
519
520 __dict__ = self.__dict__
521 __dict__['_mock_parent'] = parent
522 __dict__['_mock_name'] = name
523 __dict__['_mock_new_name'] = _new_name
524 __dict__['_mock_new_parent'] = _new_parent
525
526 if spec_set is not None:
527 spec = spec_set
528 spec_set = True
529
530 self._mock_add_spec(spec, spec_set)
531
532 __dict__['_mock_children'] = {}
533 __dict__['_mock_wraps'] = wraps
Michael Foordab5fef72012-03-15 19:16:12 -0700534 __dict__['_mock_delegate'] = None
Michael Foord1e68bec2012-03-03 22:24:30 +0000535
536 __dict__['_mock_called'] = False
537 __dict__['_mock_call_args'] = None
538 __dict__['_mock_call_count'] = 0
539 __dict__['_mock_call_args_list'] = _CallList()
540 __dict__['_mock_mock_calls'] = _CallList()
541
542 __dict__['method_calls'] = _CallList()
543
544 if kwargs:
545 self.configure_mock(**kwargs)
546
547 _super(NonCallableMock, self).__init__(
548 spec, wraps, name, spec_set, parent,
549 _spec_state
550 )
551
552
553 def attach_mock(self, mock, attribute):
554 """
555 Attach a mock as an attribute of this one, replacing its name and
556 parent. Calls to the attached mock will be recorded in the
557 `method_calls` and `mock_calls` attributes of this one."""
558 mock._mock_parent = None
559 mock._mock_new_parent = None
560 mock._mock_name = ''
561 mock._mock_new_name = None
562
563 setattr(self, attribute, mock)
564
565
566 def mock_add_spec(self, spec, spec_set=False):
567 """Add a spec to a mock. `spec` can either be an object or a
568 list of strings. Only attributes on the `spec` can be fetched as
569 attributes from the mock.
570
571 If `spec_set` is True then only attributes on the spec can be set."""
572 self._mock_add_spec(spec, spec_set)
573
574
575 def _mock_add_spec(self, spec, spec_set):
576 _spec_class = None
577
578 if spec is not None and not _is_list(spec):
579 if isinstance(spec, ClassTypes):
580 _spec_class = spec
581 else:
582 _spec_class = _get_class(spec)
583
584 spec = dir(spec)
585
586 __dict__ = self.__dict__
587 __dict__['_spec_class'] = _spec_class
588 __dict__['_spec_set'] = spec_set
589 __dict__['_mock_methods'] = spec
590
591
592 def __get_return_value(self):
593 ret = self._mock_return_value
Michael Foordab5fef72012-03-15 19:16:12 -0700594 if self._mock_delegate is not None:
595 ret = self._mock_delegate.return_value
Michael Foord1e68bec2012-03-03 22:24:30 +0000596
597 if ret is DEFAULT:
598 ret = self._get_child_mock(
599 _new_parent=self, _new_name='()'
600 )
601 self.return_value = ret
602 return ret
603
604
605 def __set_return_value(self, value):
Michael Foordab5fef72012-03-15 19:16:12 -0700606 if self._mock_delegate is not None:
607 self._mock_delegate.return_value = value
Michael Foord1e68bec2012-03-03 22:24:30 +0000608 else:
609 self._mock_return_value = value
610 _check_and_set_parent(self, value, None, '()')
611
612 __return_value_doc = "The value to be returned when the mock is called."
613 return_value = property(__get_return_value, __set_return_value,
614 __return_value_doc)
615
616
617 @property
618 def __class__(self):
619 if self._spec_class is None:
620 return type(self)
621 return self._spec_class
622
Michael Foordab5fef72012-03-15 19:16:12 -0700623 called = _delegating_property('called')
624 call_count = _delegating_property('call_count')
625 call_args = _delegating_property('call_args')
626 call_args_list = _delegating_property('call_args_list')
627 mock_calls = _delegating_property('mock_calls')
Michael Foord1e68bec2012-03-03 22:24:30 +0000628
629
630 def __get_side_effect(self):
Michael Foordab5fef72012-03-15 19:16:12 -0700631 sig = self._mock_delegate
Michael Foord1e68bec2012-03-03 22:24:30 +0000632 if sig is None:
633 return self._mock_side_effect
634 return sig.side_effect
635
636 def __set_side_effect(self, value):
637 value = _try_iter(value)
Michael Foordab5fef72012-03-15 19:16:12 -0700638 sig = self._mock_delegate
Michael Foord1e68bec2012-03-03 22:24:30 +0000639 if sig is None:
640 self._mock_side_effect = value
641 else:
642 sig.side_effect = value
643
644 side_effect = property(__get_side_effect, __set_side_effect)
645
646
647 def reset_mock(self):
648 "Restore the mock object to its initial state."
649 self.called = False
650 self.call_args = None
651 self.call_count = 0
652 self.mock_calls = _CallList()
653 self.call_args_list = _CallList()
654 self.method_calls = _CallList()
655
656 for child in self._mock_children.values():
Michael Foord9e6246d2012-06-09 15:45:05 +0100657 if isinstance(child, _SpecState):
658 continue
Michael Foord1e68bec2012-03-03 22:24:30 +0000659 child.reset_mock()
660
661 ret = self._mock_return_value
662 if _is_instance_mock(ret) and ret is not self:
663 ret.reset_mock()
664
665
666 def configure_mock(self, **kwargs):
667 """Set attributes on the mock through keyword arguments.
668
669 Attributes plus return values and side effects can be set on child
670 mocks using standard dot notation and unpacking a dictionary in the
671 method call:
672
673 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
674 >>> mock.configure_mock(**attrs)"""
675 for arg, val in sorted(kwargs.items(),
676 # we sort on the number of dots so that
677 # attributes are set before we set attributes on
678 # attributes
679 key=lambda entry: entry[0].count('.')):
680 args = arg.split('.')
681 final = args.pop()
682 obj = self
683 for entry in args:
684 obj = getattr(obj, entry)
685 setattr(obj, final, val)
686
687
688 def __getattr__(self, name):
689 if name == '_mock_methods':
690 raise AttributeError(name)
691 elif self._mock_methods is not None:
692 if name not in self._mock_methods or name in _all_magics:
693 raise AttributeError("Mock object has no attribute %r" % name)
694 elif _is_magic(name):
695 raise AttributeError(name)
696
697 result = self._mock_children.get(name)
Michael Foordafc98d42012-03-13 16:38:50 -0700698 if result is _deleted:
699 raise AttributeError(name)
700 elif result is None:
Michael Foord1e68bec2012-03-03 22:24:30 +0000701 wraps = None
702 if self._mock_wraps is not None:
703 # XXXX should we get the attribute without triggering code
704 # execution?
705 wraps = getattr(self._mock_wraps, name)
706
707 result = self._get_child_mock(
708 parent=self, name=name, wraps=wraps, _new_name=name,
709 _new_parent=self
710 )
711 self._mock_children[name] = result
712
713 elif isinstance(result, _SpecState):
714 result = create_autospec(
715 result.spec, result.spec_set, result.instance,
716 result.parent, result.name
717 )
718 self._mock_children[name] = result
719
720 return result
721
722
723 def __repr__(self):
724 _name_list = [self._mock_new_name]
725 _parent = self._mock_new_parent
726 last = self
727
728 dot = '.'
729 if _name_list == ['()']:
730 dot = ''
731 seen = set()
732 while _parent is not None:
733 last = _parent
734
735 _name_list.append(_parent._mock_new_name + dot)
736 dot = '.'
737 if _parent._mock_new_name == '()':
738 dot = ''
739
740 _parent = _parent._mock_new_parent
741
742 # use ids here so as not to call __hash__ on the mocks
743 if id(_parent) in seen:
744 break
745 seen.add(id(_parent))
746
747 _name_list = list(reversed(_name_list))
748 _first = last._mock_name or 'mock'
749 if len(_name_list) > 1:
750 if _name_list[1] not in ('()', '().'):
751 _first += '.'
752 _name_list[0] = _first
753 name = ''.join(_name_list)
754
755 name_string = ''
756 if name not in ('mock', 'mock.'):
757 name_string = ' name=%r' % name
758
759 spec_string = ''
760 if self._spec_class is not None:
761 spec_string = ' spec=%r'
762 if self._spec_set:
763 spec_string = ' spec_set=%r'
764 spec_string = spec_string % self._spec_class.__name__
765 return "<%s%s%s id='%s'>" % (
766 type(self).__name__,
767 name_string,
768 spec_string,
769 id(self)
770 )
771
772
773 def __dir__(self):
Michael Foordef502442013-03-18 12:05:39 -0700774 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord1e68bec2012-03-03 22:24:30 +0000775 extras = self._mock_methods or []
776 from_type = dir(type(self))
777 from_dict = list(self.__dict__)
778
779 if FILTER_DIR:
780 from_type = [e for e in from_type if not e.startswith('_')]
781 from_dict = [e for e in from_dict if not e.startswith('_') or
782 _is_magic(e)]
783 return sorted(set(extras + from_type + from_dict +
784 list(self._mock_children)))
785
786
787 def __setattr__(self, name, value):
788 if name in _allowed_names:
789 # property setters go through here
790 return object.__setattr__(self, name, value)
791 elif (self._spec_set and self._mock_methods is not None and
792 name not in self._mock_methods and
793 name not in self.__dict__):
794 raise AttributeError("Mock object has no attribute '%s'" % name)
795 elif name in _unsupported_magics:
796 msg = 'Attempting to set unsupported magic method %r.' % name
797 raise AttributeError(msg)
798 elif name in _all_magics:
799 if self._mock_methods is not None and name not in self._mock_methods:
800 raise AttributeError("Mock object has no attribute '%s'" % name)
801
802 if not _is_instance_mock(value):
803 setattr(type(self), name, _get_method(name, value))
804 original = value
Michael Foorda9a8bb92012-03-13 14:39:59 -0700805 value = lambda *args, **kw: original(self, *args, **kw)
Michael Foord1e68bec2012-03-03 22:24:30 +0000806 else:
807 # only set _new_name and not name so that mock_calls is tracked
808 # but not method calls
809 _check_and_set_parent(self, value, None, name)
810 setattr(type(self), name, value)
Michael Foordb74d84f2012-06-09 15:49:37 +0100811 self._mock_children[name] = value
Michael Foord8f1cda02012-03-13 23:15:40 -0700812 elif name == '__class__':
813 self._spec_class = value
814 return
Michael Foord1e68bec2012-03-03 22:24:30 +0000815 else:
816 if _check_and_set_parent(self, value, name, name):
817 self._mock_children[name] = value
818 return object.__setattr__(self, name, value)
819
820
821 def __delattr__(self, name):
822 if name in _all_magics and name in type(self).__dict__:
823 delattr(type(self), name)
824 if name not in self.__dict__:
825 # for magic methods that are still MagicProxy objects and
826 # not set on the instance itself
827 return
828
Michael Foordafc98d42012-03-13 16:38:50 -0700829 if name in self.__dict__:
830 object.__delattr__(self, name)
831
832 obj = self._mock_children.get(name, _missing)
833 if obj is _deleted:
834 raise AttributeError(name)
835 if obj is not _missing:
836 del self._mock_children[name]
837 self._mock_children[name] = _deleted
838
Michael Foord1e68bec2012-03-03 22:24:30 +0000839
840
841 def _format_mock_call_signature(self, args, kwargs):
842 name = self._mock_name or 'mock'
843 return _format_call_signature(name, args, kwargs)
844
845
846 def _format_mock_failure_message(self, args, kwargs):
847 message = 'Expected call: %s\nActual call: %s'
848 expected_string = self._format_mock_call_signature(args, kwargs)
849 call_args = self.call_args
850 if len(call_args) == 3:
851 call_args = call_args[1:]
852 actual_string = self._format_mock_call_signature(*call_args)
853 return message % (expected_string, actual_string)
854
855
856 def assert_called_with(_mock_self, *args, **kwargs):
857 """assert that the mock was called with the specified arguments.
858
859 Raises an AssertionError if the args and keyword args passed in are
860 different to the last call to the mock."""
861 self = _mock_self
862 if self.call_args is None:
863 expected = self._format_mock_call_signature(args, kwargs)
864 raise AssertionError('Expected call: %s\nNot called' % (expected,))
865
866 if self.call_args != (args, kwargs):
867 msg = self._format_mock_failure_message(args, kwargs)
868 raise AssertionError(msg)
869
870
871 def assert_called_once_with(_mock_self, *args, **kwargs):
872 """assert that the mock was called exactly once and with the specified
873 arguments."""
874 self = _mock_self
875 if not self.call_count == 1:
876 msg = ("Expected to be called once. Called %s times." %
877 self.call_count)
878 raise AssertionError(msg)
879 return self.assert_called_with(*args, **kwargs)
880
881
882 def assert_has_calls(self, calls, any_order=False):
883 """assert the mock has been called with the specified calls.
884 The `mock_calls` list is checked for the calls.
885
886 If `any_order` is False (the default) then the calls must be
887 sequential. There can be extra calls before or after the
888 specified calls.
889
890 If `any_order` is True then the calls can be in any order, but
891 they must all appear in `mock_calls`."""
892 if not any_order:
893 if calls not in self.mock_calls:
894 raise AssertionError(
895 'Calls not found.\nExpected: %r\n'
896 'Actual: %r' % (calls, self.mock_calls)
897 )
898 return
899
900 all_calls = list(self.mock_calls)
901
902 not_found = []
903 for kall in calls:
904 try:
905 all_calls.remove(kall)
906 except ValueError:
907 not_found.append(kall)
908 if not_found:
909 raise AssertionError(
910 '%r not all found in call list' % (tuple(not_found),)
911 )
912
913
914 def assert_any_call(self, *args, **kwargs):
915 """assert the mock has been called with the specified arguments.
916
917 The assert passes if the mock has *ever* been called, unlike
918 `assert_called_with` and `assert_called_once_with` that only pass if
919 the call is the most recent one."""
920 kall = call(*args, **kwargs)
921 if kall not in self.call_args_list:
922 expected_string = self._format_mock_call_signature(args, kwargs)
923 raise AssertionError(
924 '%s call not found' % expected_string
925 )
926
927
928 def _get_child_mock(self, **kw):
929 """Create the child mocks for attributes and return value.
930 By default child mocks will be the same type as the parent.
931 Subclasses of Mock may want to override this to customize the way
932 child mocks are made.
933
934 For non-callable mocks the callable variant will be used (rather than
935 any custom subclass)."""
936 _type = type(self)
937 if not issubclass(_type, CallableMixin):
938 if issubclass(_type, NonCallableMagicMock):
939 klass = MagicMock
940 elif issubclass(_type, NonCallableMock) :
941 klass = Mock
942 else:
943 klass = _type.__mro__[1]
944 return klass(**kw)
945
946
947
948def _try_iter(obj):
949 if obj is None:
950 return obj
951 if _is_exception(obj):
952 return obj
953 if _callable(obj):
954 return obj
955 try:
956 return iter(obj)
957 except TypeError:
958 # XXXX backwards compatibility
959 # but this will blow up on first call - so maybe we should fail early?
960 return obj
961
962
963
964class CallableMixin(Base):
965
966 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
967 wraps=None, name=None, spec_set=None, parent=None,
968 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
969 self.__dict__['_mock_return_value'] = return_value
970
971 _super(CallableMixin, self).__init__(
972 spec, wraps, name, spec_set, parent,
973 _spec_state, _new_name, _new_parent, **kwargs
974 )
975
976 self.side_effect = side_effect
977
978
979 def _mock_check_sig(self, *args, **kwargs):
980 # stub method that can be replaced with one with a specific signature
981 pass
982
983
984 def __call__(_mock_self, *args, **kwargs):
985 # can't use self in-case a function / method we are mocking uses self
986 # in the signature
987 _mock_self._mock_check_sig(*args, **kwargs)
988 return _mock_self._mock_call(*args, **kwargs)
989
990
991 def _mock_call(_mock_self, *args, **kwargs):
992 self = _mock_self
993 self.called = True
994 self.call_count += 1
995 self.call_args = _Call((args, kwargs), two=True)
996 self.call_args_list.append(_Call((args, kwargs), two=True))
997
998 _new_name = self._mock_new_name
999 _new_parent = self._mock_new_parent
1000 self.mock_calls.append(_Call(('', args, kwargs)))
1001
1002 seen = set()
1003 skip_next_dot = _new_name == '()'
1004 do_method_calls = self._mock_parent is not None
1005 name = self._mock_name
1006 while _new_parent is not None:
1007 this_mock_call = _Call((_new_name, args, kwargs))
1008 if _new_parent._mock_new_name:
1009 dot = '.'
1010 if skip_next_dot:
1011 dot = ''
1012
1013 skip_next_dot = False
1014 if _new_parent._mock_new_name == '()':
1015 skip_next_dot = True
1016
1017 _new_name = _new_parent._mock_new_name + dot + _new_name
1018
1019 if do_method_calls:
1020 if _new_name == name:
1021 this_method_call = this_mock_call
1022 else:
1023 this_method_call = _Call((name, args, kwargs))
1024 _new_parent.method_calls.append(this_method_call)
1025
1026 do_method_calls = _new_parent._mock_parent is not None
1027 if do_method_calls:
1028 name = _new_parent._mock_name + '.' + name
1029
1030 _new_parent.mock_calls.append(this_mock_call)
1031 _new_parent = _new_parent._mock_new_parent
1032
1033 # use ids here so as not to call __hash__ on the mocks
1034 _new_parent_id = id(_new_parent)
1035 if _new_parent_id in seen:
1036 break
1037 seen.add(_new_parent_id)
1038
1039 ret_val = DEFAULT
1040 effect = self.side_effect
1041 if effect is not None:
1042 if _is_exception(effect):
1043 raise effect
1044
1045 if not _callable(effect):
Michael Foord70b4ef62012-04-21 01:44:18 +01001046 result = next(effect)
1047 if _is_exception(result):
1048 raise result
1049 return result
Michael Foord1e68bec2012-03-03 22:24:30 +00001050
1051 ret_val = effect(*args, **kwargs)
1052 if ret_val is DEFAULT:
1053 ret_val = self.return_value
1054
1055 if (self._mock_wraps is not None and
1056 self._mock_return_value is DEFAULT):
1057 return self._mock_wraps(*args, **kwargs)
1058 if ret_val is DEFAULT:
1059 ret_val = self.return_value
1060 return ret_val
1061
1062
1063
1064class Mock(CallableMixin, NonCallableMock):
1065 """
1066 Create a new `Mock` object. `Mock` takes several optional arguments
1067 that specify the behaviour of the Mock object:
1068
1069 * `spec`: This can be either a list of strings or an existing object (a
1070 class or instance) that acts as the specification for the mock object. If
1071 you pass in an object then a list of strings is formed by calling dir on
1072 the object (excluding unsupported magic attributes and methods). Accessing
1073 any attribute not in this list will raise an `AttributeError`.
1074
1075 If `spec` is an object (rather than a list of strings) then
1076 `mock.__class__` returns the class of the spec object. This allows mocks
1077 to pass `isinstance` tests.
1078
1079 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1080 or get an attribute on the mock that isn't on the object passed as
1081 `spec_set` will raise an `AttributeError`.
1082
1083 * `side_effect`: A function to be called whenever the Mock is called. See
1084 the `side_effect` attribute. Useful for raising exceptions or
1085 dynamically changing return values. The function is called with the same
1086 arguments as the mock, and unless it returns `DEFAULT`, the return
1087 value of this function is used as the return value.
1088
1089 Alternatively `side_effect` can be an exception class or instance. In
1090 this case the exception will be raised when the mock is called.
1091
1092 If `side_effect` is an iterable then each call to the mock will return
Michael Foord70b4ef62012-04-21 01:44:18 +01001093 the next value from the iterable. If any of the members of the iterable
1094 are exceptions they will be raised instead of returned.
Michael Foord1e68bec2012-03-03 22:24:30 +00001095
1096 * `return_value`: The value returned when the mock is called. By default
1097 this is a new Mock (created on first access). See the
1098 `return_value` attribute.
1099
Michael Foord594229a2012-04-13 20:50:36 +01001100 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1101 calling the Mock will pass the call through to the wrapped object
1102 (returning the real result). Attribute access on the mock will return a
1103 Mock object that wraps the corresponding attribute of the wrapped object
1104 (so attempting to access an attribute that doesn't exist will raise an
1105 `AttributeError`).
Michael Foord1e68bec2012-03-03 22:24:30 +00001106
1107 If the mock has an explicit `return_value` set then calls are not passed
1108 to the wrapped object and the `return_value` is returned instead.
1109
1110 * `name`: If the mock has a name then it will be used in the repr of the
1111 mock. This can be useful for debugging. The name is propagated to child
1112 mocks.
1113
1114 Mocks can also be called with arbitrary keyword arguments. These will be
1115 used to set attributes on the mock after it is created.
1116 """
1117
1118
1119
1120def _dot_lookup(thing, comp, import_path):
1121 try:
1122 return getattr(thing, comp)
1123 except AttributeError:
1124 __import__(import_path)
1125 return getattr(thing, comp)
1126
1127
1128def _importer(target):
1129 components = target.split('.')
1130 import_path = components.pop(0)
1131 thing = __import__(import_path)
1132
1133 for comp in components:
1134 import_path += ".%s" % comp
1135 thing = _dot_lookup(thing, comp, import_path)
1136 return thing
1137
1138
1139def _is_started(patcher):
1140 # XXXX horrible
1141 return hasattr(patcher, 'is_local')
1142
1143
1144class _patch(object):
1145
1146 attribute_name = None
Michael Foord99dc7a52012-06-10 20:29:40 +01001147 _active_patches = set()
Michael Foord1e68bec2012-03-03 22:24:30 +00001148
1149 def __init__(
1150 self, getter, attribute, new, spec, create,
Michael Foorda9a8bb92012-03-13 14:39:59 -07001151 spec_set, autospec, new_callable, kwargs
Michael Foord1e68bec2012-03-03 22:24:30 +00001152 ):
1153 if new_callable is not None:
1154 if new is not DEFAULT:
1155 raise ValueError(
1156 "Cannot use 'new' and 'new_callable' together"
1157 )
Michael Foord08f47552012-03-25 17:39:04 +01001158 if autospec is not None:
Michael Foord1e68bec2012-03-03 22:24:30 +00001159 raise ValueError(
1160 "Cannot use 'autospec' and 'new_callable' together"
1161 )
1162
1163 self.getter = getter
1164 self.attribute = attribute
1165 self.new = new
1166 self.new_callable = new_callable
1167 self.spec = spec
1168 self.create = create
1169 self.has_local = False
Michael Foord1e68bec2012-03-03 22:24:30 +00001170 self.spec_set = spec_set
1171 self.autospec = autospec
1172 self.kwargs = kwargs
1173 self.additional_patchers = []
1174
1175
1176 def copy(self):
1177 patcher = _patch(
1178 self.getter, self.attribute, self.new, self.spec,
Michael Foorda9a8bb92012-03-13 14:39:59 -07001179 self.create, self.spec_set,
Michael Foord1e68bec2012-03-03 22:24:30 +00001180 self.autospec, self.new_callable, self.kwargs
1181 )
1182 patcher.attribute_name = self.attribute_name
1183 patcher.additional_patchers = [
1184 p.copy() for p in self.additional_patchers
1185 ]
1186 return patcher
1187
1188
1189 def __call__(self, func):
1190 if isinstance(func, ClassTypes):
1191 return self.decorate_class(func)
1192 return self.decorate_callable(func)
1193
1194
1195 def decorate_class(self, klass):
1196 for attr in dir(klass):
1197 if not attr.startswith(patch.TEST_PREFIX):
1198 continue
1199
1200 attr_value = getattr(klass, attr)
1201 if not hasattr(attr_value, "__call__"):
1202 continue
1203
1204 patcher = self.copy()
1205 setattr(klass, attr, patcher(attr_value))
1206 return klass
1207
1208
1209 def decorate_callable(self, func):
1210 if hasattr(func, 'patchings'):
1211 func.patchings.append(self)
1212 return func
1213
1214 @wraps(func)
1215 def patched(*args, **keywargs):
1216 # don't use a with here (backwards compatability with Python 2.4)
1217 extra_args = []
1218 entered_patchers = []
1219
1220 # can't use try...except...finally because of Python 2.4
1221 # compatibility
Kumar McMillan5b522f02012-03-14 23:28:31 -05001222 exc_info = tuple()
Michael Foord1e68bec2012-03-03 22:24:30 +00001223 try:
1224 try:
1225 for patching in patched.patchings:
1226 arg = patching.__enter__()
1227 entered_patchers.append(patching)
1228 if patching.attribute_name is not None:
1229 keywargs.update(arg)
1230 elif patching.new is DEFAULT:
1231 extra_args.append(arg)
1232
1233 args += tuple(extra_args)
1234 return func(*args, **keywargs)
1235 except:
1236 if (patching not in entered_patchers and
1237 _is_started(patching)):
1238 # the patcher may have been started, but an exception
1239 # raised whilst entering one of its additional_patchers
1240 entered_patchers.append(patching)
Kumar McMillan8a184172012-03-14 23:38:04 -05001241 # Pass the exception to __exit__
Kumar McMillan5b522f02012-03-14 23:28:31 -05001242 exc_info = sys.exc_info()
Michael Foord1e68bec2012-03-03 22:24:30 +00001243 # re-raise the exception
1244 raise
1245 finally:
1246 for patching in reversed(entered_patchers):
Kumar McMillan5b522f02012-03-14 23:28:31 -05001247 patching.__exit__(*exc_info)
Michael Foord1e68bec2012-03-03 22:24:30 +00001248
1249 patched.patchings = [self]
1250 if hasattr(func, 'func_code'):
1251 # not in Python 3
1252 patched.compat_co_firstlineno = getattr(
1253 func, "compat_co_firstlineno",
1254 func.func_code.co_firstlineno
1255 )
1256 return patched
1257
1258
1259 def get_original(self):
1260 target = self.getter()
1261 name = self.attribute
1262
1263 original = DEFAULT
1264 local = False
1265
1266 try:
1267 original = target.__dict__[name]
1268 except (AttributeError, KeyError):
1269 original = getattr(target, name, DEFAULT)
1270 else:
1271 local = True
1272
1273 if not self.create and original is DEFAULT:
1274 raise AttributeError(
1275 "%s does not have the attribute %r" % (target, name)
1276 )
1277 return original, local
1278
1279
1280 def __enter__(self):
1281 """Perform the patch."""
1282 new, spec, spec_set = self.new, self.spec, self.spec_set
1283 autospec, kwargs = self.autospec, self.kwargs
1284 new_callable = self.new_callable
1285 self.target = self.getter()
1286
Michael Foord08f47552012-03-25 17:39:04 +01001287 # normalise False to None
1288 if spec is False:
1289 spec = None
1290 if spec_set is False:
1291 spec_set = None
1292 if autospec is False:
1293 autospec = None
1294
1295 if spec is not None and autospec is not None:
1296 raise TypeError("Can't specify spec and autospec")
1297 if ((spec is not None or autospec is not None) and
1298 spec_set not in (True, None)):
1299 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1300
Michael Foord1e68bec2012-03-03 22:24:30 +00001301 original, local = self.get_original()
1302
Michael Foord08f47552012-03-25 17:39:04 +01001303 if new is DEFAULT and autospec is None:
Michael Foord1e68bec2012-03-03 22:24:30 +00001304 inherit = False
Michael Foord08f47552012-03-25 17:39:04 +01001305 if spec is True:
Michael Foord1e68bec2012-03-03 22:24:30 +00001306 # set spec to the object we are replacing
1307 spec = original
Michael Foord08f47552012-03-25 17:39:04 +01001308 if spec_set is True:
1309 spec_set = original
1310 spec = None
1311 elif spec is not None:
1312 if spec_set is True:
1313 spec_set = spec
1314 spec = None
1315 elif spec_set is True:
1316 spec_set = original
Michael Foord1e68bec2012-03-03 22:24:30 +00001317
Michael Foord08f47552012-03-25 17:39:04 +01001318 if spec is not None or spec_set is not None:
Michael Foord669048d2012-03-25 02:00:31 +01001319 if original is DEFAULT:
1320 raise TypeError("Can't use 'spec' with create=True")
Michael Foord1e68bec2012-03-03 22:24:30 +00001321 if isinstance(original, ClassTypes):
1322 # If we're patching out a class and there is a spec
1323 inherit = True
1324
1325 Klass = MagicMock
1326 _kwargs = {}
1327 if new_callable is not None:
1328 Klass = new_callable
Michael Foord6e71f172012-03-25 19:35:52 +01001329 elif spec is not None or spec_set is not None:
Michael Foord5c241d52012-03-25 19:54:05 +01001330 this_spec = spec
1331 if spec_set is not None:
1332 this_spec = spec_set
1333 if _is_list(this_spec):
1334 not_callable = '__call__' not in this_spec
1335 else:
1336 not_callable = not _callable(this_spec)
1337 if not_callable:
Michael Foord1e68bec2012-03-03 22:24:30 +00001338 Klass = NonCallableMagicMock
1339
1340 if spec is not None:
1341 _kwargs['spec'] = spec
1342 if spec_set is not None:
1343 _kwargs['spec_set'] = spec_set
1344
1345 # add a name to mocks
1346 if (isinstance(Klass, type) and
1347 issubclass(Klass, NonCallableMock) and self.attribute):
1348 _kwargs['name'] = self.attribute
1349
1350 _kwargs.update(kwargs)
1351 new = Klass(**_kwargs)
1352
1353 if inherit and _is_instance_mock(new):
1354 # we can only tell if the instance should be callable if the
1355 # spec is not a list
Michael Foord08f47552012-03-25 17:39:04 +01001356 this_spec = spec
1357 if spec_set is not None:
1358 this_spec = spec_set
1359 if (not _is_list(this_spec) and not
1360 _instance_callable(this_spec)):
Michael Foord1e68bec2012-03-03 22:24:30 +00001361 Klass = NonCallableMagicMock
1362
1363 _kwargs.pop('name')
1364 new.return_value = Klass(_new_parent=new, _new_name='()',
1365 **_kwargs)
Michael Foord08f47552012-03-25 17:39:04 +01001366 elif autospec is not None:
Michael Foord1e68bec2012-03-03 22:24:30 +00001367 # spec is ignored, new *must* be default, spec_set is treated
1368 # as a boolean. Should we check spec is not None and that spec_set
Michael Foorda9a8bb92012-03-13 14:39:59 -07001369 # is a bool?
Michael Foord1e68bec2012-03-03 22:24:30 +00001370 if new is not DEFAULT:
1371 raise TypeError(
1372 "autospec creates the mock for you. Can't specify "
1373 "autospec and new."
1374 )
Michael Foord669048d2012-03-25 02:00:31 +01001375 if original is DEFAULT:
Michael Foord6e71f172012-03-25 19:35:52 +01001376 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord1e68bec2012-03-03 22:24:30 +00001377 spec_set = bool(spec_set)
1378 if autospec is True:
1379 autospec = original
1380
1381 new = create_autospec(autospec, spec_set=spec_set,
1382 _name=self.attribute, **kwargs)
1383 elif kwargs:
1384 # can't set keyword args when we aren't creating the mock
1385 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1386 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1387
1388 new_attr = new
Michael Foord1e68bec2012-03-03 22:24:30 +00001389
1390 self.temp_original = original
1391 self.is_local = local
1392 setattr(self.target, self.attribute, new_attr)
1393 if self.attribute_name is not None:
1394 extra_args = {}
1395 if self.new is DEFAULT:
1396 extra_args[self.attribute_name] = new
1397 for patching in self.additional_patchers:
1398 arg = patching.__enter__()
1399 if patching.new is DEFAULT:
1400 extra_args.update(arg)
1401 return extra_args
1402
1403 return new
1404
1405
Michael Foord669048d2012-03-25 02:00:31 +01001406 def __exit__(self, *exc_info):
Michael Foord1e68bec2012-03-03 22:24:30 +00001407 """Undo the patch."""
1408 if not _is_started(self):
1409 raise RuntimeError('stop called on unstarted patcher')
1410
1411 if self.is_local and self.temp_original is not DEFAULT:
1412 setattr(self.target, self.attribute, self.temp_original)
1413 else:
1414 delattr(self.target, self.attribute)
1415 if not self.create and not hasattr(self.target, self.attribute):
1416 # needed for proxy objects like django settings
1417 setattr(self.target, self.attribute, self.temp_original)
1418
1419 del self.temp_original
1420 del self.is_local
1421 del self.target
1422 for patcher in reversed(self.additional_patchers):
1423 if _is_started(patcher):
Michael Foord669048d2012-03-25 02:00:31 +01001424 patcher.__exit__(*exc_info)
Michael Foord1e68bec2012-03-03 22:24:30 +00001425
Michael Foord99dc7a52012-06-10 20:29:40 +01001426
1427 def start(self):
1428 """Activate a patch, returning any created mock."""
1429 result = self.__enter__()
1430 self._active_patches.add(self)
1431 return result
1432
1433
1434 def stop(self):
1435 """Stop an active patch."""
1436 self._active_patches.discard(self)
1437 return self.__exit__()
Michael Foord1e68bec2012-03-03 22:24:30 +00001438
1439
1440
1441def _get_target(target):
1442 try:
1443 target, attribute = target.rsplit('.', 1)
1444 except (TypeError, ValueError):
1445 raise TypeError("Need a valid target to patch. You supplied: %r" %
1446 (target,))
1447 getter = lambda: _importer(target)
1448 return getter, attribute
1449
1450
1451def _patch_object(
1452 target, attribute, new=DEFAULT, spec=None,
Michael Foord08f47552012-03-25 17:39:04 +01001453 create=False, spec_set=None, autospec=None,
Michael Foord1e68bec2012-03-03 22:24:30 +00001454 new_callable=None, **kwargs
1455 ):
1456 """
1457 patch.object(target, attribute, new=DEFAULT, spec=None, create=False,
Michael Foord08f47552012-03-25 17:39:04 +01001458 spec_set=None, autospec=None, new_callable=None, **kwargs)
Michael Foord1e68bec2012-03-03 22:24:30 +00001459
1460 patch the named member (`attribute`) on an object (`target`) with a mock
1461 object.
1462
1463 `patch.object` can be used as a decorator, class decorator or a context
Michael Foorda9a8bb92012-03-13 14:39:59 -07001464 manager. Arguments `new`, `spec`, `create`, `spec_set`,
Michael Foord1e68bec2012-03-03 22:24:30 +00001465 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1466 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1467 the mock object it creates.
1468
1469 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1470 for choosing which methods to wrap.
1471 """
1472 getter = lambda: target
1473 return _patch(
Michael Foorda9a8bb92012-03-13 14:39:59 -07001474 getter, attribute, new, spec, create,
Michael Foord1e68bec2012-03-03 22:24:30 +00001475 spec_set, autospec, new_callable, kwargs
1476 )
1477
1478
Michael Foord08f47552012-03-25 17:39:04 +01001479def _patch_multiple(target, spec=None, create=False, spec_set=None,
Michael Foord6e71f172012-03-25 19:35:52 +01001480 autospec=None, new_callable=None, **kwargs):
Michael Foord1e68bec2012-03-03 22:24:30 +00001481 """Perform multiple patches in a single call. It takes the object to be
1482 patched (either as an object or a string to fetch the object by importing)
1483 and keyword arguments for the patches::
1484
1485 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1486 ...
1487
1488 Use `DEFAULT` as the value if you want `patch.multiple` to create
1489 mocks for you. In this case the created mocks are passed into a decorated
1490 function by keyword, and a dictionary is returned when `patch.multiple` is
1491 used as a context manager.
1492
1493 `patch.multiple` can be used as a decorator, class decorator or a context
Michael Foorda9a8bb92012-03-13 14:39:59 -07001494 manager. The arguments `spec`, `spec_set`, `create`,
Michael Foord1e68bec2012-03-03 22:24:30 +00001495 `autospec` and `new_callable` have the same meaning as for `patch`. These
1496 arguments will be applied to *all* patches done by `patch.multiple`.
1497
1498 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1499 for choosing which methods to wrap.
1500 """
1501 if type(target) in (unicode, str):
1502 getter = lambda: _importer(target)
1503 else:
1504 getter = lambda: target
1505
1506 if not kwargs:
1507 raise ValueError(
1508 'Must supply at least one keyword argument with patch.multiple'
1509 )
1510 # need to wrap in a list for python 3, where items is a view
1511 items = list(kwargs.items())
1512 attribute, new = items[0]
1513 patcher = _patch(
Michael Foorda9a8bb92012-03-13 14:39:59 -07001514 getter, attribute, new, spec, create, spec_set,
Michael Foord1e68bec2012-03-03 22:24:30 +00001515 autospec, new_callable, {}
1516 )
1517 patcher.attribute_name = attribute
1518 for attribute, new in items[1:]:
1519 this_patcher = _patch(
Michael Foorda9a8bb92012-03-13 14:39:59 -07001520 getter, attribute, new, spec, create, spec_set,
Michael Foord1e68bec2012-03-03 22:24:30 +00001521 autospec, new_callable, {}
1522 )
1523 this_patcher.attribute_name = attribute
1524 patcher.additional_patchers.append(this_patcher)
1525 return patcher
1526
1527
1528def patch(
1529 target, new=DEFAULT, spec=None, create=False,
Michael Foord08f47552012-03-25 17:39:04 +01001530 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord1e68bec2012-03-03 22:24:30 +00001531 ):
1532 """
1533 `patch` acts as a function decorator, class decorator or a context
1534 manager. Inside the body of the function or with statement, the `target`
Michael Foord06fb5c62012-03-28 15:10:06 +01001535 is patched with a `new` object. When the function/with statement exits
1536 the patch is undone.
Michael Foord1e68bec2012-03-03 22:24:30 +00001537
Michael Foord06fb5c62012-03-28 15:10:06 +01001538 If `new` is omitted, then the target is replaced with a
1539 `MagicMock`. If `patch` is used as a decorator and `new` is
1540 omitted, the created mock is passed in as an extra argument to the
1541 decorated function. If `patch` is used as a context manager the created
1542 mock is returned by the context manager.
Michael Foord1e68bec2012-03-03 22:24:30 +00001543
Michael Foord06fb5c62012-03-28 15:10:06 +01001544 `target` should be a string in the form `'package.module.ClassName'`. The
1545 `target` is imported and the specified object replaced with the `new`
1546 object, so the `target` must be importable from the environment you are
1547 calling `patch` from. The target is imported when the decorated function
1548 is executed, not at decoration time.
Michael Foord1e68bec2012-03-03 22:24:30 +00001549
1550 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1551 if patch is creating one for you.
1552
1553 In addition you can pass `spec=True` or `spec_set=True`, which causes
1554 patch to pass in the object being mocked as the spec/spec_set object.
1555
1556 `new_callable` allows you to specify a different class, or callable object,
1557 that will be called to create the `new` object. By default `MagicMock` is
1558 used.
1559
1560 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1561 then the mock with be created with a spec from the object being replaced.
1562 All attributes of the mock will also have the spec of the corresponding
Michael Foorda9a8bb92012-03-13 14:39:59 -07001563 attribute of the object being replaced. Methods and functions being
1564 mocked will have their arguments checked and will raise a `TypeError` if
1565 they are called with the wrong signature. For mocks replacing a class,
1566 their return value (the 'instance') will have the same spec as the class.
Michael Foord1e68bec2012-03-03 22:24:30 +00001567
1568 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1569 arbitrary object as the spec instead of the one being replaced.
1570
Michael Foord1e68bec2012-03-03 22:24:30 +00001571 By default `patch` will fail to replace attributes that don't exist. If
1572 you pass in `create=True`, and the attribute doesn't exist, patch will
1573 create the attribute for you when the patched function is called, and
1574 delete it again afterwards. This is useful for writing tests against
1575 attributes that your production code creates at runtime. It is off by by
1576 default because it can be dangerous. With it switched on you can write
1577 passing tests against APIs that don't actually exist!
1578
1579 Patch can be used as a `TestCase` class decorator. It works by
1580 decorating each test method in the class. This reduces the boilerplate
1581 code when your test methods share a common patchings set. `patch` finds
1582 tests by looking for method names that start with `patch.TEST_PREFIX`.
1583 By default this is `test`, which matches the way `unittest` finds tests.
1584 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1585
1586 Patch can be used as a context manager, with the with statement. Here the
1587 patching applies to the indented block after the with statement. If you
1588 use "as" then the patched object will be bound to the name after the
1589 "as"; very useful if `patch` is creating a mock object for you.
1590
1591 `patch` takes arbitrary keyword arguments. These will be passed to
1592 the `Mock` (or `new_callable`) on construction.
1593
1594 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1595 available for alternate use-cases.
1596 """
1597 getter, attribute = _get_target(target)
1598 return _patch(
Michael Foorda9a8bb92012-03-13 14:39:59 -07001599 getter, attribute, new, spec, create,
Michael Foord1e68bec2012-03-03 22:24:30 +00001600 spec_set, autospec, new_callable, kwargs
1601 )
1602
1603
1604class _patch_dict(object):
1605 """
1606 Patch a dictionary, or dictionary like object, and restore the dictionary
1607 to its original state after the test.
1608
1609 `in_dict` can be a dictionary or a mapping like container. If it is a
1610 mapping then it must at least support getting, setting and deleting items
1611 plus iterating over keys.
1612
1613 `in_dict` can also be a string specifying the name of the dictionary, which
1614 will then be fetched by importing it.
1615
1616 `values` can be a dictionary of values to set in the dictionary. `values`
1617 can also be an iterable of `(key, value)` pairs.
1618
1619 If `clear` is True then the dictionary will be cleared before the new
1620 values are set.
1621
1622 `patch.dict` can also be called with arbitrary keyword arguments to set
1623 values in the dictionary::
1624
1625 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1626 ...
1627
1628 `patch.dict` can be used as a context manager, decorator or class
1629 decorator. When used as a class decorator `patch.dict` honours
1630 `patch.TEST_PREFIX` for choosing which methods to wrap.
1631 """
1632
1633 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1634 if isinstance(in_dict, basestring):
1635 in_dict = _importer(in_dict)
1636 self.in_dict = in_dict
1637 # support any argument supported by dict(...) constructor
1638 self.values = dict(values)
1639 self.values.update(kwargs)
1640 self.clear = clear
1641 self._original = None
1642
1643
1644 def __call__(self, f):
1645 if isinstance(f, ClassTypes):
1646 return self.decorate_class(f)
1647 @wraps(f)
1648 def _inner(*args, **kw):
1649 self._patch_dict()
1650 try:
1651 return f(*args, **kw)
1652 finally:
1653 self._unpatch_dict()
1654
1655 return _inner
1656
1657
1658 def decorate_class(self, klass):
1659 for attr in dir(klass):
1660 attr_value = getattr(klass, attr)
1661 if (attr.startswith(patch.TEST_PREFIX) and
1662 hasattr(attr_value, "__call__")):
1663 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1664 decorated = decorator(attr_value)
1665 setattr(klass, attr, decorated)
1666 return klass
1667
1668
1669 def __enter__(self):
1670 """Patch the dict."""
1671 self._patch_dict()
1672
1673
1674 def _patch_dict(self):
1675 values = self.values
1676 in_dict = self.in_dict
1677 clear = self.clear
1678
1679 try:
1680 original = in_dict.copy()
1681 except AttributeError:
1682 # dict like object with no copy method
1683 # must support iteration over keys
1684 original = {}
1685 for key in in_dict:
1686 original[key] = in_dict[key]
1687 self._original = original
1688
1689 if clear:
1690 _clear_dict(in_dict)
1691
1692 try:
1693 in_dict.update(values)
1694 except AttributeError:
1695 # dict like object with no update method
1696 for key in values:
1697 in_dict[key] = values[key]
1698
1699
1700 def _unpatch_dict(self):
1701 in_dict = self.in_dict
1702 original = self._original
1703
1704 _clear_dict(in_dict)
1705
1706 try:
1707 in_dict.update(original)
1708 except AttributeError:
1709 for key in original:
1710 in_dict[key] = original[key]
1711
1712
1713 def __exit__(self, *args):
1714 """Unpatch the dict."""
1715 self._unpatch_dict()
1716 return False
1717
1718 start = __enter__
1719 stop = __exit__
1720
1721
1722def _clear_dict(in_dict):
1723 try:
1724 in_dict.clear()
1725 except AttributeError:
1726 keys = list(in_dict)
1727 for key in keys:
1728 del in_dict[key]
1729
1730
Michael Foord99dc7a52012-06-10 20:29:40 +01001731def _patch_stopall():
1732 """Stop all active patches."""
1733 for patch in list(_patch._active_patches):
1734 patch.stop()
1735
1736
Michael Foord1e68bec2012-03-03 22:24:30 +00001737patch.object = _patch_object
1738patch.dict = _patch_dict
1739patch.multiple = _patch_multiple
Michael Foord99dc7a52012-06-10 20:29:40 +01001740patch.stopall = _patch_stopall
Michael Foord1e68bec2012-03-03 22:24:30 +00001741patch.TEST_PREFIX = 'test'
1742
1743magic_methods = (
1744 "lt le gt ge eq ne "
1745 "getitem setitem delitem "
1746 "len contains iter "
1747 "hash str sizeof "
1748 "enter exit "
1749 "divmod neg pos abs invert "
1750 "complex int float index "
1751 "trunc floor ceil "
1752)
1753
1754numerics = "add sub mul div floordiv mod lshift rshift and xor or pow "
1755inplace = ' '.join('i%s' % n for n in numerics.split())
1756right = ' '.join('r%s' % n for n in numerics.split())
1757extra = ''
1758if inPy3k:
1759 extra = 'bool next '
1760else:
1761 extra = 'unicode long nonzero oct hex truediv rtruediv '
1762
1763# not including __prepare__, __instancecheck__, __subclasscheck__
1764# (as they are metaclass methods)
1765# __del__ is not supported at all as it causes problems if it exists
1766
1767_non_defaults = set('__%s__' % method for method in [
1768 'cmp', 'getslice', 'setslice', 'coerce', 'subclasses',
1769 'format', 'get', 'set', 'delete', 'reversed',
1770 'missing', 'reduce', 'reduce_ex', 'getinitargs',
1771 'getnewargs', 'getstate', 'setstate', 'getformat',
1772 'setformat', 'repr', 'dir'
1773])
1774
1775
1776def _get_method(name, func):
1777 "Turns a callable object (like a mock) into a real function"
1778 def method(self, *args, **kw):
1779 return func(self, *args, **kw)
1780 method.__name__ = name
1781 return method
1782
1783
1784_magics = set(
1785 '__%s__' % method for method in
1786 ' '.join([magic_methods, numerics, inplace, right, extra]).split()
1787)
1788
1789_all_magics = _magics | _non_defaults
1790
1791_unsupported_magics = set([
1792 '__getattr__', '__setattr__',
1793 '__init__', '__new__', '__prepare__'
1794 '__instancecheck__', '__subclasscheck__',
1795 '__del__'
1796])
1797
1798_calculate_return_value = {
1799 '__hash__': lambda self: object.__hash__(self),
1800 '__str__': lambda self: object.__str__(self),
1801 '__sizeof__': lambda self: object.__sizeof__(self),
1802 '__unicode__': lambda self: unicode(object.__str__(self)),
1803}
1804
1805_return_values = {
Michael Foord62dd80f2012-03-17 17:37:22 -07001806 '__lt__': NotImplemented,
1807 '__gt__': NotImplemented,
1808 '__le__': NotImplemented,
1809 '__ge__': NotImplemented,
Michael Foord1e68bec2012-03-03 22:24:30 +00001810 '__int__': 1,
1811 '__contains__': False,
1812 '__len__': 0,
1813 '__exit__': False,
1814 '__complex__': 1j,
1815 '__float__': 1.0,
1816 '__bool__': True,
1817 '__nonzero__': True,
1818 '__oct__': '1',
1819 '__hex__': '0x1',
1820 '__long__': long(1),
1821 '__index__': 1,
1822}
1823
1824
1825def _get_eq(self):
1826 def __eq__(other):
1827 ret_val = self.__eq__._mock_return_value
1828 if ret_val is not DEFAULT:
1829 return ret_val
1830 return self is other
1831 return __eq__
1832
1833def _get_ne(self):
1834 def __ne__(other):
1835 if self.__ne__._mock_return_value is not DEFAULT:
1836 return DEFAULT
1837 return self is not other
1838 return __ne__
1839
1840def _get_iter(self):
1841 def __iter__():
1842 ret_val = self.__iter__._mock_return_value
1843 if ret_val is DEFAULT:
1844 return iter([])
1845 # if ret_val was already an iterator, then calling iter on it should
1846 # return the iterator unchanged
1847 return iter(ret_val)
1848 return __iter__
1849
1850_side_effect_methods = {
1851 '__eq__': _get_eq,
1852 '__ne__': _get_ne,
1853 '__iter__': _get_iter,
1854}
1855
1856
1857
1858def _set_return_value(mock, method, name):
1859 fixed = _return_values.get(name, DEFAULT)
1860 if fixed is not DEFAULT:
1861 method.return_value = fixed
1862 return
1863
1864 return_calulator = _calculate_return_value.get(name)
1865 if return_calulator is not None:
1866 try:
1867 return_value = return_calulator(mock)
1868 except AttributeError:
1869 # XXXX why do we return AttributeError here?
1870 # set it as a side_effect instead?
1871 return_value = AttributeError(name)
1872 method.return_value = return_value
1873 return
1874
1875 side_effector = _side_effect_methods.get(name)
1876 if side_effector is not None:
1877 method.side_effect = side_effector(mock)
1878
1879
1880
1881class MagicMixin(object):
1882 def __init__(self, *args, **kw):
1883 _super(MagicMixin, self).__init__(*args, **kw)
1884 self._mock_set_magics()
1885
1886
1887 def _mock_set_magics(self):
1888 these_magics = _magics
1889
1890 if self._mock_methods is not None:
1891 these_magics = _magics.intersection(self._mock_methods)
1892
1893 remove_magics = set()
1894 remove_magics = _magics - these_magics
1895
1896 for entry in remove_magics:
1897 if entry in type(self).__dict__:
1898 # remove unneeded magic methods
1899 delattr(self, entry)
1900
1901 # don't overwrite existing attributes if called a second time
1902 these_magics = these_magics - set(type(self).__dict__)
1903
1904 _type = type(self)
1905 for entry in these_magics:
1906 setattr(_type, entry, MagicProxy(entry, self))
1907
1908
1909
1910class NonCallableMagicMock(MagicMixin, NonCallableMock):
1911 """A version of `MagicMock` that isn't callable."""
1912 def mock_add_spec(self, spec, spec_set=False):
1913 """Add a spec to a mock. `spec` can either be an object or a
1914 list of strings. Only attributes on the `spec` can be fetched as
1915 attributes from the mock.
1916
1917 If `spec_set` is True then only attributes on the spec can be set."""
1918 self._mock_add_spec(spec, spec_set)
1919 self._mock_set_magics()
1920
1921
1922
1923class MagicMock(MagicMixin, Mock):
1924 """
1925 MagicMock is a subclass of Mock with default implementations
1926 of most of the magic methods. You can use MagicMock without having to
1927 configure the magic methods yourself.
1928
1929 If you use the `spec` or `spec_set` arguments then *only* magic
1930 methods that exist in the spec will be created.
1931
1932 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1933 """
1934 def mock_add_spec(self, spec, spec_set=False):
1935 """Add a spec to a mock. `spec` can either be an object or a
1936 list of strings. Only attributes on the `spec` can be fetched as
1937 attributes from the mock.
1938
1939 If `spec_set` is True then only attributes on the spec can be set."""
1940 self._mock_add_spec(spec, spec_set)
1941 self._mock_set_magics()
1942
1943
1944
1945class MagicProxy(object):
1946 def __init__(self, name, parent):
1947 self.name = name
1948 self.parent = parent
1949
1950 def __call__(self, *args, **kwargs):
1951 m = self.create_mock()
1952 return m(*args, **kwargs)
1953
1954 def create_mock(self):
1955 entry = self.name
1956 parent = self.parent
1957 m = parent._get_child_mock(name=entry, _new_name=entry,
1958 _new_parent=parent)
1959 setattr(parent, entry, m)
1960 _set_return_value(parent, m, entry)
1961 return m
1962
1963 def __get__(self, obj, _type=None):
1964 return self.create_mock()
1965
1966
1967
1968class _ANY(object):
1969 "A helper object that compares equal to everything."
1970
1971 def __eq__(self, other):
1972 return True
1973
1974 def __ne__(self, other):
1975 return False
1976
1977 def __repr__(self):
1978 return '<ANY>'
1979
1980ANY = _ANY()
1981
1982
1983
1984def _format_call_signature(name, args, kwargs):
1985 message = '%s(%%s)' % name
1986 formatted_args = ''
1987 args_string = ', '.join([repr(arg) for arg in args])
1988 kwargs_string = ', '.join([
1989 '%s=%r' % (key, value) for key, value in kwargs.items()
1990 ])
1991 if args_string:
1992 formatted_args = args_string
1993 if kwargs_string:
1994 if formatted_args:
1995 formatted_args += ', '
1996 formatted_args += kwargs_string
1997
1998 return message % formatted_args
1999
2000
2001
2002class _Call(tuple):
2003 """
2004 A tuple for holding the results of a call to a mock, either in the form
2005 `(args, kwargs)` or `(name, args, kwargs)`.
2006
2007 If args or kwargs are empty then a call tuple will compare equal to
2008 a tuple without those values. This makes comparisons less verbose::
2009
2010 _Call(('name', (), {})) == ('name',)
2011 _Call(('name', (1,), {})) == ('name', (1,))
2012 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2013
2014 The `_Call` object provides a useful shortcut for comparing with call::
2015
2016 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2017 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2018
2019 If the _Call has no name then it will match any name.
2020 """
2021 def __new__(cls, value=(), name=None, parent=None, two=False,
2022 from_kall=True):
2023 name = ''
2024 args = ()
2025 kwargs = {}
2026 _len = len(value)
2027 if _len == 3:
2028 name, args, kwargs = value
2029 elif _len == 2:
2030 first, second = value
2031 if isinstance(first, basestring):
2032 name = first
2033 if isinstance(second, tuple):
2034 args = second
2035 else:
2036 kwargs = second
2037 else:
2038 args, kwargs = first, second
2039 elif _len == 1:
2040 value, = value
2041 if isinstance(value, basestring):
2042 name = value
2043 elif isinstance(value, tuple):
2044 args = value
2045 else:
2046 kwargs = value
2047
2048 if two:
2049 return tuple.__new__(cls, (args, kwargs))
2050
2051 return tuple.__new__(cls, (name, args, kwargs))
2052
2053
2054 def __init__(self, value=(), name=None, parent=None, two=False,
2055 from_kall=True):
2056 self.name = name
2057 self.parent = parent
2058 self.from_kall = from_kall
2059
2060
2061 def __eq__(self, other):
2062 if other is ANY:
2063 return True
2064 try:
2065 len_other = len(other)
2066 except TypeError:
2067 return False
2068
2069 self_name = ''
2070 if len(self) == 2:
2071 self_args, self_kwargs = self
2072 else:
2073 self_name, self_args, self_kwargs = self
2074
2075 other_name = ''
2076 if len_other == 0:
2077 other_args, other_kwargs = (), {}
2078 elif len_other == 3:
2079 other_name, other_args, other_kwargs = other
2080 elif len_other == 1:
2081 value, = other
2082 if isinstance(value, tuple):
2083 other_args = value
2084 other_kwargs = {}
2085 elif isinstance(value, basestring):
2086 other_name = value
2087 other_args, other_kwargs = (), {}
2088 else:
2089 other_args = ()
2090 other_kwargs = value
2091 else:
2092 # len 2
2093 # could be (name, args) or (name, kwargs) or (args, kwargs)
2094 first, second = other
2095 if isinstance(first, basestring):
2096 other_name = first
2097 if isinstance(second, tuple):
2098 other_args, other_kwargs = second, {}
2099 else:
2100 other_args, other_kwargs = (), second
2101 else:
2102 other_args, other_kwargs = first, second
2103
2104 if self_name and other_name != self_name:
2105 return False
2106
2107 # this order is important for ANY to work!
2108 return (other_args, other_kwargs) == (self_args, self_kwargs)
2109
2110
2111 def __ne__(self, other):
2112 return not self.__eq__(other)
2113
2114
2115 def __call__(self, *args, **kwargs):
2116 if self.name is None:
2117 return _Call(('', args, kwargs), name='()')
2118
2119 name = self.name + '()'
2120 return _Call((self.name, args, kwargs), name=name, parent=self)
2121
2122
2123 def __getattr__(self, attr):
2124 if self.name is None:
2125 return _Call(name=attr, from_kall=False)
2126 name = '%s.%s' % (self.name, attr)
2127 return _Call(name=name, parent=self, from_kall=False)
2128
2129
2130 def __repr__(self):
2131 if not self.from_kall:
2132 name = self.name or 'call'
2133 if name.startswith('()'):
2134 name = 'call%s' % name
2135 return name
2136
2137 if len(self) == 2:
2138 name = 'call'
2139 args, kwargs = self
2140 else:
2141 name, args, kwargs = self
2142 if not name:
2143 name = 'call'
2144 elif not name.startswith('()'):
2145 name = 'call.%s' % name
2146 else:
2147 name = 'call%s' % name
2148 return _format_call_signature(name, args, kwargs)
2149
2150
2151 def call_list(self):
2152 """For a call object that represents multiple calls, `call_list`
2153 returns a list of all the intermediate calls as well as the
2154 final call."""
2155 vals = []
2156 thing = self
2157 while thing is not None:
2158 if thing.from_kall:
2159 vals.append(thing)
2160 thing = thing.parent
2161 return _CallList(reversed(vals))
2162
2163
2164call = _Call(from_kall=False)
2165
2166
2167
2168def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2169 _name=None, **kwargs):
2170 """Create a mock object using another object as a spec. Attributes on the
2171 mock will use the corresponding attribute on the `spec` object as their
2172 spec.
2173
Michael Foorda9a8bb92012-03-13 14:39:59 -07002174 Functions or methods being mocked will have their arguments checked
2175 to check that they are called with the correct signature.
Michael Foord1e68bec2012-03-03 22:24:30 +00002176
2177 If `spec_set` is True then attempting to set attributes that don't exist
2178 on the spec object will raise an `AttributeError`.
2179
2180 If a class is used as a spec then the return value of the mock (the
2181 instance of the class) will have the same spec. You can use a class as the
2182 spec for an instance object by passing `instance=True`. The returned mock
2183 will only be callable if instances of the mock are callable.
2184
2185 `create_autospec` also takes arbitrary keyword arguments that are passed to
2186 the constructor of the created mock."""
2187 if _is_list(spec):
2188 # can't pass a list instance to the mock constructor as it will be
2189 # interpreted as a list of strings
2190 spec = type(spec)
2191
2192 is_type = isinstance(spec, ClassTypes)
2193
2194 _kwargs = {'spec': spec}
2195 if spec_set:
2196 _kwargs = {'spec_set': spec}
2197 elif spec is None:
2198 # None we mock with a normal mock without a spec
2199 _kwargs = {}
2200
2201 _kwargs.update(kwargs)
2202
2203 Klass = MagicMock
2204 if type(spec) in DescriptorTypes:
2205 # descriptors don't have a spec
2206 # because we don't know what type they return
2207 _kwargs = {}
2208 elif not _callable(spec):
2209 Klass = NonCallableMagicMock
2210 elif is_type and instance and not _instance_callable(spec):
2211 Klass = NonCallableMagicMock
2212
2213 _new_name = _name
2214 if _parent is None:
2215 # for a top level object no _new_name should be set
2216 _new_name = ''
2217
2218 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2219 name=_name, **_kwargs)
2220
2221 if isinstance(spec, FunctionTypes):
2222 # should only happen at the top level because we don't
2223 # recurse for functions
2224 mock = _set_signature(mock, spec)
2225 else:
2226 _check_signature(spec, mock, is_type, instance)
2227
2228 if _parent is not None and not instance:
2229 _parent._mock_children[_name] = mock
2230
2231 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord1e68bec2012-03-03 22:24:30 +00002232 mock.return_value = create_autospec(spec, spec_set, instance=True,
2233 _name='()', _parent=mock)
2234
2235 for entry in dir(spec):
2236 if _is_magic(entry):
2237 # MagicMock already does the useful magic methods for us
2238 continue
2239
2240 if isinstance(spec, FunctionTypes) and entry in FunctionAttributes:
Michael Foorda9a8bb92012-03-13 14:39:59 -07002241 # allow a mock to actually be a function
Michael Foord1e68bec2012-03-03 22:24:30 +00002242 continue
2243
2244 # XXXX do we need a better way of getting attributes without
2245 # triggering code execution (?) Probably not - we need the actual
2246 # object to mock it so we would rather trigger a property than mock
2247 # the property descriptor. Likewise we want to mock out dynamically
2248 # provided attributes.
Michael Foord9e1592e2012-04-13 17:39:31 +01002249 # XXXX what about attributes that raise exceptions other than
2250 # AttributeError on being fetched?
Michael Foord1e68bec2012-03-03 22:24:30 +00002251 # we could be resilient against it, or catch and propagate the
2252 # exception when the attribute is fetched from the mock
Michael Foord7dad0f62012-04-13 17:16:54 +01002253 try:
2254 original = getattr(spec, entry)
2255 except AttributeError:
2256 continue
Michael Foord1e68bec2012-03-03 22:24:30 +00002257
2258 kwargs = {'spec': original}
2259 if spec_set:
2260 kwargs = {'spec_set': original}
2261
2262 if not isinstance(original, FunctionTypes):
2263 new = _SpecState(original, spec_set, mock, entry, instance)
2264 mock._mock_children[entry] = new
2265 else:
2266 parent = mock
2267 if isinstance(spec, FunctionTypes):
2268 parent = mock.mock
2269
2270 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2271 _new_parent=parent, **kwargs)
2272 mock._mock_children[entry] = new
2273 skipfirst = _must_skip(spec, entry, is_type)
2274 _check_signature(original, new, skipfirst=skipfirst)
2275
Michael Foorda9a8bb92012-03-13 14:39:59 -07002276 # so functions created with _set_signature become instance attributes,
Michael Foord1e68bec2012-03-03 22:24:30 +00002277 # *plus* their underlying mock exists in _mock_children of the parent
2278 # mock. Adding to _mock_children may be unnecessary where we are also
2279 # setting as an instance attribute?
2280 if isinstance(new, FunctionTypes):
2281 setattr(mock, entry, new)
2282
2283 return mock
2284
2285
2286def _must_skip(spec, entry, is_type):
2287 if not isinstance(spec, ClassTypes):
2288 if entry in getattr(spec, '__dict__', {}):
2289 # instance attribute - shouldn't skip
2290 return False
Michael Foord1e68bec2012-03-03 22:24:30 +00002291 spec = spec.__class__
2292 if not hasattr(spec, '__mro__'):
2293 # old style class: can't have descriptors anyway
2294 return is_type
2295
2296 for klass in spec.__mro__:
2297 result = klass.__dict__.get(entry, DEFAULT)
2298 if result is DEFAULT:
2299 continue
2300 if isinstance(result, (staticmethod, classmethod)):
2301 return False
2302 return is_type
2303
2304 # shouldn't get here unless function is a dynamically provided attribute
2305 # XXXX untested behaviour
2306 return is_type
2307
2308
2309def _get_class(obj):
2310 try:
2311 return obj.__class__
2312 except AttributeError:
2313 # in Python 2, _sre.SRE_Pattern objects have no __class__
2314 return type(obj)
2315
2316
2317class _SpecState(object):
2318
2319 def __init__(self, spec, spec_set=False, parent=None,
2320 name=None, ids=None, instance=False):
2321 self.spec = spec
2322 self.ids = ids
2323 self.spec_set = spec_set
2324 self.parent = parent
2325 self.instance = instance
2326 self.name = name
2327
2328
2329FunctionTypes = (
2330 # python function
2331 type(create_autospec),
2332 # instance method
2333 type(ANY.__eq__),
2334 # unbound method
2335 type(_ANY.__eq__),
2336)
2337
2338FunctionAttributes = set([
2339 'func_closure',
2340 'func_code',
2341 'func_defaults',
2342 'func_dict',
2343 'func_doc',
2344 'func_globals',
2345 'func_name',
2346])
Michael Foordafc98d42012-03-13 16:38:50 -07002347
Michael Foord86e4ace2012-03-18 18:56:36 +00002348
2349file_spec = None
Michael Foordafc98d42012-03-13 16:38:50 -07002350
2351
Michael Foord8e7aed52012-03-17 18:00:29 -07002352def mock_open(mock=None, read_data=''):
2353 """
2354 A helper function to create a mock to replace the use of `open`. It works
2355 for `open` called directly or used as a context manager.
2356
2357 The `mock` argument is the mock object to configure. If `None` (the
2358 default) then a `MagicMock` will be created for you, with the API limited
2359 to methods or attributes available on standard file handles.
2360
2361 `read_data` is a string for the `read` method of the file handle to return.
2362 This is an empty string by default.
2363 """
Michael Foord86e4ace2012-03-18 18:56:36 +00002364 global file_spec
2365 if file_spec is None:
2366 # set on first use
2367 if inPy3k:
2368 import _io
2369 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2370 else:
2371 file_spec = file
2372
Michael Foordafc98d42012-03-13 16:38:50 -07002373 if mock is None:
Michael Foord8e7aed52012-03-17 18:00:29 -07002374 mock = MagicMock(name='open', spec=open)
Michael Foordafc98d42012-03-13 16:38:50 -07002375
2376 handle = MagicMock(spec=file_spec)
2377 handle.write.return_value = None
2378 handle.__enter__.return_value = handle
Michael Foord6e71f172012-03-25 19:35:52 +01002379 handle.read.return_value = read_data
Michael Foordafc98d42012-03-13 16:38:50 -07002380
2381 mock.return_value = handle
2382 return mock
Michael Foord4b4c9152012-03-13 23:34:50 -07002383
Michael Foordab5fef72012-03-15 19:16:12 -07002384
Michael Foord4b4c9152012-03-13 23:34:50 -07002385class PropertyMock(Mock):
Michael Foordef310bf2012-03-17 19:10:50 -07002386 """
2387 A mock intended to be used as a property, or other descriptor, on a class.
2388 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2389 a return value when it is fetched.
2390
2391 Fetching a `PropertyMock` instance from an object calls the mock, with
2392 no args. Setting it calls the mock with the value being set.
2393 """
Michael Foord95b4b372012-04-13 16:57:52 +01002394 def _get_child_mock(self, **kwargs):
2395 return MagicMock(**kwargs)
2396
Michael Foord4b4c9152012-03-13 23:34:50 -07002397 def __get__(self, obj, obj_type):
2398 return self()
2399 def __set__(self, obj, val):
2400 self(val)