blob: a9c82dcb5d3e96f56b08d9848747e91b353bfab4 [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
Ned Deily9d6d06e2018-06-11 00:45:50 -04005# https://pypi.org/project/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',
Mario Corchero552be9d2017-10-17 12:35:11 +010021 'seal',
Michael Foord345266a2012-03-14 12:24:34 -070022)
23
24
25__version__ = '1.0'
26
27
28import inspect
29import pprint
30import sys
Michael Foordfddcfa22014-04-14 16:25:20 -040031import builtins
32from types import ModuleType
Petter Strandmark47d94242018-10-28 21:37:10 +010033from unittest.util import safe_repr
Antoine Pitrou5c64df72013-02-03 00:23:58 +010034from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070035
36
Michael Foordfddcfa22014-04-14 16:25:20 -040037_builtins = {name for name in dir(builtins) if not name.startswith('_')}
38
Michael Foord345266a2012-03-14 12:24:34 -070039BaseExceptions = (BaseException,)
40if 'java' in sys.platform:
41 # jython
42 import java
43 BaseExceptions = (BaseException, java.lang.Throwable)
44
45
46FILTER_DIR = True
47
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100048# Workaround for issue #12370
49# Without this, the __class__ properties wouldn't be set correctly
50_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070051
52def _is_instance_mock(obj):
53 # can't use isinstance on Mock objects because they override __class__
54 # The base class for all mocks is NonCallableMock
55 return issubclass(type(obj), NonCallableMock)
56
57
58def _is_exception(obj):
59 return (
60 isinstance(obj, BaseExceptions) or
61 isinstance(obj, type) and issubclass(obj, BaseExceptions)
62 )
63
64
Antoine Pitrou5c64df72013-02-03 00:23:58 +010065def _get_signature_object(func, as_instance, eat_self):
66 """
67 Given an arbitrary, possibly callable object, try to create a suitable
68 signature object.
69 Return a (reduced func, signature) tuple, or None.
70 """
71 if isinstance(func, type) and not as_instance:
72 # If it's a type and should be modelled as a type, use __init__.
Michael Foord345266a2012-03-14 12:24:34 -070073 try:
74 func = func.__init__
75 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010076 return None
77 # Skip the `self` argument in __init__
78 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070079 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010080 # If we really want to model an instance of the passed type,
81 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070082 try:
83 func = func.__call__
84 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010085 return None
86 if eat_self:
87 sig_func = partial(func, None)
88 else:
89 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -070090 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010091 return func, inspect.signature(sig_func)
92 except ValueError:
93 # Certain callable types are not supported by inspect.signature()
94 return None
Michael Foord345266a2012-03-14 12:24:34 -070095
96
97def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010098 sig = _get_signature_object(func, instance, skipfirst)
99 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700100 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100101 func, sig = sig
102 def checksig(_mock_self, *args, **kwargs):
103 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700104 _copy_func_details(func, checksig)
105 type(mock)._mock_check_sig = checksig
106
107
108def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700109 # we explicitly don't copy func.__dict__ into this copy as it would
110 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300111 for attribute in (
112 '__name__', '__doc__', '__text_signature__',
113 '__module__', '__defaults__', '__kwdefaults__',
114 ):
115 try:
116 setattr(funcopy, attribute, getattr(func, attribute))
117 except AttributeError:
118 pass
Michael Foord345266a2012-03-14 12:24:34 -0700119
120
121def _callable(obj):
122 if isinstance(obj, type):
123 return True
124 if getattr(obj, '__call__', None) is not None:
125 return True
126 return False
127
128
129def _is_list(obj):
130 # checks for list or tuples
131 # XXXX badly named!
132 return type(obj) in (list, tuple)
133
134
135def _instance_callable(obj):
136 """Given an object, return True if the object is callable.
137 For classes, return True if instances would be callable."""
138 if not isinstance(obj, type):
139 # already an instance
140 return getattr(obj, '__call__', None) is not None
141
Michael Foorda74b3aa2012-03-14 14:40:22 -0700142 # *could* be broken by a class overriding __mro__ or __dict__ via
143 # a metaclass
144 for base in (obj,) + obj.__mro__:
145 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700146 return True
147 return False
148
149
150def _set_signature(mock, original, instance=False):
151 # creates a function with signature (*args, **kwargs) that delegates to a
152 # mock. It still does signature checking by calling a lambda with the same
153 # signature as the original.
154 if not _callable(original):
155 return
156
157 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100158 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700159 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700160 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100161 func, sig = result
162 def checksig(*args, **kwargs):
163 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700164 _copy_func_details(func, checksig)
165
166 name = original.__name__
167 if not name.isidentifier():
168 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100169 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700170 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100171 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700172 return mock(*args, **kwargs)""" % name
173 exec (src, context)
174 funcopy = context[name]
175 _setup_func(funcopy, mock)
176 return funcopy
177
178
179def _setup_func(funcopy, mock):
180 funcopy.mock = mock
181
182 # can't use isinstance with mocks
183 if not _is_instance_mock(mock):
184 return
185
186 def assert_called_with(*args, **kwargs):
187 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700188 def assert_called(*args, **kwargs):
189 return mock.assert_called(*args, **kwargs)
190 def assert_not_called(*args, **kwargs):
191 return mock.assert_not_called(*args, **kwargs)
192 def assert_called_once(*args, **kwargs):
193 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700194 def assert_called_once_with(*args, **kwargs):
195 return mock.assert_called_once_with(*args, **kwargs)
196 def assert_has_calls(*args, **kwargs):
197 return mock.assert_has_calls(*args, **kwargs)
198 def assert_any_call(*args, **kwargs):
199 return mock.assert_any_call(*args, **kwargs)
200 def reset_mock():
201 funcopy.method_calls = _CallList()
202 funcopy.mock_calls = _CallList()
203 mock.reset_mock()
204 ret = funcopy.return_value
205 if _is_instance_mock(ret) and not ret is mock:
206 ret.reset_mock()
207
208 funcopy.called = False
209 funcopy.call_count = 0
210 funcopy.call_args = None
211 funcopy.call_args_list = _CallList()
212 funcopy.method_calls = _CallList()
213 funcopy.mock_calls = _CallList()
214
215 funcopy.return_value = mock.return_value
216 funcopy.side_effect = mock.side_effect
217 funcopy._mock_children = mock._mock_children
218
219 funcopy.assert_called_with = assert_called_with
220 funcopy.assert_called_once_with = assert_called_once_with
221 funcopy.assert_has_calls = assert_has_calls
222 funcopy.assert_any_call = assert_any_call
223 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700224 funcopy.assert_called = assert_called
225 funcopy.assert_not_called = assert_not_called
226 funcopy.assert_called_once = assert_called_once
Michael Foord345266a2012-03-14 12:24:34 -0700227
228 mock._mock_delegate = funcopy
229
230
231def _is_magic(name):
232 return '__%s__' % name[2:-2] == name
233
234
235class _SentinelObject(object):
236 "A unique, named, sentinel object."
237 def __init__(self, name):
238 self.name = name
239
240 def __repr__(self):
241 return 'sentinel.%s' % self.name
242
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200243 def __reduce__(self):
244 return 'sentinel.%s' % self.name
245
Michael Foord345266a2012-03-14 12:24:34 -0700246
247class _Sentinel(object):
248 """Access attributes to return a named object, usable as a sentinel."""
249 def __init__(self):
250 self._sentinels = {}
251
252 def __getattr__(self, name):
253 if name == '__bases__':
254 # Without this help(unittest.mock) raises an exception
255 raise AttributeError
256 return self._sentinels.setdefault(name, _SentinelObject(name))
257
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200258 def __reduce__(self):
259 return 'sentinel'
260
Michael Foord345266a2012-03-14 12:24:34 -0700261
262sentinel = _Sentinel()
263
264DEFAULT = sentinel.DEFAULT
265_missing = sentinel.MISSING
266_deleted = sentinel.DELETED
267
268
Michael Foord345266a2012-03-14 12:24:34 -0700269def _copy(value):
270 if type(value) in (dict, list, tuple, set):
271 return type(value)(value)
272 return value
273
274
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200275_allowed_names = {
276 'return_value', '_mock_return_value', 'side_effect',
277 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
278 '_mock_name', '_mock_new_name'
279}
Michael Foord345266a2012-03-14 12:24:34 -0700280
281
282def _delegating_property(name):
283 _allowed_names.add(name)
284 _the_name = '_mock_' + name
285 def _get(self, name=name, _the_name=_the_name):
286 sig = self._mock_delegate
287 if sig is None:
288 return getattr(self, _the_name)
289 return getattr(sig, name)
290 def _set(self, value, name=name, _the_name=_the_name):
291 sig = self._mock_delegate
292 if sig is None:
293 self.__dict__[_the_name] = value
294 else:
295 setattr(sig, name, value)
296
297 return property(_get, _set)
298
299
300
301class _CallList(list):
302
303 def __contains__(self, value):
304 if not isinstance(value, list):
305 return list.__contains__(self, value)
306 len_value = len(value)
307 len_self = len(self)
308 if len_value > len_self:
309 return False
310
311 for i in range(0, len_self - len_value + 1):
312 sub_list = self[i:i+len_value]
313 if sub_list == value:
314 return True
315 return False
316
317 def __repr__(self):
318 return pprint.pformat(list(self))
319
320
321def _check_and_set_parent(parent, value, name, new_name):
322 if not _is_instance_mock(value):
323 return False
324 if ((value._mock_name or value._mock_new_name) or
325 (value._mock_parent is not None) or
326 (value._mock_new_parent is not None)):
327 return False
328
329 _parent = parent
330 while _parent is not None:
331 # setting a mock (value) as a child or return value of itself
332 # should not modify the mock
333 if _parent is value:
334 return False
335 _parent = _parent._mock_new_parent
336
337 if new_name:
338 value._mock_new_parent = parent
339 value._mock_new_name = new_name
340 if name:
341 value._mock_parent = parent
342 value._mock_name = name
343 return True
344
Michael Foord01bafdc2014-04-14 16:09:42 -0400345# Internal class to identify if we wrapped an iterator object or not.
346class _MockIter(object):
347 def __init__(self, obj):
348 self.obj = iter(obj)
349 def __iter__(self):
350 return self
351 def __next__(self):
352 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700353
354class Base(object):
355 _mock_return_value = DEFAULT
356 _mock_side_effect = None
357 def __init__(self, *args, **kwargs):
358 pass
359
360
361
362class NonCallableMock(Base):
363 """A non-callable version of `Mock`"""
364
365 def __new__(cls, *args, **kw):
366 # every instance has its own class
367 # so we can create magic methods on the
368 # class without stomping on other mocks
369 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
370 instance = object.__new__(new)
371 return instance
372
373
374 def __init__(
375 self, spec=None, wraps=None, name=None, spec_set=None,
376 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530377 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700378 ):
379 if _new_parent is None:
380 _new_parent = parent
381
382 __dict__ = self.__dict__
383 __dict__['_mock_parent'] = parent
384 __dict__['_mock_name'] = name
385 __dict__['_mock_new_name'] = _new_name
386 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100387 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700388
389 if spec_set is not None:
390 spec = spec_set
391 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100392 if _eat_self is None:
393 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700394
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100395 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700396
397 __dict__['_mock_children'] = {}
398 __dict__['_mock_wraps'] = wraps
399 __dict__['_mock_delegate'] = None
400
401 __dict__['_mock_called'] = False
402 __dict__['_mock_call_args'] = None
403 __dict__['_mock_call_count'] = 0
404 __dict__['_mock_call_args_list'] = _CallList()
405 __dict__['_mock_mock_calls'] = _CallList()
406
407 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530408 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700409
410 if kwargs:
411 self.configure_mock(**kwargs)
412
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000413 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700414 spec, wraps, name, spec_set, parent,
415 _spec_state
416 )
417
418
419 def attach_mock(self, mock, attribute):
420 """
421 Attach a mock as an attribute of this one, replacing its name and
422 parent. Calls to the attached mock will be recorded in the
423 `method_calls` and `mock_calls` attributes of this one."""
424 mock._mock_parent = None
425 mock._mock_new_parent = None
426 mock._mock_name = ''
427 mock._mock_new_name = None
428
429 setattr(self, attribute, mock)
430
431
432 def mock_add_spec(self, spec, spec_set=False):
433 """Add a spec to a mock. `spec` can either be an object or a
434 list of strings. Only attributes on the `spec` can be fetched as
435 attributes from the mock.
436
437 If `spec_set` is True then only attributes on the spec can be set."""
438 self._mock_add_spec(spec, spec_set)
439
440
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100441 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
442 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700443 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100444 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700445
446 if spec is not None and not _is_list(spec):
447 if isinstance(spec, type):
448 _spec_class = spec
449 else:
450 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100451 res = _get_signature_object(spec,
452 _spec_as_instance, _eat_self)
453 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700454
455 spec = dir(spec)
456
457 __dict__ = self.__dict__
458 __dict__['_spec_class'] = _spec_class
459 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100460 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700461 __dict__['_mock_methods'] = spec
462
463
464 def __get_return_value(self):
465 ret = self._mock_return_value
466 if self._mock_delegate is not None:
467 ret = self._mock_delegate.return_value
468
469 if ret is DEFAULT:
470 ret = self._get_child_mock(
471 _new_parent=self, _new_name='()'
472 )
473 self.return_value = ret
474 return ret
475
476
477 def __set_return_value(self, value):
478 if self._mock_delegate is not None:
479 self._mock_delegate.return_value = value
480 else:
481 self._mock_return_value = value
482 _check_and_set_parent(self, value, None, '()')
483
484 __return_value_doc = "The value to be returned when the mock is called."
485 return_value = property(__get_return_value, __set_return_value,
486 __return_value_doc)
487
488
489 @property
490 def __class__(self):
491 if self._spec_class is None:
492 return type(self)
493 return self._spec_class
494
495 called = _delegating_property('called')
496 call_count = _delegating_property('call_count')
497 call_args = _delegating_property('call_args')
498 call_args_list = _delegating_property('call_args_list')
499 mock_calls = _delegating_property('mock_calls')
500
501
502 def __get_side_effect(self):
503 delegated = self._mock_delegate
504 if delegated is None:
505 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400506 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200507 if (sf is not None and not callable(sf)
508 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400509 sf = _MockIter(sf)
510 delegated.side_effect = sf
511 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700512
513 def __set_side_effect(self, value):
514 value = _try_iter(value)
515 delegated = self._mock_delegate
516 if delegated is None:
517 self._mock_side_effect = value
518 else:
519 delegated.side_effect = value
520
521 side_effect = property(__get_side_effect, __set_side_effect)
522
523
Kushal Das9cd39a12016-06-02 10:20:16 -0700524 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700525 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200526 if visited is None:
527 visited = []
528 if id(self) in visited:
529 return
530 visited.append(id(self))
531
Michael Foord345266a2012-03-14 12:24:34 -0700532 self.called = False
533 self.call_args = None
534 self.call_count = 0
535 self.mock_calls = _CallList()
536 self.call_args_list = _CallList()
537 self.method_calls = _CallList()
538
Kushal Das9cd39a12016-06-02 10:20:16 -0700539 if return_value:
540 self._mock_return_value = DEFAULT
541 if side_effect:
542 self._mock_side_effect = None
543
Michael Foord345266a2012-03-14 12:24:34 -0700544 for child in self._mock_children.values():
Michael Foord75963642012-06-09 17:31:59 +0100545 if isinstance(child, _SpecState):
546 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200547 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700548
549 ret = self._mock_return_value
550 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200551 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700552
553
554 def configure_mock(self, **kwargs):
555 """Set attributes on the mock through keyword arguments.
556
557 Attributes plus return values and side effects can be set on child
558 mocks using standard dot notation and unpacking a dictionary in the
559 method call:
560
561 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
562 >>> mock.configure_mock(**attrs)"""
563 for arg, val in sorted(kwargs.items(),
564 # we sort on the number of dots so that
565 # attributes are set before we set attributes on
566 # attributes
567 key=lambda entry: entry[0].count('.')):
568 args = arg.split('.')
569 final = args.pop()
570 obj = self
571 for entry in args:
572 obj = getattr(obj, entry)
573 setattr(obj, final, val)
574
575
576 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530577 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700578 raise AttributeError(name)
579 elif self._mock_methods is not None:
580 if name not in self._mock_methods or name in _all_magics:
581 raise AttributeError("Mock object has no attribute %r" % name)
582 elif _is_magic(name):
583 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530584 if not self._mock_unsafe:
585 if name.startswith(('assert', 'assret')):
586 raise AttributeError(name)
Michael Foord345266a2012-03-14 12:24:34 -0700587
588 result = self._mock_children.get(name)
589 if result is _deleted:
590 raise AttributeError(name)
591 elif result is None:
592 wraps = None
593 if self._mock_wraps is not None:
594 # XXXX should we get the attribute without triggering code
595 # execution?
596 wraps = getattr(self._mock_wraps, name)
597
598 result = self._get_child_mock(
599 parent=self, name=name, wraps=wraps, _new_name=name,
600 _new_parent=self
601 )
602 self._mock_children[name] = result
603
604 elif isinstance(result, _SpecState):
605 result = create_autospec(
606 result.spec, result.spec_set, result.instance,
607 result.parent, result.name
608 )
609 self._mock_children[name] = result
610
611 return result
612
613
Mario Corchero552be9d2017-10-17 12:35:11 +0100614 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700615 _name_list = [self._mock_new_name]
616 _parent = self._mock_new_parent
617 last = self
618
619 dot = '.'
620 if _name_list == ['()']:
621 dot = ''
622 seen = set()
623 while _parent is not None:
624 last = _parent
625
626 _name_list.append(_parent._mock_new_name + dot)
627 dot = '.'
628 if _parent._mock_new_name == '()':
629 dot = ''
630
631 _parent = _parent._mock_new_parent
632
633 # use ids here so as not to call __hash__ on the mocks
634 if id(_parent) in seen:
635 break
636 seen.add(id(_parent))
637
638 _name_list = list(reversed(_name_list))
639 _first = last._mock_name or 'mock'
640 if len(_name_list) > 1:
641 if _name_list[1] not in ('()', '().'):
642 _first += '.'
643 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100644 return ''.join(_name_list)
645
646 def __repr__(self):
647 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700648
649 name_string = ''
650 if name not in ('mock', 'mock.'):
651 name_string = ' name=%r' % name
652
653 spec_string = ''
654 if self._spec_class is not None:
655 spec_string = ' spec=%r'
656 if self._spec_set:
657 spec_string = ' spec_set=%r'
658 spec_string = spec_string % self._spec_class.__name__
659 return "<%s%s%s id='%s'>" % (
660 type(self).__name__,
661 name_string,
662 spec_string,
663 id(self)
664 )
665
666
667 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700668 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100669 if not FILTER_DIR:
670 return object.__dir__(self)
671
Michael Foord345266a2012-03-14 12:24:34 -0700672 extras = self._mock_methods or []
673 from_type = dir(type(self))
674 from_dict = list(self.__dict__)
675
Michael Foord313f85f2012-03-25 18:16:07 +0100676 from_type = [e for e in from_type if not e.startswith('_')]
677 from_dict = [e for e in from_dict if not e.startswith('_') or
678 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700679 return sorted(set(extras + from_type + from_dict +
680 list(self._mock_children)))
681
682
683 def __setattr__(self, name, value):
684 if name in _allowed_names:
685 # property setters go through here
686 return object.__setattr__(self, name, value)
687 elif (self._spec_set and self._mock_methods is not None and
688 name not in self._mock_methods and
689 name not in self.__dict__):
690 raise AttributeError("Mock object has no attribute '%s'" % name)
691 elif name in _unsupported_magics:
692 msg = 'Attempting to set unsupported magic method %r.' % name
693 raise AttributeError(msg)
694 elif name in _all_magics:
695 if self._mock_methods is not None and name not in self._mock_methods:
696 raise AttributeError("Mock object has no attribute '%s'" % name)
697
698 if not _is_instance_mock(value):
699 setattr(type(self), name, _get_method(name, value))
700 original = value
701 value = lambda *args, **kw: original(self, *args, **kw)
702 else:
703 # only set _new_name and not name so that mock_calls is tracked
704 # but not method calls
705 _check_and_set_parent(self, value, None, name)
706 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100707 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700708 elif name == '__class__':
709 self._spec_class = value
710 return
711 else:
712 if _check_and_set_parent(self, value, name, name):
713 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100714
715 if self._mock_sealed and not hasattr(self, name):
716 mock_name = f'{self._extract_mock_name()}.{name}'
717 raise AttributeError(f'Cannot set {mock_name}')
718
Michael Foord345266a2012-03-14 12:24:34 -0700719 return object.__setattr__(self, name, value)
720
721
722 def __delattr__(self, name):
723 if name in _all_magics and name in type(self).__dict__:
724 delattr(type(self), name)
725 if name not in self.__dict__:
726 # for magic methods that are still MagicProxy objects and
727 # not set on the instance itself
728 return
729
730 if name in self.__dict__:
731 object.__delattr__(self, name)
732
733 obj = self._mock_children.get(name, _missing)
734 if obj is _deleted:
735 raise AttributeError(name)
736 if obj is not _missing:
737 del self._mock_children[name]
738 self._mock_children[name] = _deleted
739
740
Michael Foord345266a2012-03-14 12:24:34 -0700741 def _format_mock_call_signature(self, args, kwargs):
742 name = self._mock_name or 'mock'
743 return _format_call_signature(name, args, kwargs)
744
745
746 def _format_mock_failure_message(self, args, kwargs):
747 message = 'Expected call: %s\nActual call: %s'
748 expected_string = self._format_mock_call_signature(args, kwargs)
749 call_args = self.call_args
750 if len(call_args) == 3:
751 call_args = call_args[1:]
752 actual_string = self._format_mock_call_signature(*call_args)
753 return message % (expected_string, actual_string)
754
755
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100756 def _call_matcher(self, _call):
757 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000758 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100759 comparison key suitable for matching with other calls.
760 This is a best effort method which relies on the spec's signature,
761 if available, or falls back on the arguments themselves.
762 """
763 sig = self._spec_signature
764 if sig is not None:
765 if len(_call) == 2:
766 name = ''
767 args, kwargs = _call
768 else:
769 name, args, kwargs = _call
770 try:
771 return name, sig.bind(*args, **kwargs)
772 except TypeError as e:
773 return e.with_traceback(None)
774 else:
775 return _call
776
Kushal Das68290f42014-04-17 01:54:07 +0530777 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530778 """assert that the mock was never called.
779 """
780 self = _mock_self
781 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100782 msg = ("Expected '%s' to not have been called. Called %s times.%s"
783 % (self._mock_name or 'mock',
784 self.call_count,
785 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530786 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100787
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100788 def assert_called(_mock_self):
789 """assert that the mock was called at least once
790 """
791 self = _mock_self
792 if self.call_count == 0:
793 msg = ("Expected '%s' to have been called." %
794 self._mock_name or 'mock')
795 raise AssertionError(msg)
796
797 def assert_called_once(_mock_self):
798 """assert that the mock was called only once.
799 """
800 self = _mock_self
801 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100802 msg = ("Expected '%s' to have been called once. Called %s times.%s"
803 % (self._mock_name or 'mock',
804 self.call_count,
805 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100806 raise AssertionError(msg)
807
Michael Foord345266a2012-03-14 12:24:34 -0700808 def assert_called_with(_mock_self, *args, **kwargs):
809 """assert that the mock was called with the specified arguments.
810
811 Raises an AssertionError if the args and keyword args passed in are
812 different to the last call to the mock."""
813 self = _mock_self
814 if self.call_args is None:
815 expected = self._format_mock_call_signature(args, kwargs)
816 raise AssertionError('Expected call: %s\nNot called' % (expected,))
817
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100818 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700819 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100820 return msg
821 expected = self._call_matcher((args, kwargs))
822 actual = self._call_matcher(self.call_args)
823 if expected != actual:
824 cause = expected if isinstance(expected, Exception) else None
825 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700826
827
828 def assert_called_once_with(_mock_self, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100829 """assert that the mock was called exactly once and that that call was
830 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700831 self = _mock_self
832 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100833 msg = ("Expected '%s' to be called once. Called %s times.%s"
834 % (self._mock_name or 'mock',
835 self.call_count,
836 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700837 raise AssertionError(msg)
838 return self.assert_called_with(*args, **kwargs)
839
840
841 def assert_has_calls(self, calls, any_order=False):
842 """assert the mock has been called with the specified calls.
843 The `mock_calls` list is checked for the calls.
844
845 If `any_order` is False (the default) then the calls must be
846 sequential. There can be extra calls before or after the
847 specified calls.
848
849 If `any_order` is True then the calls can be in any order, but
850 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100851 expected = [self._call_matcher(c) for c in calls]
852 cause = expected if isinstance(expected, Exception) else None
853 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700854 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100855 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700856 raise AssertionError(
Petter Strandmark47d94242018-10-28 21:37:10 +0100857 'Calls not found.\nExpected: %r%s'
858 % (_CallList(calls), self._calls_repr(prefix="Actual"))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100859 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700860 return
861
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100862 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700863
864 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100865 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700866 try:
867 all_calls.remove(kall)
868 except ValueError:
869 not_found.append(kall)
870 if not_found:
871 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400872 '%r does not contain all of %r in its call list, '
873 'found %r instead' % (self._mock_name or 'mock',
874 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100875 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700876
877
878 def assert_any_call(self, *args, **kwargs):
879 """assert the mock has been called with the specified arguments.
880
881 The assert passes if the mock has *ever* been called, unlike
882 `assert_called_with` and `assert_called_once_with` that only pass if
883 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100884 expected = self._call_matcher((args, kwargs))
885 actual = [self._call_matcher(c) for c in self.call_args_list]
886 if expected not in actual:
887 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700888 expected_string = self._format_mock_call_signature(args, kwargs)
889 raise AssertionError(
890 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100891 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700892
893
894 def _get_child_mock(self, **kw):
895 """Create the child mocks for attributes and return value.
896 By default child mocks will be the same type as the parent.
897 Subclasses of Mock may want to override this to customize the way
898 child mocks are made.
899
900 For non-callable mocks the callable variant will be used (rather than
901 any custom subclass)."""
902 _type = type(self)
903 if not issubclass(_type, CallableMixin):
904 if issubclass(_type, NonCallableMagicMock):
905 klass = MagicMock
906 elif issubclass(_type, NonCallableMock) :
907 klass = Mock
908 else:
909 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +0100910
911 if self._mock_sealed:
912 attribute = "." + kw["name"] if "name" in kw else "()"
913 mock_name = self._extract_mock_name() + attribute
914 raise AttributeError(mock_name)
915
Michael Foord345266a2012-03-14 12:24:34 -0700916 return klass(**kw)
917
918
Petter Strandmark47d94242018-10-28 21:37:10 +0100919 def _calls_repr(self, prefix="Calls"):
920 """Renders self.mock_calls as a string.
921
922 Example: "\nCalls: [call(1), call(2)]."
923
924 If self.mock_calls is empty, an empty string is returned. The
925 output will be truncated if very long.
926 """
927 if not self.mock_calls:
928 return ""
929 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
930
931
Michael Foord345266a2012-03-14 12:24:34 -0700932
933def _try_iter(obj):
934 if obj is None:
935 return obj
936 if _is_exception(obj):
937 return obj
938 if _callable(obj):
939 return obj
940 try:
941 return iter(obj)
942 except TypeError:
943 # XXXX backwards compatibility
944 # but this will blow up on first call - so maybe we should fail early?
945 return obj
946
947
948
949class CallableMixin(Base):
950
951 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
952 wraps=None, name=None, spec_set=None, parent=None,
953 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
954 self.__dict__['_mock_return_value'] = return_value
955
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000956 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700957 spec, wraps, name, spec_set, parent,
958 _spec_state, _new_name, _new_parent, **kwargs
959 )
960
961 self.side_effect = side_effect
962
963
964 def _mock_check_sig(self, *args, **kwargs):
965 # stub method that can be replaced with one with a specific signature
966 pass
967
968
969 def __call__(_mock_self, *args, **kwargs):
970 # can't use self in-case a function / method we are mocking uses self
971 # in the signature
972 _mock_self._mock_check_sig(*args, **kwargs)
973 return _mock_self._mock_call(*args, **kwargs)
974
975
976 def _mock_call(_mock_self, *args, **kwargs):
977 self = _mock_self
978 self.called = True
979 self.call_count += 1
Michael Foord345266a2012-03-14 12:24:34 -0700980 _new_name = self._mock_new_name
981 _new_parent = self._mock_new_parent
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100982
983 _call = _Call((args, kwargs), two=True)
984 self.call_args = _call
985 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700986 self.mock_calls.append(_Call(('', args, kwargs)))
987
988 seen = set()
989 skip_next_dot = _new_name == '()'
990 do_method_calls = self._mock_parent is not None
991 name = self._mock_name
992 while _new_parent is not None:
993 this_mock_call = _Call((_new_name, args, kwargs))
994 if _new_parent._mock_new_name:
995 dot = '.'
996 if skip_next_dot:
997 dot = ''
998
999 skip_next_dot = False
1000 if _new_parent._mock_new_name == '()':
1001 skip_next_dot = True
1002
1003 _new_name = _new_parent._mock_new_name + dot + _new_name
1004
1005 if do_method_calls:
1006 if _new_name == name:
1007 this_method_call = this_mock_call
1008 else:
1009 this_method_call = _Call((name, args, kwargs))
1010 _new_parent.method_calls.append(this_method_call)
1011
1012 do_method_calls = _new_parent._mock_parent is not None
1013 if do_method_calls:
1014 name = _new_parent._mock_name + '.' + name
1015
1016 _new_parent.mock_calls.append(this_mock_call)
1017 _new_parent = _new_parent._mock_new_parent
1018
1019 # use ids here so as not to call __hash__ on the mocks
1020 _new_parent_id = id(_new_parent)
1021 if _new_parent_id in seen:
1022 break
1023 seen.add(_new_parent_id)
1024
1025 ret_val = DEFAULT
1026 effect = self.side_effect
1027 if effect is not None:
1028 if _is_exception(effect):
1029 raise effect
1030
1031 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001032 result = next(effect)
1033 if _is_exception(result):
1034 raise result
Andrew Svetlov8b2cd752013-04-07 16:42:24 +03001035 if result is DEFAULT:
1036 result = self.return_value
Michael Foord2cd48732012-04-21 15:52:11 +01001037 return result
Michael Foord345266a2012-03-14 12:24:34 -07001038
1039 ret_val = effect(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001040
1041 if (self._mock_wraps is not None and
1042 self._mock_return_value is DEFAULT):
1043 return self._mock_wraps(*args, **kwargs)
1044 if ret_val is DEFAULT:
1045 ret_val = self.return_value
1046 return ret_val
1047
1048
1049
1050class Mock(CallableMixin, NonCallableMock):
1051 """
1052 Create a new `Mock` object. `Mock` takes several optional arguments
1053 that specify the behaviour of the Mock object:
1054
1055 * `spec`: This can be either a list of strings or an existing object (a
1056 class or instance) that acts as the specification for the mock object. If
1057 you pass in an object then a list of strings is formed by calling dir on
1058 the object (excluding unsupported magic attributes and methods). Accessing
1059 any attribute not in this list will raise an `AttributeError`.
1060
1061 If `spec` is an object (rather than a list of strings) then
1062 `mock.__class__` returns the class of the spec object. This allows mocks
1063 to pass `isinstance` tests.
1064
1065 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1066 or get an attribute on the mock that isn't on the object passed as
1067 `spec_set` will raise an `AttributeError`.
1068
1069 * `side_effect`: A function to be called whenever the Mock is called. See
1070 the `side_effect` attribute. Useful for raising exceptions or
1071 dynamically changing return values. The function is called with the same
1072 arguments as the mock, and unless it returns `DEFAULT`, the return
1073 value of this function is used as the return value.
1074
Michael Foord2cd48732012-04-21 15:52:11 +01001075 If `side_effect` is an iterable then each call to the mock will return
1076 the next value from the iterable. If any of the members of the iterable
1077 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001078
Michael Foord345266a2012-03-14 12:24:34 -07001079 * `return_value`: The value returned when the mock is called. By default
1080 this is a new Mock (created on first access). See the
1081 `return_value` attribute.
1082
Michael Foord0682a0c2012-04-13 20:51:20 +01001083 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1084 calling the Mock will pass the call through to the wrapped object
1085 (returning the real result). Attribute access on the mock will return a
1086 Mock object that wraps the corresponding attribute of the wrapped object
1087 (so attempting to access an attribute that doesn't exist will raise an
1088 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001089
1090 If the mock has an explicit `return_value` set then calls are not passed
1091 to the wrapped object and the `return_value` is returned instead.
1092
1093 * `name`: If the mock has a name then it will be used in the repr of the
1094 mock. This can be useful for debugging. The name is propagated to child
1095 mocks.
1096
1097 Mocks can also be called with arbitrary keyword arguments. These will be
1098 used to set attributes on the mock after it is created.
1099 """
1100
1101
1102
1103def _dot_lookup(thing, comp, import_path):
1104 try:
1105 return getattr(thing, comp)
1106 except AttributeError:
1107 __import__(import_path)
1108 return getattr(thing, comp)
1109
1110
1111def _importer(target):
1112 components = target.split('.')
1113 import_path = components.pop(0)
1114 thing = __import__(import_path)
1115
1116 for comp in components:
1117 import_path += ".%s" % comp
1118 thing = _dot_lookup(thing, comp, import_path)
1119 return thing
1120
1121
1122def _is_started(patcher):
1123 # XXXX horrible
1124 return hasattr(patcher, 'is_local')
1125
1126
1127class _patch(object):
1128
1129 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001130 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001131
1132 def __init__(
1133 self, getter, attribute, new, spec, create,
1134 spec_set, autospec, new_callable, kwargs
1135 ):
1136 if new_callable is not None:
1137 if new is not DEFAULT:
1138 raise ValueError(
1139 "Cannot use 'new' and 'new_callable' together"
1140 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001141 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001142 raise ValueError(
1143 "Cannot use 'autospec' and 'new_callable' together"
1144 )
1145
1146 self.getter = getter
1147 self.attribute = attribute
1148 self.new = new
1149 self.new_callable = new_callable
1150 self.spec = spec
1151 self.create = create
1152 self.has_local = False
1153 self.spec_set = spec_set
1154 self.autospec = autospec
1155 self.kwargs = kwargs
1156 self.additional_patchers = []
1157
1158
1159 def copy(self):
1160 patcher = _patch(
1161 self.getter, self.attribute, self.new, self.spec,
1162 self.create, self.spec_set,
1163 self.autospec, self.new_callable, self.kwargs
1164 )
1165 patcher.attribute_name = self.attribute_name
1166 patcher.additional_patchers = [
1167 p.copy() for p in self.additional_patchers
1168 ]
1169 return patcher
1170
1171
1172 def __call__(self, func):
1173 if isinstance(func, type):
1174 return self.decorate_class(func)
1175 return self.decorate_callable(func)
1176
1177
1178 def decorate_class(self, klass):
1179 for attr in dir(klass):
1180 if not attr.startswith(patch.TEST_PREFIX):
1181 continue
1182
1183 attr_value = getattr(klass, attr)
1184 if not hasattr(attr_value, "__call__"):
1185 continue
1186
1187 patcher = self.copy()
1188 setattr(klass, attr, patcher(attr_value))
1189 return klass
1190
1191
1192 def decorate_callable(self, func):
1193 if hasattr(func, 'patchings'):
1194 func.patchings.append(self)
1195 return func
1196
1197 @wraps(func)
1198 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001199 extra_args = []
1200 entered_patchers = []
1201
Michael Foord50a8c0e2012-03-25 18:57:58 +01001202 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001203 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001204 for patching in patched.patchings:
1205 arg = patching.__enter__()
1206 entered_patchers.append(patching)
1207 if patching.attribute_name is not None:
1208 keywargs.update(arg)
1209 elif patching.new is DEFAULT:
1210 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001211
Michael Foordd7c65e22012-03-14 14:56:54 -07001212 args += tuple(extra_args)
1213 return func(*args, **keywargs)
1214 except:
1215 if (patching not in entered_patchers and
1216 _is_started(patching)):
1217 # the patcher may have been started, but an exception
1218 # raised whilst entering one of its additional_patchers
1219 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001220 # Pass the exception to __exit__
1221 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001222 # re-raise the exception
1223 raise
Michael Foord345266a2012-03-14 12:24:34 -07001224 finally:
1225 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001226 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001227
1228 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001229 return patched
1230
1231
1232 def get_original(self):
1233 target = self.getter()
1234 name = self.attribute
1235
1236 original = DEFAULT
1237 local = False
1238
1239 try:
1240 original = target.__dict__[name]
1241 except (AttributeError, KeyError):
1242 original = getattr(target, name, DEFAULT)
1243 else:
1244 local = True
1245
Michael Foordfddcfa22014-04-14 16:25:20 -04001246 if name in _builtins and isinstance(target, ModuleType):
1247 self.create = True
1248
Michael Foord345266a2012-03-14 12:24:34 -07001249 if not self.create and original is DEFAULT:
1250 raise AttributeError(
1251 "%s does not have the attribute %r" % (target, name)
1252 )
1253 return original, local
1254
1255
1256 def __enter__(self):
1257 """Perform the patch."""
1258 new, spec, spec_set = self.new, self.spec, self.spec_set
1259 autospec, kwargs = self.autospec, self.kwargs
1260 new_callable = self.new_callable
1261 self.target = self.getter()
1262
Michael Foord50a8c0e2012-03-25 18:57:58 +01001263 # normalise False to None
1264 if spec is False:
1265 spec = None
1266 if spec_set is False:
1267 spec_set = None
1268 if autospec is False:
1269 autospec = None
1270
1271 if spec is not None and autospec is not None:
1272 raise TypeError("Can't specify spec and autospec")
1273 if ((spec is not None or autospec is not None) and
1274 spec_set not in (True, None)):
1275 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1276
Michael Foord345266a2012-03-14 12:24:34 -07001277 original, local = self.get_original()
1278
Michael Foord50a8c0e2012-03-25 18:57:58 +01001279 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001280 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001281 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001282 # set spec to the object we are replacing
1283 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001284 if spec_set is True:
1285 spec_set = original
1286 spec = None
1287 elif spec is not None:
1288 if spec_set is True:
1289 spec_set = spec
1290 spec = None
1291 elif spec_set is True:
1292 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001293
Michael Foord50a8c0e2012-03-25 18:57:58 +01001294 if spec is not None or spec_set is not None:
1295 if original is DEFAULT:
1296 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001297 if isinstance(original, type):
1298 # If we're patching out a class and there is a spec
1299 inherit = True
1300
1301 Klass = MagicMock
1302 _kwargs = {}
1303 if new_callable is not None:
1304 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001305 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001306 this_spec = spec
1307 if spec_set is not None:
1308 this_spec = spec_set
1309 if _is_list(this_spec):
1310 not_callable = '__call__' not in this_spec
1311 else:
1312 not_callable = not callable(this_spec)
1313 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001314 Klass = NonCallableMagicMock
1315
1316 if spec is not None:
1317 _kwargs['spec'] = spec
1318 if spec_set is not None:
1319 _kwargs['spec_set'] = spec_set
1320
1321 # add a name to mocks
1322 if (isinstance(Klass, type) and
1323 issubclass(Klass, NonCallableMock) and self.attribute):
1324 _kwargs['name'] = self.attribute
1325
1326 _kwargs.update(kwargs)
1327 new = Klass(**_kwargs)
1328
1329 if inherit and _is_instance_mock(new):
1330 # we can only tell if the instance should be callable if the
1331 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001332 this_spec = spec
1333 if spec_set is not None:
1334 this_spec = spec_set
1335 if (not _is_list(this_spec) and not
1336 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001337 Klass = NonCallableMagicMock
1338
1339 _kwargs.pop('name')
1340 new.return_value = Klass(_new_parent=new, _new_name='()',
1341 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001342 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001343 # spec is ignored, new *must* be default, spec_set is treated
1344 # as a boolean. Should we check spec is not None and that spec_set
1345 # is a bool?
1346 if new is not DEFAULT:
1347 raise TypeError(
1348 "autospec creates the mock for you. Can't specify "
1349 "autospec and new."
1350 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001351 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001352 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001353 spec_set = bool(spec_set)
1354 if autospec is True:
1355 autospec = original
1356
1357 new = create_autospec(autospec, spec_set=spec_set,
1358 _name=self.attribute, **kwargs)
1359 elif kwargs:
1360 # can't set keyword args when we aren't creating the mock
1361 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1362 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1363
1364 new_attr = new
1365
1366 self.temp_original = original
1367 self.is_local = local
1368 setattr(self.target, self.attribute, new_attr)
1369 if self.attribute_name is not None:
1370 extra_args = {}
1371 if self.new is DEFAULT:
1372 extra_args[self.attribute_name] = new
1373 for patching in self.additional_patchers:
1374 arg = patching.__enter__()
1375 if patching.new is DEFAULT:
1376 extra_args.update(arg)
1377 return extra_args
1378
1379 return new
1380
1381
Michael Foord50a8c0e2012-03-25 18:57:58 +01001382 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001383 """Undo the patch."""
1384 if not _is_started(self):
1385 raise RuntimeError('stop called on unstarted patcher')
1386
1387 if self.is_local and self.temp_original is not DEFAULT:
1388 setattr(self.target, self.attribute, self.temp_original)
1389 else:
1390 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001391 if not self.create and (not hasattr(self.target, self.attribute) or
1392 self.attribute in ('__doc__', '__module__',
1393 '__defaults__', '__annotations__',
1394 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001395 # needed for proxy objects like django settings
1396 setattr(self.target, self.attribute, self.temp_original)
1397
1398 del self.temp_original
1399 del self.is_local
1400 del self.target
1401 for patcher in reversed(self.additional_patchers):
1402 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001403 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001404
Michael Foordf7c41582012-06-10 20:36:32 +01001405
1406 def start(self):
1407 """Activate a patch, returning any created mock."""
1408 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001409 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001410 return result
1411
1412
1413 def stop(self):
1414 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001415 try:
1416 self._active_patches.remove(self)
1417 except ValueError:
1418 # If the patch hasn't been started this will fail
1419 pass
1420
Michael Foordf7c41582012-06-10 20:36:32 +01001421 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001422
1423
1424
1425def _get_target(target):
1426 try:
1427 target, attribute = target.rsplit('.', 1)
1428 except (TypeError, ValueError):
1429 raise TypeError("Need a valid target to patch. You supplied: %r" %
1430 (target,))
1431 getter = lambda: _importer(target)
1432 return getter, attribute
1433
1434
1435def _patch_object(
1436 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001437 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001438 new_callable=None, **kwargs
1439 ):
1440 """
Michael Foord345266a2012-03-14 12:24:34 -07001441 patch the named member (`attribute`) on an object (`target`) with a mock
1442 object.
1443
1444 `patch.object` can be used as a decorator, class decorator or a context
1445 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1446 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1447 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1448 the mock object it creates.
1449
1450 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1451 for choosing which methods to wrap.
1452 """
1453 getter = lambda: target
1454 return _patch(
1455 getter, attribute, new, spec, create,
1456 spec_set, autospec, new_callable, kwargs
1457 )
1458
1459
Michael Foord50a8c0e2012-03-25 18:57:58 +01001460def _patch_multiple(target, spec=None, create=False, spec_set=None,
1461 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001462 """Perform multiple patches in a single call. It takes the object to be
1463 patched (either as an object or a string to fetch the object by importing)
1464 and keyword arguments for the patches::
1465
1466 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1467 ...
1468
1469 Use `DEFAULT` as the value if you want `patch.multiple` to create
1470 mocks for you. In this case the created mocks are passed into a decorated
1471 function by keyword, and a dictionary is returned when `patch.multiple` is
1472 used as a context manager.
1473
1474 `patch.multiple` can be used as a decorator, class decorator or a context
1475 manager. The arguments `spec`, `spec_set`, `create`,
1476 `autospec` and `new_callable` have the same meaning as for `patch`. These
1477 arguments will be applied to *all* patches done by `patch.multiple`.
1478
1479 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1480 for choosing which methods to wrap.
1481 """
1482 if type(target) is str:
1483 getter = lambda: _importer(target)
1484 else:
1485 getter = lambda: target
1486
1487 if not kwargs:
1488 raise ValueError(
1489 'Must supply at least one keyword argument with patch.multiple'
1490 )
1491 # need to wrap in a list for python 3, where items is a view
1492 items = list(kwargs.items())
1493 attribute, new = items[0]
1494 patcher = _patch(
1495 getter, attribute, new, spec, create, spec_set,
1496 autospec, new_callable, {}
1497 )
1498 patcher.attribute_name = attribute
1499 for attribute, new in items[1:]:
1500 this_patcher = _patch(
1501 getter, attribute, new, spec, create, spec_set,
1502 autospec, new_callable, {}
1503 )
1504 this_patcher.attribute_name = attribute
1505 patcher.additional_patchers.append(this_patcher)
1506 return patcher
1507
1508
1509def patch(
1510 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001511 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001512 ):
1513 """
1514 `patch` acts as a function decorator, class decorator or a context
1515 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001516 is patched with a `new` object. When the function/with statement exits
1517 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001518
Michael Foord54b3db82012-03-28 15:08:08 +01001519 If `new` is omitted, then the target is replaced with a
1520 `MagicMock`. If `patch` is used as a decorator and `new` is
1521 omitted, the created mock is passed in as an extra argument to the
1522 decorated function. If `patch` is used as a context manager the created
1523 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001524
Michael Foord54b3db82012-03-28 15:08:08 +01001525 `target` should be a string in the form `'package.module.ClassName'`. The
1526 `target` is imported and the specified object replaced with the `new`
1527 object, so the `target` must be importable from the environment you are
1528 calling `patch` from. The target is imported when the decorated function
1529 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001530
1531 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1532 if patch is creating one for you.
1533
1534 In addition you can pass `spec=True` or `spec_set=True`, which causes
1535 patch to pass in the object being mocked as the spec/spec_set object.
1536
1537 `new_callable` allows you to specify a different class, or callable object,
1538 that will be called to create the `new` object. By default `MagicMock` is
1539 used.
1540
1541 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001542 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001543 All attributes of the mock will also have the spec of the corresponding
1544 attribute of the object being replaced. Methods and functions being
1545 mocked will have their arguments checked and will raise a `TypeError` if
1546 they are called with the wrong signature. For mocks replacing a class,
1547 their return value (the 'instance') will have the same spec as the class.
1548
1549 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1550 arbitrary object as the spec instead of the one being replaced.
1551
1552 By default `patch` will fail to replace attributes that don't exist. If
1553 you pass in `create=True`, and the attribute doesn't exist, patch will
1554 create the attribute for you when the patched function is called, and
1555 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001556 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001557 default because it can be dangerous. With it switched on you can write
1558 passing tests against APIs that don't actually exist!
1559
1560 Patch can be used as a `TestCase` class decorator. It works by
1561 decorating each test method in the class. This reduces the boilerplate
1562 code when your test methods share a common patchings set. `patch` finds
1563 tests by looking for method names that start with `patch.TEST_PREFIX`.
1564 By default this is `test`, which matches the way `unittest` finds tests.
1565 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1566
1567 Patch can be used as a context manager, with the with statement. Here the
1568 patching applies to the indented block after the with statement. If you
1569 use "as" then the patched object will be bound to the name after the
1570 "as"; very useful if `patch` is creating a mock object for you.
1571
1572 `patch` takes arbitrary keyword arguments. These will be passed to
1573 the `Mock` (or `new_callable`) on construction.
1574
1575 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1576 available for alternate use-cases.
1577 """
1578 getter, attribute = _get_target(target)
1579 return _patch(
1580 getter, attribute, new, spec, create,
1581 spec_set, autospec, new_callable, kwargs
1582 )
1583
1584
1585class _patch_dict(object):
1586 """
1587 Patch a dictionary, or dictionary like object, and restore the dictionary
1588 to its original state after the test.
1589
1590 `in_dict` can be a dictionary or a mapping like container. If it is a
1591 mapping then it must at least support getting, setting and deleting items
1592 plus iterating over keys.
1593
1594 `in_dict` can also be a string specifying the name of the dictionary, which
1595 will then be fetched by importing it.
1596
1597 `values` can be a dictionary of values to set in the dictionary. `values`
1598 can also be an iterable of `(key, value)` pairs.
1599
1600 If `clear` is True then the dictionary will be cleared before the new
1601 values are set.
1602
1603 `patch.dict` can also be called with arbitrary keyword arguments to set
1604 values in the dictionary::
1605
1606 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1607 ...
1608
1609 `patch.dict` can be used as a context manager, decorator or class
1610 decorator. When used as a class decorator `patch.dict` honours
1611 `patch.TEST_PREFIX` for choosing which methods to wrap.
1612 """
1613
1614 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1615 if isinstance(in_dict, str):
1616 in_dict = _importer(in_dict)
1617 self.in_dict = in_dict
1618 # support any argument supported by dict(...) constructor
1619 self.values = dict(values)
1620 self.values.update(kwargs)
1621 self.clear = clear
1622 self._original = None
1623
1624
1625 def __call__(self, f):
1626 if isinstance(f, type):
1627 return self.decorate_class(f)
1628 @wraps(f)
1629 def _inner(*args, **kw):
1630 self._patch_dict()
1631 try:
1632 return f(*args, **kw)
1633 finally:
1634 self._unpatch_dict()
1635
1636 return _inner
1637
1638
1639 def decorate_class(self, klass):
1640 for attr in dir(klass):
1641 attr_value = getattr(klass, attr)
1642 if (attr.startswith(patch.TEST_PREFIX) and
1643 hasattr(attr_value, "__call__")):
1644 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1645 decorated = decorator(attr_value)
1646 setattr(klass, attr, decorated)
1647 return klass
1648
1649
1650 def __enter__(self):
1651 """Patch the dict."""
1652 self._patch_dict()
1653
1654
1655 def _patch_dict(self):
1656 values = self.values
1657 in_dict = self.in_dict
1658 clear = self.clear
1659
1660 try:
1661 original = in_dict.copy()
1662 except AttributeError:
1663 # dict like object with no copy method
1664 # must support iteration over keys
1665 original = {}
1666 for key in in_dict:
1667 original[key] = in_dict[key]
1668 self._original = original
1669
1670 if clear:
1671 _clear_dict(in_dict)
1672
1673 try:
1674 in_dict.update(values)
1675 except AttributeError:
1676 # dict like object with no update method
1677 for key in values:
1678 in_dict[key] = values[key]
1679
1680
1681 def _unpatch_dict(self):
1682 in_dict = self.in_dict
1683 original = self._original
1684
1685 _clear_dict(in_dict)
1686
1687 try:
1688 in_dict.update(original)
1689 except AttributeError:
1690 for key in original:
1691 in_dict[key] = original[key]
1692
1693
1694 def __exit__(self, *args):
1695 """Unpatch the dict."""
1696 self._unpatch_dict()
1697 return False
1698
1699 start = __enter__
1700 stop = __exit__
1701
1702
1703def _clear_dict(in_dict):
1704 try:
1705 in_dict.clear()
1706 except AttributeError:
1707 keys = list(in_dict)
1708 for key in keys:
1709 del in_dict[key]
1710
1711
Michael Foordf7c41582012-06-10 20:36:32 +01001712def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001713 """Stop all active patches. LIFO to unroll nested patches."""
1714 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001715 patch.stop()
1716
1717
Michael Foord345266a2012-03-14 12:24:34 -07001718patch.object = _patch_object
1719patch.dict = _patch_dict
1720patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001721patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001722patch.TEST_PREFIX = 'test'
1723
1724magic_methods = (
1725 "lt le gt ge eq ne "
1726 "getitem setitem delitem "
1727 "len contains iter "
1728 "hash str sizeof "
1729 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001730 # we added divmod and rdivmod here instead of numerics
1731 # because there is no idivmod
1732 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001733 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001734 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001735 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001736 "fspath "
Michael Foord345266a2012-03-14 12:24:34 -07001737)
1738
Michael Foordd2623d72014-04-14 11:23:48 -04001739numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001740 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001741)
Michael Foord345266a2012-03-14 12:24:34 -07001742inplace = ' '.join('i%s' % n for n in numerics.split())
1743right = ' '.join('r%s' % n for n in numerics.split())
1744
1745# not including __prepare__, __instancecheck__, __subclasscheck__
1746# (as they are metaclass methods)
1747# __del__ is not supported at all as it causes problems if it exists
1748
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001749_non_defaults = {
1750 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1751 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1752 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1753 '__repr__', '__dir__', '__subclasses__', '__format__',
Serhiy Storchaka5943ea72016-06-19 18:30:43 +03001754 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001755}
Michael Foord345266a2012-03-14 12:24:34 -07001756
1757
1758def _get_method(name, func):
1759 "Turns a callable object (like a mock) into a real function"
1760 def method(self, *args, **kw):
1761 return func(self, *args, **kw)
1762 method.__name__ = name
1763 return method
1764
1765
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001766_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001767 '__%s__' % method for method in
1768 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001769}
Michael Foord345266a2012-03-14 12:24:34 -07001770
1771_all_magics = _magics | _non_defaults
1772
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001773_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001774 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001775 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001776 '__instancecheck__', '__subclasscheck__',
1777 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001778}
Michael Foord345266a2012-03-14 12:24:34 -07001779
1780_calculate_return_value = {
1781 '__hash__': lambda self: object.__hash__(self),
1782 '__str__': lambda self: object.__str__(self),
1783 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001784 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001785}
1786
1787_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001788 '__lt__': NotImplemented,
1789 '__gt__': NotImplemented,
1790 '__le__': NotImplemented,
1791 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001792 '__int__': 1,
1793 '__contains__': False,
1794 '__len__': 0,
1795 '__exit__': False,
1796 '__complex__': 1j,
1797 '__float__': 1.0,
1798 '__bool__': True,
1799 '__index__': 1,
1800}
1801
1802
1803def _get_eq(self):
1804 def __eq__(other):
1805 ret_val = self.__eq__._mock_return_value
1806 if ret_val is not DEFAULT:
1807 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001808 if self is other:
1809 return True
1810 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001811 return __eq__
1812
1813def _get_ne(self):
1814 def __ne__(other):
1815 if self.__ne__._mock_return_value is not DEFAULT:
1816 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001817 if self is other:
1818 return False
1819 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001820 return __ne__
1821
1822def _get_iter(self):
1823 def __iter__():
1824 ret_val = self.__iter__._mock_return_value
1825 if ret_val is DEFAULT:
1826 return iter([])
1827 # if ret_val was already an iterator, then calling iter on it should
1828 # return the iterator unchanged
1829 return iter(ret_val)
1830 return __iter__
1831
1832_side_effect_methods = {
1833 '__eq__': _get_eq,
1834 '__ne__': _get_ne,
1835 '__iter__': _get_iter,
1836}
1837
1838
1839
1840def _set_return_value(mock, method, name):
1841 fixed = _return_values.get(name, DEFAULT)
1842 if fixed is not DEFAULT:
1843 method.return_value = fixed
1844 return
1845
1846 return_calulator = _calculate_return_value.get(name)
1847 if return_calulator is not None:
1848 try:
1849 return_value = return_calulator(mock)
1850 except AttributeError:
1851 # XXXX why do we return AttributeError here?
1852 # set it as a side_effect instead?
1853 return_value = AttributeError(name)
1854 method.return_value = return_value
1855 return
1856
1857 side_effector = _side_effect_methods.get(name)
1858 if side_effector is not None:
1859 method.side_effect = side_effector(mock)
1860
1861
1862
1863class MagicMixin(object):
1864 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001865 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001866 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001867 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001868
1869
1870 def _mock_set_magics(self):
1871 these_magics = _magics
1872
Łukasz Langaa468db92015-04-13 23:12:42 -07001873 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001874 these_magics = _magics.intersection(self._mock_methods)
1875
1876 remove_magics = set()
1877 remove_magics = _magics - these_magics
1878
1879 for entry in remove_magics:
1880 if entry in type(self).__dict__:
1881 # remove unneeded magic methods
1882 delattr(self, entry)
1883
1884 # don't overwrite existing attributes if called a second time
1885 these_magics = these_magics - set(type(self).__dict__)
1886
1887 _type = type(self)
1888 for entry in these_magics:
1889 setattr(_type, entry, MagicProxy(entry, self))
1890
1891
1892
1893class NonCallableMagicMock(MagicMixin, NonCallableMock):
1894 """A version of `MagicMock` that isn't callable."""
1895 def mock_add_spec(self, spec, spec_set=False):
1896 """Add a spec to a mock. `spec` can either be an object or a
1897 list of strings. Only attributes on the `spec` can be fetched as
1898 attributes from the mock.
1899
1900 If `spec_set` is True then only attributes on the spec can be set."""
1901 self._mock_add_spec(spec, spec_set)
1902 self._mock_set_magics()
1903
1904
1905
1906class MagicMock(MagicMixin, Mock):
1907 """
1908 MagicMock is a subclass of Mock with default implementations
1909 of most of the magic methods. You can use MagicMock without having to
1910 configure the magic methods yourself.
1911
1912 If you use the `spec` or `spec_set` arguments then *only* magic
1913 methods that exist in the spec will be created.
1914
1915 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1916 """
1917 def mock_add_spec(self, spec, spec_set=False):
1918 """Add a spec to a mock. `spec` can either be an object or a
1919 list of strings. Only attributes on the `spec` can be fetched as
1920 attributes from the mock.
1921
1922 If `spec_set` is True then only attributes on the spec can be set."""
1923 self._mock_add_spec(spec, spec_set)
1924 self._mock_set_magics()
1925
1926
1927
1928class MagicProxy(object):
1929 def __init__(self, name, parent):
1930 self.name = name
1931 self.parent = parent
1932
1933 def __call__(self, *args, **kwargs):
1934 m = self.create_mock()
1935 return m(*args, **kwargs)
1936
1937 def create_mock(self):
1938 entry = self.name
1939 parent = self.parent
1940 m = parent._get_child_mock(name=entry, _new_name=entry,
1941 _new_parent=parent)
1942 setattr(parent, entry, m)
1943 _set_return_value(parent, m, entry)
1944 return m
1945
1946 def __get__(self, obj, _type=None):
1947 return self.create_mock()
1948
1949
1950
1951class _ANY(object):
1952 "A helper object that compares equal to everything."
1953
1954 def __eq__(self, other):
1955 return True
1956
1957 def __ne__(self, other):
1958 return False
1959
1960 def __repr__(self):
1961 return '<ANY>'
1962
1963ANY = _ANY()
1964
1965
1966
1967def _format_call_signature(name, args, kwargs):
1968 message = '%s(%%s)' % name
1969 formatted_args = ''
1970 args_string = ', '.join([repr(arg) for arg in args])
1971 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301972 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001973 ])
1974 if args_string:
1975 formatted_args = args_string
1976 if kwargs_string:
1977 if formatted_args:
1978 formatted_args += ', '
1979 formatted_args += kwargs_string
1980
1981 return message % formatted_args
1982
1983
1984
1985class _Call(tuple):
1986 """
1987 A tuple for holding the results of a call to a mock, either in the form
1988 `(args, kwargs)` or `(name, args, kwargs)`.
1989
1990 If args or kwargs are empty then a call tuple will compare equal to
1991 a tuple without those values. This makes comparisons less verbose::
1992
1993 _Call(('name', (), {})) == ('name',)
1994 _Call(('name', (1,), {})) == ('name', (1,))
1995 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1996
1997 The `_Call` object provides a useful shortcut for comparing with call::
1998
1999 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2000 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2001
2002 If the _Call has no name then it will match any name.
2003 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002004 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002005 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002006 args = ()
2007 kwargs = {}
2008 _len = len(value)
2009 if _len == 3:
2010 name, args, kwargs = value
2011 elif _len == 2:
2012 first, second = value
2013 if isinstance(first, str):
2014 name = first
2015 if isinstance(second, tuple):
2016 args = second
2017 else:
2018 kwargs = second
2019 else:
2020 args, kwargs = first, second
2021 elif _len == 1:
2022 value, = value
2023 if isinstance(value, str):
2024 name = value
2025 elif isinstance(value, tuple):
2026 args = value
2027 else:
2028 kwargs = value
2029
2030 if two:
2031 return tuple.__new__(cls, (args, kwargs))
2032
2033 return tuple.__new__(cls, (name, args, kwargs))
2034
2035
2036 def __init__(self, value=(), name=None, parent=None, two=False,
2037 from_kall=True):
2038 self.name = name
2039 self.parent = parent
2040 self.from_kall = from_kall
2041
2042
2043 def __eq__(self, other):
2044 if other is ANY:
2045 return True
2046 try:
2047 len_other = len(other)
2048 except TypeError:
2049 return False
2050
2051 self_name = ''
2052 if len(self) == 2:
2053 self_args, self_kwargs = self
2054 else:
2055 self_name, self_args, self_kwargs = self
2056
2057 other_name = ''
2058 if len_other == 0:
2059 other_args, other_kwargs = (), {}
2060 elif len_other == 3:
2061 other_name, other_args, other_kwargs = other
2062 elif len_other == 1:
2063 value, = other
2064 if isinstance(value, tuple):
2065 other_args = value
2066 other_kwargs = {}
2067 elif isinstance(value, str):
2068 other_name = value
2069 other_args, other_kwargs = (), {}
2070 else:
2071 other_args = ()
2072 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002073 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002074 # could be (name, args) or (name, kwargs) or (args, kwargs)
2075 first, second = other
2076 if isinstance(first, str):
2077 other_name = first
2078 if isinstance(second, tuple):
2079 other_args, other_kwargs = second, {}
2080 else:
2081 other_args, other_kwargs = (), second
2082 else:
2083 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002084 else:
2085 return False
Michael Foord345266a2012-03-14 12:24:34 -07002086
2087 if self_name and other_name != self_name:
2088 return False
2089
2090 # this order is important for ANY to work!
2091 return (other_args, other_kwargs) == (self_args, self_kwargs)
2092
2093
Berker Peksagce913872016-03-28 00:30:02 +03002094 __ne__ = object.__ne__
2095
2096
Michael Foord345266a2012-03-14 12:24:34 -07002097 def __call__(self, *args, **kwargs):
2098 if self.name is None:
2099 return _Call(('', args, kwargs), name='()')
2100
2101 name = self.name + '()'
2102 return _Call((self.name, args, kwargs), name=name, parent=self)
2103
2104
2105 def __getattr__(self, attr):
2106 if self.name is None:
2107 return _Call(name=attr, from_kall=False)
2108 name = '%s.%s' % (self.name, attr)
2109 return _Call(name=name, parent=self, from_kall=False)
2110
2111
Kushal Dasa37b9582014-09-16 18:33:37 +05302112 def count(self, *args, **kwargs):
2113 return self.__getattr__('count')(*args, **kwargs)
2114
2115 def index(self, *args, **kwargs):
2116 return self.__getattr__('index')(*args, **kwargs)
2117
Michael Foord345266a2012-03-14 12:24:34 -07002118 def __repr__(self):
2119 if not self.from_kall:
2120 name = self.name or 'call'
2121 if name.startswith('()'):
2122 name = 'call%s' % name
2123 return name
2124
2125 if len(self) == 2:
2126 name = 'call'
2127 args, kwargs = self
2128 else:
2129 name, args, kwargs = self
2130 if not name:
2131 name = 'call'
2132 elif not name.startswith('()'):
2133 name = 'call.%s' % name
2134 else:
2135 name = 'call%s' % name
2136 return _format_call_signature(name, args, kwargs)
2137
2138
2139 def call_list(self):
2140 """For a call object that represents multiple calls, `call_list`
2141 returns a list of all the intermediate calls as well as the
2142 final call."""
2143 vals = []
2144 thing = self
2145 while thing is not None:
2146 if thing.from_kall:
2147 vals.append(thing)
2148 thing = thing.parent
2149 return _CallList(reversed(vals))
2150
2151
2152call = _Call(from_kall=False)
2153
2154
2155
2156def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2157 _name=None, **kwargs):
2158 """Create a mock object using another object as a spec. Attributes on the
2159 mock will use the corresponding attribute on the `spec` object as their
2160 spec.
2161
2162 Functions or methods being mocked will have their arguments checked
2163 to check that they are called with the correct signature.
2164
2165 If `spec_set` is True then attempting to set attributes that don't exist
2166 on the spec object will raise an `AttributeError`.
2167
2168 If a class is used as a spec then the return value of the mock (the
2169 instance of the class) will have the same spec. You can use a class as the
2170 spec for an instance object by passing `instance=True`. The returned mock
2171 will only be callable if instances of the mock are callable.
2172
2173 `create_autospec` also takes arbitrary keyword arguments that are passed to
2174 the constructor of the created mock."""
2175 if _is_list(spec):
2176 # can't pass a list instance to the mock constructor as it will be
2177 # interpreted as a list of strings
2178 spec = type(spec)
2179
2180 is_type = isinstance(spec, type)
2181
2182 _kwargs = {'spec': spec}
2183 if spec_set:
2184 _kwargs = {'spec_set': spec}
2185 elif spec is None:
2186 # None we mock with a normal mock without a spec
2187 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002188 if _kwargs and instance:
2189 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002190
2191 _kwargs.update(kwargs)
2192
2193 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002194 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002195 # descriptors don't have a spec
2196 # because we don't know what type they return
2197 _kwargs = {}
2198 elif not _callable(spec):
2199 Klass = NonCallableMagicMock
2200 elif is_type and instance and not _instance_callable(spec):
2201 Klass = NonCallableMagicMock
2202
Kushal Das484f8a82014-04-16 01:05:50 +05302203 _name = _kwargs.pop('name', _name)
2204
Michael Foord345266a2012-03-14 12:24:34 -07002205 _new_name = _name
2206 if _parent is None:
2207 # for a top level object no _new_name should be set
2208 _new_name = ''
2209
2210 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2211 name=_name, **_kwargs)
2212
2213 if isinstance(spec, FunctionTypes):
2214 # should only happen at the top level because we don't
2215 # recurse for functions
2216 mock = _set_signature(mock, spec)
2217 else:
2218 _check_signature(spec, mock, is_type, instance)
2219
2220 if _parent is not None and not instance:
2221 _parent._mock_children[_name] = mock
2222
2223 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002224 mock.return_value = create_autospec(spec, spec_set, instance=True,
2225 _name='()', _parent=mock)
2226
2227 for entry in dir(spec):
2228 if _is_magic(entry):
2229 # MagicMock already does the useful magic methods for us
2230 continue
2231
Michael Foord345266a2012-03-14 12:24:34 -07002232 # XXXX do we need a better way of getting attributes without
2233 # triggering code execution (?) Probably not - we need the actual
2234 # object to mock it so we would rather trigger a property than mock
2235 # the property descriptor. Likewise we want to mock out dynamically
2236 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002237 # XXXX what about attributes that raise exceptions other than
2238 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002239 # we could be resilient against it, or catch and propagate the
2240 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002241 try:
2242 original = getattr(spec, entry)
2243 except AttributeError:
2244 continue
Michael Foord345266a2012-03-14 12:24:34 -07002245
2246 kwargs = {'spec': original}
2247 if spec_set:
2248 kwargs = {'spec_set': original}
2249
2250 if not isinstance(original, FunctionTypes):
2251 new = _SpecState(original, spec_set, mock, entry, instance)
2252 mock._mock_children[entry] = new
2253 else:
2254 parent = mock
2255 if isinstance(spec, FunctionTypes):
2256 parent = mock.mock
2257
Michael Foord345266a2012-03-14 12:24:34 -07002258 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002259 kwargs['_eat_self'] = skipfirst
2260 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2261 _new_parent=parent,
2262 **kwargs)
2263 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002264 _check_signature(original, new, skipfirst=skipfirst)
2265
2266 # so functions created with _set_signature become instance attributes,
2267 # *plus* their underlying mock exists in _mock_children of the parent
2268 # mock. Adding to _mock_children may be unnecessary where we are also
2269 # setting as an instance attribute?
2270 if isinstance(new, FunctionTypes):
2271 setattr(mock, entry, new)
2272
2273 return mock
2274
2275
2276def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002277 """
2278 Return whether we should skip the first argument on spec's `entry`
2279 attribute.
2280 """
Michael Foord345266a2012-03-14 12:24:34 -07002281 if not isinstance(spec, type):
2282 if entry in getattr(spec, '__dict__', {}):
2283 # instance attribute - shouldn't skip
2284 return False
Michael Foord345266a2012-03-14 12:24:34 -07002285 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002286
2287 for klass in spec.__mro__:
2288 result = klass.__dict__.get(entry, DEFAULT)
2289 if result is DEFAULT:
2290 continue
2291 if isinstance(result, (staticmethod, classmethod)):
2292 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002293 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2294 # Normal method => skip if looked up on type
2295 # (if looked up on instance, self is already skipped)
2296 return is_type
2297 else:
2298 return False
Michael Foord345266a2012-03-14 12:24:34 -07002299
2300 # shouldn't get here unless function is a dynamically provided attribute
2301 # XXXX untested behaviour
2302 return is_type
2303
2304
2305def _get_class(obj):
2306 try:
2307 return obj.__class__
2308 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002309 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002310 return type(obj)
2311
2312
2313class _SpecState(object):
2314
2315 def __init__(self, spec, spec_set=False, parent=None,
2316 name=None, ids=None, instance=False):
2317 self.spec = spec
2318 self.ids = ids
2319 self.spec_set = spec_set
2320 self.parent = parent
2321 self.instance = instance
2322 self.name = name
2323
2324
2325FunctionTypes = (
2326 # python function
2327 type(create_autospec),
2328 # instance method
2329 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002330)
2331
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002332MethodWrapperTypes = (
2333 type(ANY.__eq__.__get__),
2334)
2335
Michael Foord345266a2012-03-14 12:24:34 -07002336
Michael Foorda74561a2012-03-25 19:03:13 +01002337file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002338
Michael Foord04cbe0c2013-03-19 17:22:51 -07002339def _iterate_read_data(read_data):
2340 # Helper for mock_open:
2341 # Retrieve lines from read_data via a generator so that separate calls to
2342 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002343 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2344 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002345
Berker Peksag86b34da2015-08-06 13:15:51 +03002346 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002347 # If the last line ended in a newline, the list comprehension will have an
2348 # extra entry that's just a newline. Remove this.
2349 data_as_list = data_as_list[:-1]
2350 else:
2351 # If there wasn't an extra newline by itself, then the file being
2352 # emulated doesn't have a newline to end the last line remove the
2353 # newline that our naive format() added
2354 data_as_list[-1] = data_as_list[-1][:-1]
2355
2356 for line in data_as_list:
2357 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002358
Robert Collins5329aaa2015-07-17 20:08:45 +12002359
Michael Foord0dccf652012-03-25 19:11:50 +01002360def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002361 """
2362 A helper function to create a mock to replace the use of `open`. It works
2363 for `open` called directly or used as a context manager.
2364
2365 The `mock` argument is the mock object to configure. If `None` (the
2366 default) then a `MagicMock` will be created for you, with the API limited
2367 to methods or attributes available on standard file handles.
2368
Michael Foord04cbe0c2013-03-19 17:22:51 -07002369 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2370 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002371 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002372 def _readlines_side_effect(*args, **kwargs):
2373 if handle.readlines.return_value is not None:
2374 return handle.readlines.return_value
2375 return list(_state[0])
2376
2377 def _read_side_effect(*args, **kwargs):
2378 if handle.read.return_value is not None:
2379 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002380 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002381
2382 def _readline_side_effect():
Tony Flury20870232018-09-12 23:21:16 +01002383 yield from _iter_side_effect()
2384 while True:
2385 yield type(read_data)()
2386
2387 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002388 if handle.readline.return_value is not None:
2389 while True:
2390 yield handle.readline.return_value
2391 for line in _state[0]:
2392 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002393
Michael Foorda74561a2012-03-25 19:03:13 +01002394 global file_spec
2395 if file_spec is None:
2396 import _io
2397 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2398
Michael Foord345266a2012-03-14 12:24:34 -07002399 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002400 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002401
Robert Collinsca647ef2015-07-24 03:48:20 +12002402 handle = MagicMock(spec=file_spec)
2403 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002404
Robert Collinsca647ef2015-07-24 03:48:20 +12002405 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002406
Robert Collinsca647ef2015-07-24 03:48:20 +12002407 handle.write.return_value = None
2408 handle.read.return_value = None
2409 handle.readline.return_value = None
2410 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002411
Robert Collinsca647ef2015-07-24 03:48:20 +12002412 handle.read.side_effect = _read_side_effect
2413 _state[1] = _readline_side_effect()
2414 handle.readline.side_effect = _state[1]
2415 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002416 handle.__iter__.side_effect = _iter_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002417
Robert Collinsca647ef2015-07-24 03:48:20 +12002418 def reset_data(*args, **kwargs):
2419 _state[0] = _iterate_read_data(read_data)
2420 if handle.readline.side_effect == _state[1]:
2421 # Only reset the side effect if the user hasn't overridden it.
2422 _state[1] = _readline_side_effect()
2423 handle.readline.side_effect = _state[1]
2424 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002425
Robert Collinsca647ef2015-07-24 03:48:20 +12002426 mock.side_effect = reset_data
2427 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002428 return mock
2429
2430
2431class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002432 """
2433 A mock intended to be used as a property, or other descriptor, on a class.
2434 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2435 a return value when it is fetched.
2436
2437 Fetching a `PropertyMock` instance from an object calls the mock, with
2438 no args. Setting it calls the mock with the value being set.
2439 """
Michael Foordc2870622012-04-13 16:57:22 +01002440 def _get_child_mock(self, **kwargs):
2441 return MagicMock(**kwargs)
2442
Michael Foord345266a2012-03-14 12:24:34 -07002443 def __get__(self, obj, obj_type):
2444 return self()
2445 def __set__(self, obj, val):
2446 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002447
2448
2449def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002450 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002451
2452 Given an input Mock, seals it to ensure no further mocks will be generated
2453 when accessing an attribute that was not already defined.
2454
Mario Corchero96200eb2018-10-19 22:57:37 +01002455 The operation recursively seals the mock passed in, meaning that
2456 the mock itself, any mocks generated by accessing one of its attributes,
2457 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002458 """
2459 mock._mock_sealed = True
2460 for attr in dir(mock):
2461 try:
2462 m = getattr(mock, attr)
2463 except AttributeError:
2464 continue
2465 if not isinstance(m, NonCallableMock):
2466 continue
2467 if m._mock_new_parent is mock:
2468 seal(m)