blob: d13f74982086b2405caeecfdace390f61c9ad8d5 [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():
Xtreakedeca922018-12-01 15:33:54 +0530545 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100546 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
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100980
Chris Withers8ca0fa92018-12-03 21:31:37 +0000981 # handle call_args
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100982 _call = _Call((args, kwargs), two=True)
983 self.call_args = _call
984 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700985
986 seen = set()
Chris Withers8ca0fa92018-12-03 21:31:37 +0000987
988 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700989 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +0000990 method_call_name = self._mock_name
991
992 # initial stuff for mock_calls:
993 mock_call_name = self._mock_new_name
994 is_a_call = mock_call_name == '()'
995 self.mock_calls.append(_Call(('', args, kwargs)))
996
997 # follow up the chain of mocks:
998 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -0700999 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001000
Chris Withers8ca0fa92018-12-03 21:31:37 +00001001 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001002 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001003 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001004 do_method_calls = _new_parent._mock_parent is not None
1005 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001006 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001007
Chris Withers8ca0fa92018-12-03 21:31:37 +00001008 # handle mock_calls:
1009 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001010 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001011
1012 if _new_parent._mock_new_name:
1013 if is_a_call:
1014 dot = ''
1015 else:
1016 dot = '.'
1017 is_a_call = _new_parent._mock_new_name == '()'
1018 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1019
1020 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001021 _new_parent = _new_parent._mock_new_parent
1022
Chris Withers8ca0fa92018-12-03 21:31:37 +00001023 # check we're not in an infinite loop:
1024 # ( use ids here so as not to call __hash__ on the mocks)
Michael Foord345266a2012-03-14 12:24:34 -07001025 _new_parent_id = id(_new_parent)
1026 if _new_parent_id in seen:
1027 break
1028 seen.add(_new_parent_id)
1029
1030 ret_val = DEFAULT
1031 effect = self.side_effect
1032 if effect is not None:
1033 if _is_exception(effect):
1034 raise effect
1035
1036 if not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001037 result = next(effect)
1038 if _is_exception(result):
1039 raise result
Andrew Svetlov8b2cd752013-04-07 16:42:24 +03001040 if result is DEFAULT:
1041 result = self.return_value
Michael Foord2cd48732012-04-21 15:52:11 +01001042 return result
Michael Foord345266a2012-03-14 12:24:34 -07001043
1044 ret_val = effect(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001045
1046 if (self._mock_wraps is not None and
1047 self._mock_return_value is DEFAULT):
1048 return self._mock_wraps(*args, **kwargs)
1049 if ret_val is DEFAULT:
1050 ret_val = self.return_value
1051 return ret_val
1052
1053
1054
1055class Mock(CallableMixin, NonCallableMock):
1056 """
1057 Create a new `Mock` object. `Mock` takes several optional arguments
1058 that specify the behaviour of the Mock object:
1059
1060 * `spec`: This can be either a list of strings or an existing object (a
1061 class or instance) that acts as the specification for the mock object. If
1062 you pass in an object then a list of strings is formed by calling dir on
1063 the object (excluding unsupported magic attributes and methods). Accessing
1064 any attribute not in this list will raise an `AttributeError`.
1065
1066 If `spec` is an object (rather than a list of strings) then
1067 `mock.__class__` returns the class of the spec object. This allows mocks
1068 to pass `isinstance` tests.
1069
1070 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1071 or get an attribute on the mock that isn't on the object passed as
1072 `spec_set` will raise an `AttributeError`.
1073
1074 * `side_effect`: A function to be called whenever the Mock is called. See
1075 the `side_effect` attribute. Useful for raising exceptions or
1076 dynamically changing return values. The function is called with the same
1077 arguments as the mock, and unless it returns `DEFAULT`, the return
1078 value of this function is used as the return value.
1079
Michael Foord2cd48732012-04-21 15:52:11 +01001080 If `side_effect` is an iterable then each call to the mock will return
1081 the next value from the iterable. If any of the members of the iterable
1082 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001083
Michael Foord345266a2012-03-14 12:24:34 -07001084 * `return_value`: The value returned when the mock is called. By default
1085 this is a new Mock (created on first access). See the
1086 `return_value` attribute.
1087
Michael Foord0682a0c2012-04-13 20:51:20 +01001088 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1089 calling the Mock will pass the call through to the wrapped object
1090 (returning the real result). Attribute access on the mock will return a
1091 Mock object that wraps the corresponding attribute of the wrapped object
1092 (so attempting to access an attribute that doesn't exist will raise an
1093 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001094
1095 If the mock has an explicit `return_value` set then calls are not passed
1096 to the wrapped object and the `return_value` is returned instead.
1097
1098 * `name`: If the mock has a name then it will be used in the repr of the
1099 mock. This can be useful for debugging. The name is propagated to child
1100 mocks.
1101
1102 Mocks can also be called with arbitrary keyword arguments. These will be
1103 used to set attributes on the mock after it is created.
1104 """
1105
1106
1107
1108def _dot_lookup(thing, comp, import_path):
1109 try:
1110 return getattr(thing, comp)
1111 except AttributeError:
1112 __import__(import_path)
1113 return getattr(thing, comp)
1114
1115
1116def _importer(target):
1117 components = target.split('.')
1118 import_path = components.pop(0)
1119 thing = __import__(import_path)
1120
1121 for comp in components:
1122 import_path += ".%s" % comp
1123 thing = _dot_lookup(thing, comp, import_path)
1124 return thing
1125
1126
1127def _is_started(patcher):
1128 # XXXX horrible
1129 return hasattr(patcher, 'is_local')
1130
1131
1132class _patch(object):
1133
1134 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001135 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001136
1137 def __init__(
1138 self, getter, attribute, new, spec, create,
1139 spec_set, autospec, new_callable, kwargs
1140 ):
1141 if new_callable is not None:
1142 if new is not DEFAULT:
1143 raise ValueError(
1144 "Cannot use 'new' and 'new_callable' together"
1145 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001146 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001147 raise ValueError(
1148 "Cannot use 'autospec' and 'new_callable' together"
1149 )
1150
1151 self.getter = getter
1152 self.attribute = attribute
1153 self.new = new
1154 self.new_callable = new_callable
1155 self.spec = spec
1156 self.create = create
1157 self.has_local = False
1158 self.spec_set = spec_set
1159 self.autospec = autospec
1160 self.kwargs = kwargs
1161 self.additional_patchers = []
1162
1163
1164 def copy(self):
1165 patcher = _patch(
1166 self.getter, self.attribute, self.new, self.spec,
1167 self.create, self.spec_set,
1168 self.autospec, self.new_callable, self.kwargs
1169 )
1170 patcher.attribute_name = self.attribute_name
1171 patcher.additional_patchers = [
1172 p.copy() for p in self.additional_patchers
1173 ]
1174 return patcher
1175
1176
1177 def __call__(self, func):
1178 if isinstance(func, type):
1179 return self.decorate_class(func)
1180 return self.decorate_callable(func)
1181
1182
1183 def decorate_class(self, klass):
1184 for attr in dir(klass):
1185 if not attr.startswith(patch.TEST_PREFIX):
1186 continue
1187
1188 attr_value = getattr(klass, attr)
1189 if not hasattr(attr_value, "__call__"):
1190 continue
1191
1192 patcher = self.copy()
1193 setattr(klass, attr, patcher(attr_value))
1194 return klass
1195
1196
1197 def decorate_callable(self, func):
1198 if hasattr(func, 'patchings'):
1199 func.patchings.append(self)
1200 return func
1201
1202 @wraps(func)
1203 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001204 extra_args = []
1205 entered_patchers = []
1206
Michael Foord50a8c0e2012-03-25 18:57:58 +01001207 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001208 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001209 for patching in patched.patchings:
1210 arg = patching.__enter__()
1211 entered_patchers.append(patching)
1212 if patching.attribute_name is not None:
1213 keywargs.update(arg)
1214 elif patching.new is DEFAULT:
1215 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001216
Michael Foordd7c65e22012-03-14 14:56:54 -07001217 args += tuple(extra_args)
1218 return func(*args, **keywargs)
1219 except:
1220 if (patching not in entered_patchers and
1221 _is_started(patching)):
1222 # the patcher may have been started, but an exception
1223 # raised whilst entering one of its additional_patchers
1224 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001225 # Pass the exception to __exit__
1226 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001227 # re-raise the exception
1228 raise
Michael Foord345266a2012-03-14 12:24:34 -07001229 finally:
1230 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001231 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001232
1233 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001234 return patched
1235
1236
1237 def get_original(self):
1238 target = self.getter()
1239 name = self.attribute
1240
1241 original = DEFAULT
1242 local = False
1243
1244 try:
1245 original = target.__dict__[name]
1246 except (AttributeError, KeyError):
1247 original = getattr(target, name, DEFAULT)
1248 else:
1249 local = True
1250
Michael Foordfddcfa22014-04-14 16:25:20 -04001251 if name in _builtins and isinstance(target, ModuleType):
1252 self.create = True
1253
Michael Foord345266a2012-03-14 12:24:34 -07001254 if not self.create and original is DEFAULT:
1255 raise AttributeError(
1256 "%s does not have the attribute %r" % (target, name)
1257 )
1258 return original, local
1259
1260
1261 def __enter__(self):
1262 """Perform the patch."""
1263 new, spec, spec_set = self.new, self.spec, self.spec_set
1264 autospec, kwargs = self.autospec, self.kwargs
1265 new_callable = self.new_callable
1266 self.target = self.getter()
1267
Michael Foord50a8c0e2012-03-25 18:57:58 +01001268 # normalise False to None
1269 if spec is False:
1270 spec = None
1271 if spec_set is False:
1272 spec_set = None
1273 if autospec is False:
1274 autospec = None
1275
1276 if spec is not None and autospec is not None:
1277 raise TypeError("Can't specify spec and autospec")
1278 if ((spec is not None or autospec is not None) and
1279 spec_set not in (True, None)):
1280 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1281
Michael Foord345266a2012-03-14 12:24:34 -07001282 original, local = self.get_original()
1283
Michael Foord50a8c0e2012-03-25 18:57:58 +01001284 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001285 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001286 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001287 # set spec to the object we are replacing
1288 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001289 if spec_set is True:
1290 spec_set = original
1291 spec = None
1292 elif spec is not None:
1293 if spec_set is True:
1294 spec_set = spec
1295 spec = None
1296 elif spec_set is True:
1297 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001298
Michael Foord50a8c0e2012-03-25 18:57:58 +01001299 if spec is not None or spec_set is not None:
1300 if original is DEFAULT:
1301 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001302 if isinstance(original, type):
1303 # If we're patching out a class and there is a spec
1304 inherit = True
1305
1306 Klass = MagicMock
1307 _kwargs = {}
1308 if new_callable is not None:
1309 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001310 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001311 this_spec = spec
1312 if spec_set is not None:
1313 this_spec = spec_set
1314 if _is_list(this_spec):
1315 not_callable = '__call__' not in this_spec
1316 else:
1317 not_callable = not callable(this_spec)
1318 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001319 Klass = NonCallableMagicMock
1320
1321 if spec is not None:
1322 _kwargs['spec'] = spec
1323 if spec_set is not None:
1324 _kwargs['spec_set'] = spec_set
1325
1326 # add a name to mocks
1327 if (isinstance(Klass, type) and
1328 issubclass(Klass, NonCallableMock) and self.attribute):
1329 _kwargs['name'] = self.attribute
1330
1331 _kwargs.update(kwargs)
1332 new = Klass(**_kwargs)
1333
1334 if inherit and _is_instance_mock(new):
1335 # we can only tell if the instance should be callable if the
1336 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001337 this_spec = spec
1338 if spec_set is not None:
1339 this_spec = spec_set
1340 if (not _is_list(this_spec) and not
1341 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001342 Klass = NonCallableMagicMock
1343
1344 _kwargs.pop('name')
1345 new.return_value = Klass(_new_parent=new, _new_name='()',
1346 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001347 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001348 # spec is ignored, new *must* be default, spec_set is treated
1349 # as a boolean. Should we check spec is not None and that spec_set
1350 # is a bool?
1351 if new is not DEFAULT:
1352 raise TypeError(
1353 "autospec creates the mock for you. Can't specify "
1354 "autospec and new."
1355 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001356 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001357 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001358 spec_set = bool(spec_set)
1359 if autospec is True:
1360 autospec = original
1361
1362 new = create_autospec(autospec, spec_set=spec_set,
1363 _name=self.attribute, **kwargs)
1364 elif kwargs:
1365 # can't set keyword args when we aren't creating the mock
1366 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1367 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1368
1369 new_attr = new
1370
1371 self.temp_original = original
1372 self.is_local = local
1373 setattr(self.target, self.attribute, new_attr)
1374 if self.attribute_name is not None:
1375 extra_args = {}
1376 if self.new is DEFAULT:
1377 extra_args[self.attribute_name] = new
1378 for patching in self.additional_patchers:
1379 arg = patching.__enter__()
1380 if patching.new is DEFAULT:
1381 extra_args.update(arg)
1382 return extra_args
1383
1384 return new
1385
1386
Michael Foord50a8c0e2012-03-25 18:57:58 +01001387 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001388 """Undo the patch."""
1389 if not _is_started(self):
1390 raise RuntimeError('stop called on unstarted patcher')
1391
1392 if self.is_local and self.temp_original is not DEFAULT:
1393 setattr(self.target, self.attribute, self.temp_original)
1394 else:
1395 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001396 if not self.create and (not hasattr(self.target, self.attribute) or
1397 self.attribute in ('__doc__', '__module__',
1398 '__defaults__', '__annotations__',
1399 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001400 # needed for proxy objects like django settings
1401 setattr(self.target, self.attribute, self.temp_original)
1402
1403 del self.temp_original
1404 del self.is_local
1405 del self.target
1406 for patcher in reversed(self.additional_patchers):
1407 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001408 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001409
Michael Foordf7c41582012-06-10 20:36:32 +01001410
1411 def start(self):
1412 """Activate a patch, returning any created mock."""
1413 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001414 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001415 return result
1416
1417
1418 def stop(self):
1419 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001420 try:
1421 self._active_patches.remove(self)
1422 except ValueError:
1423 # If the patch hasn't been started this will fail
1424 pass
1425
Michael Foordf7c41582012-06-10 20:36:32 +01001426 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001427
1428
1429
1430def _get_target(target):
1431 try:
1432 target, attribute = target.rsplit('.', 1)
1433 except (TypeError, ValueError):
1434 raise TypeError("Need a valid target to patch. You supplied: %r" %
1435 (target,))
1436 getter = lambda: _importer(target)
1437 return getter, attribute
1438
1439
1440def _patch_object(
1441 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001442 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001443 new_callable=None, **kwargs
1444 ):
1445 """
Michael Foord345266a2012-03-14 12:24:34 -07001446 patch the named member (`attribute`) on an object (`target`) with a mock
1447 object.
1448
1449 `patch.object` can be used as a decorator, class decorator or a context
1450 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1451 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1452 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1453 the mock object it creates.
1454
1455 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1456 for choosing which methods to wrap.
1457 """
1458 getter = lambda: target
1459 return _patch(
1460 getter, attribute, new, spec, create,
1461 spec_set, autospec, new_callable, kwargs
1462 )
1463
1464
Michael Foord50a8c0e2012-03-25 18:57:58 +01001465def _patch_multiple(target, spec=None, create=False, spec_set=None,
1466 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001467 """Perform multiple patches in a single call. It takes the object to be
1468 patched (either as an object or a string to fetch the object by importing)
1469 and keyword arguments for the patches::
1470
1471 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1472 ...
1473
1474 Use `DEFAULT` as the value if you want `patch.multiple` to create
1475 mocks for you. In this case the created mocks are passed into a decorated
1476 function by keyword, and a dictionary is returned when `patch.multiple` is
1477 used as a context manager.
1478
1479 `patch.multiple` can be used as a decorator, class decorator or a context
1480 manager. The arguments `spec`, `spec_set`, `create`,
1481 `autospec` and `new_callable` have the same meaning as for `patch`. These
1482 arguments will be applied to *all* patches done by `patch.multiple`.
1483
1484 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1485 for choosing which methods to wrap.
1486 """
1487 if type(target) is str:
1488 getter = lambda: _importer(target)
1489 else:
1490 getter = lambda: target
1491
1492 if not kwargs:
1493 raise ValueError(
1494 'Must supply at least one keyword argument with patch.multiple'
1495 )
1496 # need to wrap in a list for python 3, where items is a view
1497 items = list(kwargs.items())
1498 attribute, new = items[0]
1499 patcher = _patch(
1500 getter, attribute, new, spec, create, spec_set,
1501 autospec, new_callable, {}
1502 )
1503 patcher.attribute_name = attribute
1504 for attribute, new in items[1:]:
1505 this_patcher = _patch(
1506 getter, attribute, new, spec, create, spec_set,
1507 autospec, new_callable, {}
1508 )
1509 this_patcher.attribute_name = attribute
1510 patcher.additional_patchers.append(this_patcher)
1511 return patcher
1512
1513
1514def patch(
1515 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001516 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001517 ):
1518 """
1519 `patch` acts as a function decorator, class decorator or a context
1520 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001521 is patched with a `new` object. When the function/with statement exits
1522 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001523
Michael Foord54b3db82012-03-28 15:08:08 +01001524 If `new` is omitted, then the target is replaced with a
1525 `MagicMock`. If `patch` is used as a decorator and `new` is
1526 omitted, the created mock is passed in as an extra argument to the
1527 decorated function. If `patch` is used as a context manager the created
1528 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001529
Michael Foord54b3db82012-03-28 15:08:08 +01001530 `target` should be a string in the form `'package.module.ClassName'`. The
1531 `target` is imported and the specified object replaced with the `new`
1532 object, so the `target` must be importable from the environment you are
1533 calling `patch` from. The target is imported when the decorated function
1534 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001535
1536 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1537 if patch is creating one for you.
1538
1539 In addition you can pass `spec=True` or `spec_set=True`, which causes
1540 patch to pass in the object being mocked as the spec/spec_set object.
1541
1542 `new_callable` allows you to specify a different class, or callable object,
1543 that will be called to create the `new` object. By default `MagicMock` is
1544 used.
1545
1546 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001547 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001548 All attributes of the mock will also have the spec of the corresponding
1549 attribute of the object being replaced. Methods and functions being
1550 mocked will have their arguments checked and will raise a `TypeError` if
1551 they are called with the wrong signature. For mocks replacing a class,
1552 their return value (the 'instance') will have the same spec as the class.
1553
1554 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1555 arbitrary object as the spec instead of the one being replaced.
1556
1557 By default `patch` will fail to replace attributes that don't exist. If
1558 you pass in `create=True`, and the attribute doesn't exist, patch will
1559 create the attribute for you when the patched function is called, and
1560 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001561 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001562 default because it can be dangerous. With it switched on you can write
1563 passing tests against APIs that don't actually exist!
1564
1565 Patch can be used as a `TestCase` class decorator. It works by
1566 decorating each test method in the class. This reduces the boilerplate
1567 code when your test methods share a common patchings set. `patch` finds
1568 tests by looking for method names that start with `patch.TEST_PREFIX`.
1569 By default this is `test`, which matches the way `unittest` finds tests.
1570 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1571
1572 Patch can be used as a context manager, with the with statement. Here the
1573 patching applies to the indented block after the with statement. If you
1574 use "as" then the patched object will be bound to the name after the
1575 "as"; very useful if `patch` is creating a mock object for you.
1576
1577 `patch` takes arbitrary keyword arguments. These will be passed to
1578 the `Mock` (or `new_callable`) on construction.
1579
1580 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1581 available for alternate use-cases.
1582 """
1583 getter, attribute = _get_target(target)
1584 return _patch(
1585 getter, attribute, new, spec, create,
1586 spec_set, autospec, new_callable, kwargs
1587 )
1588
1589
1590class _patch_dict(object):
1591 """
1592 Patch a dictionary, or dictionary like object, and restore the dictionary
1593 to its original state after the test.
1594
1595 `in_dict` can be a dictionary or a mapping like container. If it is a
1596 mapping then it must at least support getting, setting and deleting items
1597 plus iterating over keys.
1598
1599 `in_dict` can also be a string specifying the name of the dictionary, which
1600 will then be fetched by importing it.
1601
1602 `values` can be a dictionary of values to set in the dictionary. `values`
1603 can also be an iterable of `(key, value)` pairs.
1604
1605 If `clear` is True then the dictionary will be cleared before the new
1606 values are set.
1607
1608 `patch.dict` can also be called with arbitrary keyword arguments to set
1609 values in the dictionary::
1610
1611 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1612 ...
1613
1614 `patch.dict` can be used as a context manager, decorator or class
1615 decorator. When used as a class decorator `patch.dict` honours
1616 `patch.TEST_PREFIX` for choosing which methods to wrap.
1617 """
1618
1619 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1620 if isinstance(in_dict, str):
1621 in_dict = _importer(in_dict)
1622 self.in_dict = in_dict
1623 # support any argument supported by dict(...) constructor
1624 self.values = dict(values)
1625 self.values.update(kwargs)
1626 self.clear = clear
1627 self._original = None
1628
1629
1630 def __call__(self, f):
1631 if isinstance(f, type):
1632 return self.decorate_class(f)
1633 @wraps(f)
1634 def _inner(*args, **kw):
1635 self._patch_dict()
1636 try:
1637 return f(*args, **kw)
1638 finally:
1639 self._unpatch_dict()
1640
1641 return _inner
1642
1643
1644 def decorate_class(self, klass):
1645 for attr in dir(klass):
1646 attr_value = getattr(klass, attr)
1647 if (attr.startswith(patch.TEST_PREFIX) and
1648 hasattr(attr_value, "__call__")):
1649 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1650 decorated = decorator(attr_value)
1651 setattr(klass, attr, decorated)
1652 return klass
1653
1654
1655 def __enter__(self):
1656 """Patch the dict."""
1657 self._patch_dict()
1658
1659
1660 def _patch_dict(self):
1661 values = self.values
1662 in_dict = self.in_dict
1663 clear = self.clear
1664
1665 try:
1666 original = in_dict.copy()
1667 except AttributeError:
1668 # dict like object with no copy method
1669 # must support iteration over keys
1670 original = {}
1671 for key in in_dict:
1672 original[key] = in_dict[key]
1673 self._original = original
1674
1675 if clear:
1676 _clear_dict(in_dict)
1677
1678 try:
1679 in_dict.update(values)
1680 except AttributeError:
1681 # dict like object with no update method
1682 for key in values:
1683 in_dict[key] = values[key]
1684
1685
1686 def _unpatch_dict(self):
1687 in_dict = self.in_dict
1688 original = self._original
1689
1690 _clear_dict(in_dict)
1691
1692 try:
1693 in_dict.update(original)
1694 except AttributeError:
1695 for key in original:
1696 in_dict[key] = original[key]
1697
1698
1699 def __exit__(self, *args):
1700 """Unpatch the dict."""
1701 self._unpatch_dict()
1702 return False
1703
1704 start = __enter__
1705 stop = __exit__
1706
1707
1708def _clear_dict(in_dict):
1709 try:
1710 in_dict.clear()
1711 except AttributeError:
1712 keys = list(in_dict)
1713 for key in keys:
1714 del in_dict[key]
1715
1716
Michael Foordf7c41582012-06-10 20:36:32 +01001717def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001718 """Stop all active patches. LIFO to unroll nested patches."""
1719 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001720 patch.stop()
1721
1722
Michael Foord345266a2012-03-14 12:24:34 -07001723patch.object = _patch_object
1724patch.dict = _patch_dict
1725patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001726patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001727patch.TEST_PREFIX = 'test'
1728
1729magic_methods = (
1730 "lt le gt ge eq ne "
1731 "getitem setitem delitem "
1732 "len contains iter "
1733 "hash str sizeof "
1734 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001735 # we added divmod and rdivmod here instead of numerics
1736 # because there is no idivmod
1737 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001738 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001739 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001740 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001741 "fspath "
Michael Foord345266a2012-03-14 12:24:34 -07001742)
1743
Michael Foordd2623d72014-04-14 11:23:48 -04001744numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001745 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001746)
Michael Foord345266a2012-03-14 12:24:34 -07001747inplace = ' '.join('i%s' % n for n in numerics.split())
1748right = ' '.join('r%s' % n for n in numerics.split())
1749
1750# not including __prepare__, __instancecheck__, __subclasscheck__
1751# (as they are metaclass methods)
1752# __del__ is not supported at all as it causes problems if it exists
1753
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001754_non_defaults = {
1755 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1756 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1757 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1758 '__repr__', '__dir__', '__subclasses__', '__format__',
Serhiy Storchaka5943ea72016-06-19 18:30:43 +03001759 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001760}
Michael Foord345266a2012-03-14 12:24:34 -07001761
1762
1763def _get_method(name, func):
1764 "Turns a callable object (like a mock) into a real function"
1765 def method(self, *args, **kw):
1766 return func(self, *args, **kw)
1767 method.__name__ = name
1768 return method
1769
1770
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001771_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001772 '__%s__' % method for method in
1773 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001774}
Michael Foord345266a2012-03-14 12:24:34 -07001775
1776_all_magics = _magics | _non_defaults
1777
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001778_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001779 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001780 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001781 '__instancecheck__', '__subclasscheck__',
1782 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001783}
Michael Foord345266a2012-03-14 12:24:34 -07001784
1785_calculate_return_value = {
1786 '__hash__': lambda self: object.__hash__(self),
1787 '__str__': lambda self: object.__str__(self),
1788 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001789 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001790}
1791
1792_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001793 '__lt__': NotImplemented,
1794 '__gt__': NotImplemented,
1795 '__le__': NotImplemented,
1796 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001797 '__int__': 1,
1798 '__contains__': False,
1799 '__len__': 0,
1800 '__exit__': False,
1801 '__complex__': 1j,
1802 '__float__': 1.0,
1803 '__bool__': True,
1804 '__index__': 1,
1805}
1806
1807
1808def _get_eq(self):
1809 def __eq__(other):
1810 ret_val = self.__eq__._mock_return_value
1811 if ret_val is not DEFAULT:
1812 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001813 if self is other:
1814 return True
1815 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001816 return __eq__
1817
1818def _get_ne(self):
1819 def __ne__(other):
1820 if self.__ne__._mock_return_value is not DEFAULT:
1821 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001822 if self is other:
1823 return False
1824 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001825 return __ne__
1826
1827def _get_iter(self):
1828 def __iter__():
1829 ret_val = self.__iter__._mock_return_value
1830 if ret_val is DEFAULT:
1831 return iter([])
1832 # if ret_val was already an iterator, then calling iter on it should
1833 # return the iterator unchanged
1834 return iter(ret_val)
1835 return __iter__
1836
1837_side_effect_methods = {
1838 '__eq__': _get_eq,
1839 '__ne__': _get_ne,
1840 '__iter__': _get_iter,
1841}
1842
1843
1844
1845def _set_return_value(mock, method, name):
1846 fixed = _return_values.get(name, DEFAULT)
1847 if fixed is not DEFAULT:
1848 method.return_value = fixed
1849 return
1850
1851 return_calulator = _calculate_return_value.get(name)
1852 if return_calulator is not None:
1853 try:
1854 return_value = return_calulator(mock)
1855 except AttributeError:
1856 # XXXX why do we return AttributeError here?
1857 # set it as a side_effect instead?
1858 return_value = AttributeError(name)
1859 method.return_value = return_value
1860 return
1861
1862 side_effector = _side_effect_methods.get(name)
1863 if side_effector is not None:
1864 method.side_effect = side_effector(mock)
1865
1866
1867
1868class MagicMixin(object):
1869 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001870 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001871 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001872 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001873
1874
1875 def _mock_set_magics(self):
1876 these_magics = _magics
1877
Łukasz Langaa468db92015-04-13 23:12:42 -07001878 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001879 these_magics = _magics.intersection(self._mock_methods)
1880
1881 remove_magics = set()
1882 remove_magics = _magics - these_magics
1883
1884 for entry in remove_magics:
1885 if entry in type(self).__dict__:
1886 # remove unneeded magic methods
1887 delattr(self, entry)
1888
1889 # don't overwrite existing attributes if called a second time
1890 these_magics = these_magics - set(type(self).__dict__)
1891
1892 _type = type(self)
1893 for entry in these_magics:
1894 setattr(_type, entry, MagicProxy(entry, self))
1895
1896
1897
1898class NonCallableMagicMock(MagicMixin, NonCallableMock):
1899 """A version of `MagicMock` that isn't callable."""
1900 def mock_add_spec(self, spec, spec_set=False):
1901 """Add a spec to a mock. `spec` can either be an object or a
1902 list of strings. Only attributes on the `spec` can be fetched as
1903 attributes from the mock.
1904
1905 If `spec_set` is True then only attributes on the spec can be set."""
1906 self._mock_add_spec(spec, spec_set)
1907 self._mock_set_magics()
1908
1909
1910
1911class MagicMock(MagicMixin, Mock):
1912 """
1913 MagicMock is a subclass of Mock with default implementations
1914 of most of the magic methods. You can use MagicMock without having to
1915 configure the magic methods yourself.
1916
1917 If you use the `spec` or `spec_set` arguments then *only* magic
1918 methods that exist in the spec will be created.
1919
1920 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1921 """
1922 def mock_add_spec(self, spec, spec_set=False):
1923 """Add a spec to a mock. `spec` can either be an object or a
1924 list of strings. Only attributes on the `spec` can be fetched as
1925 attributes from the mock.
1926
1927 If `spec_set` is True then only attributes on the spec can be set."""
1928 self._mock_add_spec(spec, spec_set)
1929 self._mock_set_magics()
1930
1931
1932
1933class MagicProxy(object):
1934 def __init__(self, name, parent):
1935 self.name = name
1936 self.parent = parent
1937
1938 def __call__(self, *args, **kwargs):
1939 m = self.create_mock()
1940 return m(*args, **kwargs)
1941
1942 def create_mock(self):
1943 entry = self.name
1944 parent = self.parent
1945 m = parent._get_child_mock(name=entry, _new_name=entry,
1946 _new_parent=parent)
1947 setattr(parent, entry, m)
1948 _set_return_value(parent, m, entry)
1949 return m
1950
1951 def __get__(self, obj, _type=None):
1952 return self.create_mock()
1953
1954
1955
1956class _ANY(object):
1957 "A helper object that compares equal to everything."
1958
1959 def __eq__(self, other):
1960 return True
1961
1962 def __ne__(self, other):
1963 return False
1964
1965 def __repr__(self):
1966 return '<ANY>'
1967
1968ANY = _ANY()
1969
1970
1971
1972def _format_call_signature(name, args, kwargs):
1973 message = '%s(%%s)' % name
1974 formatted_args = ''
1975 args_string = ', '.join([repr(arg) for arg in args])
1976 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301977 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001978 ])
1979 if args_string:
1980 formatted_args = args_string
1981 if kwargs_string:
1982 if formatted_args:
1983 formatted_args += ', '
1984 formatted_args += kwargs_string
1985
1986 return message % formatted_args
1987
1988
1989
1990class _Call(tuple):
1991 """
1992 A tuple for holding the results of a call to a mock, either in the form
1993 `(args, kwargs)` or `(name, args, kwargs)`.
1994
1995 If args or kwargs are empty then a call tuple will compare equal to
1996 a tuple without those values. This makes comparisons less verbose::
1997
1998 _Call(('name', (), {})) == ('name',)
1999 _Call(('name', (1,), {})) == ('name', (1,))
2000 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2001
2002 The `_Call` object provides a useful shortcut for comparing with call::
2003
2004 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2005 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2006
2007 If the _Call has no name then it will match any name.
2008 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002009 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002010 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002011 args = ()
2012 kwargs = {}
2013 _len = len(value)
2014 if _len == 3:
2015 name, args, kwargs = value
2016 elif _len == 2:
2017 first, second = value
2018 if isinstance(first, str):
2019 name = first
2020 if isinstance(second, tuple):
2021 args = second
2022 else:
2023 kwargs = second
2024 else:
2025 args, kwargs = first, second
2026 elif _len == 1:
2027 value, = value
2028 if isinstance(value, str):
2029 name = value
2030 elif isinstance(value, tuple):
2031 args = value
2032 else:
2033 kwargs = value
2034
2035 if two:
2036 return tuple.__new__(cls, (args, kwargs))
2037
2038 return tuple.__new__(cls, (name, args, kwargs))
2039
2040
2041 def __init__(self, value=(), name=None, parent=None, two=False,
2042 from_kall=True):
2043 self.name = name
2044 self.parent = parent
2045 self.from_kall = from_kall
2046
2047
2048 def __eq__(self, other):
2049 if other is ANY:
2050 return True
2051 try:
2052 len_other = len(other)
2053 except TypeError:
2054 return False
2055
2056 self_name = ''
2057 if len(self) == 2:
2058 self_args, self_kwargs = self
2059 else:
2060 self_name, self_args, self_kwargs = self
2061
Chris Withers8ca0fa92018-12-03 21:31:37 +00002062 if (getattr(self, 'parent', None) and getattr(other, 'parent', None)
2063 and self.parent != other.parent):
2064 return False
2065
Michael Foord345266a2012-03-14 12:24:34 -07002066 other_name = ''
2067 if len_other == 0:
2068 other_args, other_kwargs = (), {}
2069 elif len_other == 3:
2070 other_name, other_args, other_kwargs = other
2071 elif len_other == 1:
2072 value, = other
2073 if isinstance(value, tuple):
2074 other_args = value
2075 other_kwargs = {}
2076 elif isinstance(value, str):
2077 other_name = value
2078 other_args, other_kwargs = (), {}
2079 else:
2080 other_args = ()
2081 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002082 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002083 # could be (name, args) or (name, kwargs) or (args, kwargs)
2084 first, second = other
2085 if isinstance(first, str):
2086 other_name = first
2087 if isinstance(second, tuple):
2088 other_args, other_kwargs = second, {}
2089 else:
2090 other_args, other_kwargs = (), second
2091 else:
2092 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002093 else:
2094 return False
Michael Foord345266a2012-03-14 12:24:34 -07002095
2096 if self_name and other_name != self_name:
2097 return False
2098
2099 # this order is important for ANY to work!
2100 return (other_args, other_kwargs) == (self_args, self_kwargs)
2101
2102
Berker Peksagce913872016-03-28 00:30:02 +03002103 __ne__ = object.__ne__
2104
2105
Michael Foord345266a2012-03-14 12:24:34 -07002106 def __call__(self, *args, **kwargs):
2107 if self.name is None:
2108 return _Call(('', args, kwargs), name='()')
2109
2110 name = self.name + '()'
2111 return _Call((self.name, args, kwargs), name=name, parent=self)
2112
2113
2114 def __getattr__(self, attr):
2115 if self.name is None:
2116 return _Call(name=attr, from_kall=False)
2117 name = '%s.%s' % (self.name, attr)
2118 return _Call(name=name, parent=self, from_kall=False)
2119
2120
Kushal Dasa37b9582014-09-16 18:33:37 +05302121 def count(self, *args, **kwargs):
2122 return self.__getattr__('count')(*args, **kwargs)
2123
2124 def index(self, *args, **kwargs):
2125 return self.__getattr__('index')(*args, **kwargs)
2126
Michael Foord345266a2012-03-14 12:24:34 -07002127 def __repr__(self):
2128 if not self.from_kall:
2129 name = self.name or 'call'
2130 if name.startswith('()'):
2131 name = 'call%s' % name
2132 return name
2133
2134 if len(self) == 2:
2135 name = 'call'
2136 args, kwargs = self
2137 else:
2138 name, args, kwargs = self
2139 if not name:
2140 name = 'call'
2141 elif not name.startswith('()'):
2142 name = 'call.%s' % name
2143 else:
2144 name = 'call%s' % name
2145 return _format_call_signature(name, args, kwargs)
2146
2147
2148 def call_list(self):
2149 """For a call object that represents multiple calls, `call_list`
2150 returns a list of all the intermediate calls as well as the
2151 final call."""
2152 vals = []
2153 thing = self
2154 while thing is not None:
2155 if thing.from_kall:
2156 vals.append(thing)
2157 thing = thing.parent
2158 return _CallList(reversed(vals))
2159
2160
2161call = _Call(from_kall=False)
2162
2163
2164
2165def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2166 _name=None, **kwargs):
2167 """Create a mock object using another object as a spec. Attributes on the
2168 mock will use the corresponding attribute on the `spec` object as their
2169 spec.
2170
2171 Functions or methods being mocked will have their arguments checked
2172 to check that they are called with the correct signature.
2173
2174 If `spec_set` is True then attempting to set attributes that don't exist
2175 on the spec object will raise an `AttributeError`.
2176
2177 If a class is used as a spec then the return value of the mock (the
2178 instance of the class) will have the same spec. You can use a class as the
2179 spec for an instance object by passing `instance=True`. The returned mock
2180 will only be callable if instances of the mock are callable.
2181
2182 `create_autospec` also takes arbitrary keyword arguments that are passed to
2183 the constructor of the created mock."""
2184 if _is_list(spec):
2185 # can't pass a list instance to the mock constructor as it will be
2186 # interpreted as a list of strings
2187 spec = type(spec)
2188
2189 is_type = isinstance(spec, type)
2190
2191 _kwargs = {'spec': spec}
2192 if spec_set:
2193 _kwargs = {'spec_set': spec}
2194 elif spec is None:
2195 # None we mock with a normal mock without a spec
2196 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002197 if _kwargs and instance:
2198 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002199
2200 _kwargs.update(kwargs)
2201
2202 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002203 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002204 # descriptors don't have a spec
2205 # because we don't know what type they return
2206 _kwargs = {}
2207 elif not _callable(spec):
2208 Klass = NonCallableMagicMock
2209 elif is_type and instance and not _instance_callable(spec):
2210 Klass = NonCallableMagicMock
2211
Kushal Das484f8a82014-04-16 01:05:50 +05302212 _name = _kwargs.pop('name', _name)
2213
Michael Foord345266a2012-03-14 12:24:34 -07002214 _new_name = _name
2215 if _parent is None:
2216 # for a top level object no _new_name should be set
2217 _new_name = ''
2218
2219 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2220 name=_name, **_kwargs)
2221
2222 if isinstance(spec, FunctionTypes):
2223 # should only happen at the top level because we don't
2224 # recurse for functions
2225 mock = _set_signature(mock, spec)
2226 else:
2227 _check_signature(spec, mock, is_type, instance)
2228
2229 if _parent is not None and not instance:
2230 _parent._mock_children[_name] = mock
2231
2232 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002233 mock.return_value = create_autospec(spec, spec_set, instance=True,
2234 _name='()', _parent=mock)
2235
2236 for entry in dir(spec):
2237 if _is_magic(entry):
2238 # MagicMock already does the useful magic methods for us
2239 continue
2240
Michael Foord345266a2012-03-14 12:24:34 -07002241 # XXXX do we need a better way of getting attributes without
2242 # triggering code execution (?) Probably not - we need the actual
2243 # object to mock it so we would rather trigger a property than mock
2244 # the property descriptor. Likewise we want to mock out dynamically
2245 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002246 # XXXX what about attributes that raise exceptions other than
2247 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002248 # we could be resilient against it, or catch and propagate the
2249 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002250 try:
2251 original = getattr(spec, entry)
2252 except AttributeError:
2253 continue
Michael Foord345266a2012-03-14 12:24:34 -07002254
2255 kwargs = {'spec': original}
2256 if spec_set:
2257 kwargs = {'spec_set': original}
2258
2259 if not isinstance(original, FunctionTypes):
2260 new = _SpecState(original, spec_set, mock, entry, instance)
2261 mock._mock_children[entry] = new
2262 else:
2263 parent = mock
2264 if isinstance(spec, FunctionTypes):
2265 parent = mock.mock
2266
Michael Foord345266a2012-03-14 12:24:34 -07002267 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002268 kwargs['_eat_self'] = skipfirst
2269 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2270 _new_parent=parent,
2271 **kwargs)
2272 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002273 _check_signature(original, new, skipfirst=skipfirst)
2274
2275 # so functions created with _set_signature become instance attributes,
2276 # *plus* their underlying mock exists in _mock_children of the parent
2277 # mock. Adding to _mock_children may be unnecessary where we are also
2278 # setting as an instance attribute?
2279 if isinstance(new, FunctionTypes):
2280 setattr(mock, entry, new)
2281
2282 return mock
2283
2284
2285def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002286 """
2287 Return whether we should skip the first argument on spec's `entry`
2288 attribute.
2289 """
Michael Foord345266a2012-03-14 12:24:34 -07002290 if not isinstance(spec, type):
2291 if entry in getattr(spec, '__dict__', {}):
2292 # instance attribute - shouldn't skip
2293 return False
Michael Foord345266a2012-03-14 12:24:34 -07002294 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002295
2296 for klass in spec.__mro__:
2297 result = klass.__dict__.get(entry, DEFAULT)
2298 if result is DEFAULT:
2299 continue
2300 if isinstance(result, (staticmethod, classmethod)):
2301 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002302 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2303 # Normal method => skip if looked up on type
2304 # (if looked up on instance, self is already skipped)
2305 return is_type
2306 else:
2307 return False
Michael Foord345266a2012-03-14 12:24:34 -07002308
2309 # shouldn't get here unless function is a dynamically provided attribute
2310 # XXXX untested behaviour
2311 return is_type
2312
2313
2314def _get_class(obj):
2315 try:
2316 return obj.__class__
2317 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002318 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002319 return type(obj)
2320
2321
2322class _SpecState(object):
2323
2324 def __init__(self, spec, spec_set=False, parent=None,
2325 name=None, ids=None, instance=False):
2326 self.spec = spec
2327 self.ids = ids
2328 self.spec_set = spec_set
2329 self.parent = parent
2330 self.instance = instance
2331 self.name = name
2332
2333
2334FunctionTypes = (
2335 # python function
2336 type(create_autospec),
2337 # instance method
2338 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002339)
2340
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002341MethodWrapperTypes = (
2342 type(ANY.__eq__.__get__),
2343)
2344
Michael Foord345266a2012-03-14 12:24:34 -07002345
Michael Foorda74561a2012-03-25 19:03:13 +01002346file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002347
Michael Foord04cbe0c2013-03-19 17:22:51 -07002348def _iterate_read_data(read_data):
2349 # Helper for mock_open:
2350 # Retrieve lines from read_data via a generator so that separate calls to
2351 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002352 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2353 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002354
Berker Peksag86b34da2015-08-06 13:15:51 +03002355 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002356 # If the last line ended in a newline, the list comprehension will have an
2357 # extra entry that's just a newline. Remove this.
2358 data_as_list = data_as_list[:-1]
2359 else:
2360 # If there wasn't an extra newline by itself, then the file being
2361 # emulated doesn't have a newline to end the last line remove the
2362 # newline that our naive format() added
2363 data_as_list[-1] = data_as_list[-1][:-1]
2364
2365 for line in data_as_list:
2366 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002367
Robert Collins5329aaa2015-07-17 20:08:45 +12002368
Michael Foord0dccf652012-03-25 19:11:50 +01002369def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002370 """
2371 A helper function to create a mock to replace the use of `open`. It works
2372 for `open` called directly or used as a context manager.
2373
2374 The `mock` argument is the mock object to configure. If `None` (the
2375 default) then a `MagicMock` will be created for you, with the API limited
2376 to methods or attributes available on standard file handles.
2377
Michael Foord04cbe0c2013-03-19 17:22:51 -07002378 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2379 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002380 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002381 def _readlines_side_effect(*args, **kwargs):
2382 if handle.readlines.return_value is not None:
2383 return handle.readlines.return_value
2384 return list(_state[0])
2385
2386 def _read_side_effect(*args, **kwargs):
2387 if handle.read.return_value is not None:
2388 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002389 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002390
2391 def _readline_side_effect():
Tony Flury20870232018-09-12 23:21:16 +01002392 yield from _iter_side_effect()
2393 while True:
2394 yield type(read_data)()
2395
2396 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002397 if handle.readline.return_value is not None:
2398 while True:
2399 yield handle.readline.return_value
2400 for line in _state[0]:
2401 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002402
Michael Foorda74561a2012-03-25 19:03:13 +01002403 global file_spec
2404 if file_spec is None:
2405 import _io
2406 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2407
Michael Foord345266a2012-03-14 12:24:34 -07002408 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002409 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002410
Robert Collinsca647ef2015-07-24 03:48:20 +12002411 handle = MagicMock(spec=file_spec)
2412 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002413
Robert Collinsca647ef2015-07-24 03:48:20 +12002414 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002415
Robert Collinsca647ef2015-07-24 03:48:20 +12002416 handle.write.return_value = None
2417 handle.read.return_value = None
2418 handle.readline.return_value = None
2419 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002420
Robert Collinsca647ef2015-07-24 03:48:20 +12002421 handle.read.side_effect = _read_side_effect
2422 _state[1] = _readline_side_effect()
2423 handle.readline.side_effect = _state[1]
2424 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002425 handle.__iter__.side_effect = _iter_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002426
Robert Collinsca647ef2015-07-24 03:48:20 +12002427 def reset_data(*args, **kwargs):
2428 _state[0] = _iterate_read_data(read_data)
2429 if handle.readline.side_effect == _state[1]:
2430 # Only reset the side effect if the user hasn't overridden it.
2431 _state[1] = _readline_side_effect()
2432 handle.readline.side_effect = _state[1]
2433 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002434
Robert Collinsca647ef2015-07-24 03:48:20 +12002435 mock.side_effect = reset_data
2436 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002437 return mock
2438
2439
2440class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002441 """
2442 A mock intended to be used as a property, or other descriptor, on a class.
2443 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2444 a return value when it is fetched.
2445
2446 Fetching a `PropertyMock` instance from an object calls the mock, with
2447 no args. Setting it calls the mock with the value being set.
2448 """
Michael Foordc2870622012-04-13 16:57:22 +01002449 def _get_child_mock(self, **kwargs):
2450 return MagicMock(**kwargs)
2451
Michael Foord345266a2012-03-14 12:24:34 -07002452 def __get__(self, obj, obj_type):
2453 return self()
2454 def __set__(self, obj, val):
2455 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002456
2457
2458def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002459 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002460
2461 Given an input Mock, seals it to ensure no further mocks will be generated
2462 when accessing an attribute that was not already defined.
2463
Mario Corchero96200eb2018-10-19 22:57:37 +01002464 The operation recursively seals the mock passed in, meaning that
2465 the mock itself, any mocks generated by accessing one of its attributes,
2466 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002467 """
2468 mock._mock_sealed = True
2469 for attr in dir(mock):
2470 try:
2471 m = getattr(mock, attr)
2472 except AttributeError:
2473 continue
2474 if not isinstance(m, NonCallableMock):
2475 continue
2476 if m._mock_new_parent is mock:
2477 seal(m)