blob: f641e38dc54bea132117cfe15d431775bd08060a [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
Miss Islington (bot)a9846e02018-06-10 22:05:22 -07005# 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
Antoine Pitrou5c64df72013-02-03 00:23:58 +010033from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070034
35
Michael Foordfddcfa22014-04-14 16:25:20 -040036_builtins = {name for name in dir(builtins) if not name.startswith('_')}
37
Michael Foord345266a2012-03-14 12:24:34 -070038BaseExceptions = (BaseException,)
39if 'java' in sys.platform:
40 # jython
41 import java
42 BaseExceptions = (BaseException, java.lang.Throwable)
43
44
45FILTER_DIR = True
46
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100047# Workaround for issue #12370
48# Without this, the __class__ properties wouldn't be set correctly
49_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070050
51def _is_instance_mock(obj):
52 # can't use isinstance on Mock objects because they override __class__
53 # The base class for all mocks is NonCallableMock
54 return issubclass(type(obj), NonCallableMock)
55
56
57def _is_exception(obj):
58 return (
59 isinstance(obj, BaseExceptions) or
60 isinstance(obj, type) and issubclass(obj, BaseExceptions)
61 )
62
63
Antoine Pitrou5c64df72013-02-03 00:23:58 +010064def _get_signature_object(func, as_instance, eat_self):
65 """
66 Given an arbitrary, possibly callable object, try to create a suitable
67 signature object.
68 Return a (reduced func, signature) tuple, or None.
69 """
70 if isinstance(func, type) and not as_instance:
71 # If it's a type and should be modelled as a type, use __init__.
Michael Foord345266a2012-03-14 12:24:34 -070072 try:
73 func = func.__init__
74 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010075 return None
76 # Skip the `self` argument in __init__
77 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070078 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010079 # If we really want to model an instance of the passed type,
80 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070081 try:
82 func = func.__call__
83 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010084 return None
85 if eat_self:
86 sig_func = partial(func, None)
87 else:
88 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -070089 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010090 return func, inspect.signature(sig_func)
91 except ValueError:
92 # Certain callable types are not supported by inspect.signature()
93 return None
Michael Foord345266a2012-03-14 12:24:34 -070094
95
96def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010097 sig = _get_signature_object(func, instance, skipfirst)
98 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -070099 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100100 func, sig = sig
101 def checksig(_mock_self, *args, **kwargs):
102 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700103 _copy_func_details(func, checksig)
104 type(mock)._mock_check_sig = checksig
105
106
107def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700108 # we explicitly don't copy func.__dict__ into this copy as it would
109 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300110 for attribute in (
111 '__name__', '__doc__', '__text_signature__',
112 '__module__', '__defaults__', '__kwdefaults__',
113 ):
114 try:
115 setattr(funcopy, attribute, getattr(func, attribute))
116 except AttributeError:
117 pass
Michael Foord345266a2012-03-14 12:24:34 -0700118
119
120def _callable(obj):
121 if isinstance(obj, type):
122 return True
123 if getattr(obj, '__call__', None) is not None:
124 return True
125 return False
126
127
128def _is_list(obj):
129 # checks for list or tuples
130 # XXXX badly named!
131 return type(obj) in (list, tuple)
132
133
134def _instance_callable(obj):
135 """Given an object, return True if the object is callable.
136 For classes, return True if instances would be callable."""
137 if not isinstance(obj, type):
138 # already an instance
139 return getattr(obj, '__call__', None) is not None
140
Michael Foorda74b3aa2012-03-14 14:40:22 -0700141 # *could* be broken by a class overriding __mro__ or __dict__ via
142 # a metaclass
143 for base in (obj,) + obj.__mro__:
144 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700145 return True
146 return False
147
148
149def _set_signature(mock, original, instance=False):
150 # creates a function with signature (*args, **kwargs) that delegates to a
151 # mock. It still does signature checking by calling a lambda with the same
152 # signature as the original.
153 if not _callable(original):
154 return
155
156 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100157 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700158 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700159 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100160 func, sig = result
161 def checksig(*args, **kwargs):
162 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700163 _copy_func_details(func, checksig)
164
165 name = original.__name__
166 if not name.isidentifier():
167 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100168 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700169 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100170 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700171 return mock(*args, **kwargs)""" % name
172 exec (src, context)
173 funcopy = context[name]
174 _setup_func(funcopy, mock)
175 return funcopy
176
177
178def _setup_func(funcopy, mock):
179 funcopy.mock = mock
180
181 # can't use isinstance with mocks
182 if not _is_instance_mock(mock):
183 return
184
185 def assert_called_with(*args, **kwargs):
186 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700187 def assert_called(*args, **kwargs):
188 return mock.assert_called(*args, **kwargs)
189 def assert_not_called(*args, **kwargs):
190 return mock.assert_not_called(*args, **kwargs)
191 def assert_called_once(*args, **kwargs):
192 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700193 def assert_called_once_with(*args, **kwargs):
194 return mock.assert_called_once_with(*args, **kwargs)
195 def assert_has_calls(*args, **kwargs):
196 return mock.assert_has_calls(*args, **kwargs)
197 def assert_any_call(*args, **kwargs):
198 return mock.assert_any_call(*args, **kwargs)
199 def reset_mock():
200 funcopy.method_calls = _CallList()
201 funcopy.mock_calls = _CallList()
202 mock.reset_mock()
203 ret = funcopy.return_value
204 if _is_instance_mock(ret) and not ret is mock:
205 ret.reset_mock()
206
207 funcopy.called = False
208 funcopy.call_count = 0
209 funcopy.call_args = None
210 funcopy.call_args_list = _CallList()
211 funcopy.method_calls = _CallList()
212 funcopy.mock_calls = _CallList()
213
214 funcopy.return_value = mock.return_value
215 funcopy.side_effect = mock.side_effect
216 funcopy._mock_children = mock._mock_children
217
218 funcopy.assert_called_with = assert_called_with
219 funcopy.assert_called_once_with = assert_called_once_with
220 funcopy.assert_has_calls = assert_has_calls
221 funcopy.assert_any_call = assert_any_call
222 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700223 funcopy.assert_called = assert_called
224 funcopy.assert_not_called = assert_not_called
225 funcopy.assert_called_once = assert_called_once
Michael Foord345266a2012-03-14 12:24:34 -0700226
227 mock._mock_delegate = funcopy
228
229
230def _is_magic(name):
231 return '__%s__' % name[2:-2] == name
232
233
234class _SentinelObject(object):
235 "A unique, named, sentinel object."
236 def __init__(self, name):
237 self.name = name
238
239 def __repr__(self):
240 return 'sentinel.%s' % self.name
241
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200242 def __reduce__(self):
243 return 'sentinel.%s' % self.name
244
Michael Foord345266a2012-03-14 12:24:34 -0700245
246class _Sentinel(object):
247 """Access attributes to return a named object, usable as a sentinel."""
248 def __init__(self):
249 self._sentinels = {}
250
251 def __getattr__(self, name):
252 if name == '__bases__':
253 # Without this help(unittest.mock) raises an exception
254 raise AttributeError
255 return self._sentinels.setdefault(name, _SentinelObject(name))
256
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200257 def __reduce__(self):
258 return 'sentinel'
259
Michael Foord345266a2012-03-14 12:24:34 -0700260
261sentinel = _Sentinel()
262
263DEFAULT = sentinel.DEFAULT
264_missing = sentinel.MISSING
265_deleted = sentinel.DELETED
266
267
Michael Foord345266a2012-03-14 12:24:34 -0700268def _copy(value):
269 if type(value) in (dict, list, tuple, set):
270 return type(value)(value)
271 return value
272
273
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200274_allowed_names = {
275 'return_value', '_mock_return_value', 'side_effect',
276 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
277 '_mock_name', '_mock_new_name'
278}
Michael Foord345266a2012-03-14 12:24:34 -0700279
280
281def _delegating_property(name):
282 _allowed_names.add(name)
283 _the_name = '_mock_' + name
284 def _get(self, name=name, _the_name=_the_name):
285 sig = self._mock_delegate
286 if sig is None:
287 return getattr(self, _the_name)
288 return getattr(sig, name)
289 def _set(self, value, name=name, _the_name=_the_name):
290 sig = self._mock_delegate
291 if sig is None:
292 self.__dict__[_the_name] = value
293 else:
294 setattr(sig, name, value)
295
296 return property(_get, _set)
297
298
299
300class _CallList(list):
301
302 def __contains__(self, value):
303 if not isinstance(value, list):
304 return list.__contains__(self, value)
305 len_value = len(value)
306 len_self = len(self)
307 if len_value > len_self:
308 return False
309
310 for i in range(0, len_self - len_value + 1):
311 sub_list = self[i:i+len_value]
312 if sub_list == value:
313 return True
314 return False
315
316 def __repr__(self):
317 return pprint.pformat(list(self))
318
319
320def _check_and_set_parent(parent, value, name, new_name):
321 if not _is_instance_mock(value):
322 return False
323 if ((value._mock_name or value._mock_new_name) or
324 (value._mock_parent is not None) or
325 (value._mock_new_parent is not None)):
326 return False
327
328 _parent = parent
329 while _parent is not None:
330 # setting a mock (value) as a child or return value of itself
331 # should not modify the mock
332 if _parent is value:
333 return False
334 _parent = _parent._mock_new_parent
335
336 if new_name:
337 value._mock_new_parent = parent
338 value._mock_new_name = new_name
339 if name:
340 value._mock_parent = parent
341 value._mock_name = name
342 return True
343
Michael Foord01bafdc2014-04-14 16:09:42 -0400344# Internal class to identify if we wrapped an iterator object or not.
345class _MockIter(object):
346 def __init__(self, obj):
347 self.obj = iter(obj)
348 def __iter__(self):
349 return self
350 def __next__(self):
351 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700352
353class Base(object):
354 _mock_return_value = DEFAULT
355 _mock_side_effect = None
356 def __init__(self, *args, **kwargs):
357 pass
358
359
360
361class NonCallableMock(Base):
362 """A non-callable version of `Mock`"""
363
364 def __new__(cls, *args, **kw):
365 # every instance has its own class
366 # so we can create magic methods on the
367 # class without stomping on other mocks
368 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
369 instance = object.__new__(new)
370 return instance
371
372
373 def __init__(
374 self, spec=None, wraps=None, name=None, spec_set=None,
375 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530376 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700377 ):
378 if _new_parent is None:
379 _new_parent = parent
380
381 __dict__ = self.__dict__
382 __dict__['_mock_parent'] = parent
383 __dict__['_mock_name'] = name
384 __dict__['_mock_new_name'] = _new_name
385 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100386 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700387
388 if spec_set is not None:
389 spec = spec_set
390 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100391 if _eat_self is None:
392 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700393
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100394 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700395
396 __dict__['_mock_children'] = {}
397 __dict__['_mock_wraps'] = wraps
398 __dict__['_mock_delegate'] = None
399
400 __dict__['_mock_called'] = False
401 __dict__['_mock_call_args'] = None
402 __dict__['_mock_call_count'] = 0
403 __dict__['_mock_call_args_list'] = _CallList()
404 __dict__['_mock_mock_calls'] = _CallList()
405
406 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530407 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700408
409 if kwargs:
410 self.configure_mock(**kwargs)
411
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000412 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700413 spec, wraps, name, spec_set, parent,
414 _spec_state
415 )
416
417
418 def attach_mock(self, mock, attribute):
419 """
420 Attach a mock as an attribute of this one, replacing its name and
421 parent. Calls to the attached mock will be recorded in the
422 `method_calls` and `mock_calls` attributes of this one."""
423 mock._mock_parent = None
424 mock._mock_new_parent = None
425 mock._mock_name = ''
426 mock._mock_new_name = None
427
428 setattr(self, attribute, mock)
429
430
431 def mock_add_spec(self, spec, spec_set=False):
432 """Add a spec to a mock. `spec` can either be an object or a
433 list of strings. Only attributes on the `spec` can be fetched as
434 attributes from the mock.
435
436 If `spec_set` is True then only attributes on the spec can be set."""
437 self._mock_add_spec(spec, spec_set)
438
439
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100440 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
441 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700442 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100443 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700444
445 if spec is not None and not _is_list(spec):
446 if isinstance(spec, type):
447 _spec_class = spec
448 else:
449 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100450 res = _get_signature_object(spec,
451 _spec_as_instance, _eat_self)
452 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700453
454 spec = dir(spec)
455
456 __dict__ = self.__dict__
457 __dict__['_spec_class'] = _spec_class
458 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100459 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700460 __dict__['_mock_methods'] = spec
461
462
463 def __get_return_value(self):
464 ret = self._mock_return_value
465 if self._mock_delegate is not None:
466 ret = self._mock_delegate.return_value
467
468 if ret is DEFAULT:
469 ret = self._get_child_mock(
470 _new_parent=self, _new_name='()'
471 )
472 self.return_value = ret
473 return ret
474
475
476 def __set_return_value(self, value):
477 if self._mock_delegate is not None:
478 self._mock_delegate.return_value = value
479 else:
480 self._mock_return_value = value
481 _check_and_set_parent(self, value, None, '()')
482
483 __return_value_doc = "The value to be returned when the mock is called."
484 return_value = property(__get_return_value, __set_return_value,
485 __return_value_doc)
486
487
488 @property
489 def __class__(self):
490 if self._spec_class is None:
491 return type(self)
492 return self._spec_class
493
494 called = _delegating_property('called')
495 call_count = _delegating_property('call_count')
496 call_args = _delegating_property('call_args')
497 call_args_list = _delegating_property('call_args_list')
498 mock_calls = _delegating_property('mock_calls')
499
500
501 def __get_side_effect(self):
502 delegated = self._mock_delegate
503 if delegated is None:
504 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400505 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200506 if (sf is not None and not callable(sf)
507 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400508 sf = _MockIter(sf)
509 delegated.side_effect = sf
510 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700511
512 def __set_side_effect(self, value):
513 value = _try_iter(value)
514 delegated = self._mock_delegate
515 if delegated is None:
516 self._mock_side_effect = value
517 else:
518 delegated.side_effect = value
519
520 side_effect = property(__get_side_effect, __set_side_effect)
521
522
Kushal Das9cd39a12016-06-02 10:20:16 -0700523 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700524 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200525 if visited is None:
526 visited = []
527 if id(self) in visited:
528 return
529 visited.append(id(self))
530
Michael Foord345266a2012-03-14 12:24:34 -0700531 self.called = False
532 self.call_args = None
533 self.call_count = 0
534 self.mock_calls = _CallList()
535 self.call_args_list = _CallList()
536 self.method_calls = _CallList()
537
Kushal Das9cd39a12016-06-02 10:20:16 -0700538 if return_value:
539 self._mock_return_value = DEFAULT
540 if side_effect:
541 self._mock_side_effect = None
542
Michael Foord345266a2012-03-14 12:24:34 -0700543 for child in self._mock_children.values():
Miss Islington (bot)422c1652018-12-01 02:24:47 -0800544 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100545 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200546 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700547
548 ret = self._mock_return_value
549 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200550 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700551
552
553 def configure_mock(self, **kwargs):
554 """Set attributes on the mock through keyword arguments.
555
556 Attributes plus return values and side effects can be set on child
557 mocks using standard dot notation and unpacking a dictionary in the
558 method call:
559
560 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
561 >>> mock.configure_mock(**attrs)"""
562 for arg, val in sorted(kwargs.items(),
563 # we sort on the number of dots so that
564 # attributes are set before we set attributes on
565 # attributes
566 key=lambda entry: entry[0].count('.')):
567 args = arg.split('.')
568 final = args.pop()
569 obj = self
570 for entry in args:
571 obj = getattr(obj, entry)
572 setattr(obj, final, val)
573
574
575 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530576 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700577 raise AttributeError(name)
578 elif self._mock_methods is not None:
579 if name not in self._mock_methods or name in _all_magics:
580 raise AttributeError("Mock object has no attribute %r" % name)
581 elif _is_magic(name):
582 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530583 if not self._mock_unsafe:
584 if name.startswith(('assert', 'assret')):
585 raise AttributeError(name)
Michael Foord345266a2012-03-14 12:24:34 -0700586
587 result = self._mock_children.get(name)
588 if result is _deleted:
589 raise AttributeError(name)
590 elif result is None:
591 wraps = None
592 if self._mock_wraps is not None:
593 # XXXX should we get the attribute without triggering code
594 # execution?
595 wraps = getattr(self._mock_wraps, name)
596
597 result = self._get_child_mock(
598 parent=self, name=name, wraps=wraps, _new_name=name,
599 _new_parent=self
600 )
601 self._mock_children[name] = result
602
603 elif isinstance(result, _SpecState):
604 result = create_autospec(
605 result.spec, result.spec_set, result.instance,
606 result.parent, result.name
607 )
608 self._mock_children[name] = result
609
610 return result
611
612
Mario Corchero552be9d2017-10-17 12:35:11 +0100613 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700614 _name_list = [self._mock_new_name]
615 _parent = self._mock_new_parent
616 last = self
617
618 dot = '.'
619 if _name_list == ['()']:
620 dot = ''
621 seen = set()
622 while _parent is not None:
623 last = _parent
624
625 _name_list.append(_parent._mock_new_name + dot)
626 dot = '.'
627 if _parent._mock_new_name == '()':
628 dot = ''
629
630 _parent = _parent._mock_new_parent
631
632 # use ids here so as not to call __hash__ on the mocks
633 if id(_parent) in seen:
634 break
635 seen.add(id(_parent))
636
637 _name_list = list(reversed(_name_list))
638 _first = last._mock_name or 'mock'
639 if len(_name_list) > 1:
640 if _name_list[1] not in ('()', '().'):
641 _first += '.'
642 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100643 return ''.join(_name_list)
644
645 def __repr__(self):
646 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700647
648 name_string = ''
649 if name not in ('mock', 'mock.'):
650 name_string = ' name=%r' % name
651
652 spec_string = ''
653 if self._spec_class is not None:
654 spec_string = ' spec=%r'
655 if self._spec_set:
656 spec_string = ' spec_set=%r'
657 spec_string = spec_string % self._spec_class.__name__
658 return "<%s%s%s id='%s'>" % (
659 type(self).__name__,
660 name_string,
661 spec_string,
662 id(self)
663 )
664
665
666 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700667 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100668 if not FILTER_DIR:
669 return object.__dir__(self)
670
Michael Foord345266a2012-03-14 12:24:34 -0700671 extras = self._mock_methods or []
672 from_type = dir(type(self))
673 from_dict = list(self.__dict__)
674
Michael Foord313f85f2012-03-25 18:16:07 +0100675 from_type = [e for e in from_type if not e.startswith('_')]
676 from_dict = [e for e in from_dict if not e.startswith('_') or
677 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700678 return sorted(set(extras + from_type + from_dict +
679 list(self._mock_children)))
680
681
682 def __setattr__(self, name, value):
683 if name in _allowed_names:
684 # property setters go through here
685 return object.__setattr__(self, name, value)
686 elif (self._spec_set and self._mock_methods is not None and
687 name not in self._mock_methods and
688 name not in self.__dict__):
689 raise AttributeError("Mock object has no attribute '%s'" % name)
690 elif name in _unsupported_magics:
691 msg = 'Attempting to set unsupported magic method %r.' % name
692 raise AttributeError(msg)
693 elif name in _all_magics:
694 if self._mock_methods is not None and name not in self._mock_methods:
695 raise AttributeError("Mock object has no attribute '%s'" % name)
696
697 if not _is_instance_mock(value):
698 setattr(type(self), name, _get_method(name, value))
699 original = value
700 value = lambda *args, **kw: original(self, *args, **kw)
701 else:
702 # only set _new_name and not name so that mock_calls is tracked
703 # but not method calls
704 _check_and_set_parent(self, value, None, name)
705 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100706 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700707 elif name == '__class__':
708 self._spec_class = value
709 return
710 else:
711 if _check_and_set_parent(self, value, name, name):
712 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100713
714 if self._mock_sealed and not hasattr(self, name):
715 mock_name = f'{self._extract_mock_name()}.{name}'
716 raise AttributeError(f'Cannot set {mock_name}')
717
Michael Foord345266a2012-03-14 12:24:34 -0700718 return object.__setattr__(self, name, value)
719
720
721 def __delattr__(self, name):
722 if name in _all_magics and name in type(self).__dict__:
723 delattr(type(self), name)
724 if name not in self.__dict__:
725 # for magic methods that are still MagicProxy objects and
726 # not set on the instance itself
727 return
728
729 if name in self.__dict__:
730 object.__delattr__(self, name)
731
732 obj = self._mock_children.get(name, _missing)
733 if obj is _deleted:
734 raise AttributeError(name)
735 if obj is not _missing:
736 del self._mock_children[name]
737 self._mock_children[name] = _deleted
738
739
Michael Foord345266a2012-03-14 12:24:34 -0700740 def _format_mock_call_signature(self, args, kwargs):
741 name = self._mock_name or 'mock'
742 return _format_call_signature(name, args, kwargs)
743
744
745 def _format_mock_failure_message(self, args, kwargs):
746 message = 'Expected call: %s\nActual call: %s'
747 expected_string = self._format_mock_call_signature(args, kwargs)
748 call_args = self.call_args
749 if len(call_args) == 3:
750 call_args = call_args[1:]
751 actual_string = self._format_mock_call_signature(*call_args)
752 return message % (expected_string, actual_string)
753
754
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100755 def _call_matcher(self, _call):
756 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000757 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100758 comparison key suitable for matching with other calls.
759 This is a best effort method which relies on the spec's signature,
760 if available, or falls back on the arguments themselves.
761 """
762 sig = self._spec_signature
763 if sig is not None:
764 if len(_call) == 2:
765 name = ''
766 args, kwargs = _call
767 else:
768 name, args, kwargs = _call
769 try:
770 return name, sig.bind(*args, **kwargs)
771 except TypeError as e:
772 return e.with_traceback(None)
773 else:
774 return _call
775
Kushal Das68290f42014-04-17 01:54:07 +0530776 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530777 """assert that the mock was never called.
778 """
779 self = _mock_self
780 if self.call_count != 0:
781 msg = ("Expected '%s' to not have been called. Called %s times." %
782 (self._mock_name or 'mock', self.call_count))
783 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100784
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100785 def assert_called(_mock_self):
786 """assert that the mock was called at least once
787 """
788 self = _mock_self
789 if self.call_count == 0:
790 msg = ("Expected '%s' to have been called." %
791 self._mock_name or 'mock')
792 raise AssertionError(msg)
793
794 def assert_called_once(_mock_self):
795 """assert that the mock was called only once.
796 """
797 self = _mock_self
798 if not self.call_count == 1:
799 msg = ("Expected '%s' to have been called once. Called %s times." %
800 (self._mock_name or 'mock', self.call_count))
801 raise AssertionError(msg)
802
Michael Foord345266a2012-03-14 12:24:34 -0700803 def assert_called_with(_mock_self, *args, **kwargs):
804 """assert that the mock was called with the specified arguments.
805
806 Raises an AssertionError if the args and keyword args passed in are
807 different to the last call to the mock."""
808 self = _mock_self
809 if self.call_args is None:
810 expected = self._format_mock_call_signature(args, kwargs)
811 raise AssertionError('Expected call: %s\nNot called' % (expected,))
812
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100813 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700814 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100815 return msg
816 expected = self._call_matcher((args, kwargs))
817 actual = self._call_matcher(self.call_args)
818 if expected != actual:
819 cause = expected if isinstance(expected, Exception) else None
820 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700821
822
823 def assert_called_once_with(_mock_self, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100824 """assert that the mock was called exactly once and that that call was
825 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700826 self = _mock_self
827 if not self.call_count == 1:
Michael Foord28d591c2012-09-28 16:15:22 +0100828 msg = ("Expected '%s' to be called once. Called %s times." %
829 (self._mock_name or 'mock', self.call_count))
Michael Foord345266a2012-03-14 12:24:34 -0700830 raise AssertionError(msg)
831 return self.assert_called_with(*args, **kwargs)
832
833
834 def assert_has_calls(self, calls, any_order=False):
835 """assert the mock has been called with the specified calls.
836 The `mock_calls` list is checked for the calls.
837
838 If `any_order` is False (the default) then the calls must be
839 sequential. There can be extra calls before or after the
840 specified calls.
841
842 If `any_order` is True then the calls can be in any order, but
843 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100844 expected = [self._call_matcher(c) for c in calls]
845 cause = expected if isinstance(expected, Exception) else None
846 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700847 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100848 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700849 raise AssertionError(
850 'Calls not found.\nExpected: %r\n'
Senthil Kumaran121edbf2016-01-12 06:18:32 -0800851 'Actual: %r' % (_CallList(calls), self.mock_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100852 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700853 return
854
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100855 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700856
857 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100858 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700859 try:
860 all_calls.remove(kall)
861 except ValueError:
862 not_found.append(kall)
863 if not_found:
864 raise AssertionError(
865 '%r not all found in call list' % (tuple(not_found),)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100866 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700867
868
869 def assert_any_call(self, *args, **kwargs):
870 """assert the mock has been called with the specified arguments.
871
872 The assert passes if the mock has *ever* been called, unlike
873 `assert_called_with` and `assert_called_once_with` that only pass if
874 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100875 expected = self._call_matcher((args, kwargs))
876 actual = [self._call_matcher(c) for c in self.call_args_list]
877 if expected not in actual:
878 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700879 expected_string = self._format_mock_call_signature(args, kwargs)
880 raise AssertionError(
881 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100882 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700883
884
885 def _get_child_mock(self, **kw):
886 """Create the child mocks for attributes and return value.
887 By default child mocks will be the same type as the parent.
888 Subclasses of Mock may want to override this to customize the way
889 child mocks are made.
890
891 For non-callable mocks the callable variant will be used (rather than
892 any custom subclass)."""
893 _type = type(self)
894 if not issubclass(_type, CallableMixin):
895 if issubclass(_type, NonCallableMagicMock):
896 klass = MagicMock
897 elif issubclass(_type, NonCallableMock) :
898 klass = Mock
899 else:
900 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +0100901
902 if self._mock_sealed:
903 attribute = "." + kw["name"] if "name" in kw else "()"
904 mock_name = self._extract_mock_name() + attribute
905 raise AttributeError(mock_name)
906
Michael Foord345266a2012-03-14 12:24:34 -0700907 return klass(**kw)
908
909
910
911def _try_iter(obj):
912 if obj is None:
913 return obj
914 if _is_exception(obj):
915 return obj
916 if _callable(obj):
917 return obj
918 try:
919 return iter(obj)
920 except TypeError:
921 # XXXX backwards compatibility
922 # but this will blow up on first call - so maybe we should fail early?
923 return obj
924
925
926
927class CallableMixin(Base):
928
929 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
930 wraps=None, name=None, spec_set=None, parent=None,
931 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
932 self.__dict__['_mock_return_value'] = return_value
933
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000934 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700935 spec, wraps, name, spec_set, parent,
936 _spec_state, _new_name, _new_parent, **kwargs
937 )
938
939 self.side_effect = side_effect
940
941
942 def _mock_check_sig(self, *args, **kwargs):
943 # stub method that can be replaced with one with a specific signature
944 pass
945
946
947 def __call__(_mock_self, *args, **kwargs):
948 # can't use self in-case a function / method we are mocking uses self
949 # in the signature
950 _mock_self._mock_check_sig(*args, **kwargs)
951 return _mock_self._mock_call(*args, **kwargs)
952
953
954 def _mock_call(_mock_self, *args, **kwargs):
955 self = _mock_self
956 self.called = True
957 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100958
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800959 # handle call_args
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100960 _call = _Call((args, kwargs), two=True)
961 self.call_args = _call
962 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700963
964 seen = set()
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800965
966 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700967 do_method_calls = self._mock_parent is not None
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800968 method_call_name = self._mock_name
969
970 # initial stuff for mock_calls:
971 mock_call_name = self._mock_new_name
972 is_a_call = mock_call_name == '()'
973 self.mock_calls.append(_Call(('', args, kwargs)))
974
975 # follow up the chain of mocks:
976 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -0700977 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700978
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800979 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700980 if do_method_calls:
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800981 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -0700982 do_method_calls = _new_parent._mock_parent is not None
983 if do_method_calls:
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800984 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -0700985
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800986 # handle mock_calls:
987 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -0700988 _new_parent.mock_calls.append(this_mock_call)
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800989
990 if _new_parent._mock_new_name:
991 if is_a_call:
992 dot = ''
993 else:
994 dot = '.'
995 is_a_call = _new_parent._mock_new_name == '()'
996 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
997
998 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -0700999 _new_parent = _new_parent._mock_new_parent
1000
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -08001001 # check we're not in an infinite loop:
1002 # ( use ids here so as not to call __hash__ on the mocks)
Michael Foord345266a2012-03-14 12:24:34 -07001003 _new_parent_id = id(_new_parent)
1004 if _new_parent_id in seen:
1005 break
1006 seen.add(_new_parent_id)
1007
Michael Foord345266a2012-03-14 12:24:34 -07001008 effect = self.side_effect
1009 if effect is not None:
1010 if _is_exception(effect):
1011 raise effect
Miss Islington (bot)ee2c5a82018-12-08 03:47:01 -08001012 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001013 result = next(effect)
1014 if _is_exception(result):
1015 raise result
Miss Islington (bot)ee2c5a82018-12-08 03:47:01 -08001016 else:
1017 result = effect(*args, **kwargs)
1018
1019 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001020 return result
Michael Foord345266a2012-03-14 12:24:34 -07001021
Miss Islington (bot)ee2c5a82018-12-08 03:47:01 -08001022 if self._mock_return_value is not DEFAULT:
1023 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001024
Miss Islington (bot)ee2c5a82018-12-08 03:47:01 -08001025 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001026 return self._mock_wraps(*args, **kwargs)
Miss Islington (bot)ee2c5a82018-12-08 03:47:01 -08001027
1028 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001029
1030
1031
1032class Mock(CallableMixin, NonCallableMock):
1033 """
1034 Create a new `Mock` object. `Mock` takes several optional arguments
1035 that specify the behaviour of the Mock object:
1036
1037 * `spec`: This can be either a list of strings or an existing object (a
1038 class or instance) that acts as the specification for the mock object. If
1039 you pass in an object then a list of strings is formed by calling dir on
1040 the object (excluding unsupported magic attributes and methods). Accessing
1041 any attribute not in this list will raise an `AttributeError`.
1042
1043 If `spec` is an object (rather than a list of strings) then
1044 `mock.__class__` returns the class of the spec object. This allows mocks
1045 to pass `isinstance` tests.
1046
1047 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1048 or get an attribute on the mock that isn't on the object passed as
1049 `spec_set` will raise an `AttributeError`.
1050
1051 * `side_effect`: A function to be called whenever the Mock is called. See
1052 the `side_effect` attribute. Useful for raising exceptions or
1053 dynamically changing return values. The function is called with the same
1054 arguments as the mock, and unless it returns `DEFAULT`, the return
1055 value of this function is used as the return value.
1056
Michael Foord2cd48732012-04-21 15:52:11 +01001057 If `side_effect` is an iterable then each call to the mock will return
1058 the next value from the iterable. If any of the members of the iterable
1059 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001060
Michael Foord345266a2012-03-14 12:24:34 -07001061 * `return_value`: The value returned when the mock is called. By default
1062 this is a new Mock (created on first access). See the
1063 `return_value` attribute.
1064
Michael Foord0682a0c2012-04-13 20:51:20 +01001065 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1066 calling the Mock will pass the call through to the wrapped object
1067 (returning the real result). Attribute access on the mock will return a
1068 Mock object that wraps the corresponding attribute of the wrapped object
1069 (so attempting to access an attribute that doesn't exist will raise an
1070 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001071
1072 If the mock has an explicit `return_value` set then calls are not passed
1073 to the wrapped object and the `return_value` is returned instead.
1074
1075 * `name`: If the mock has a name then it will be used in the repr of the
1076 mock. This can be useful for debugging. The name is propagated to child
1077 mocks.
1078
1079 Mocks can also be called with arbitrary keyword arguments. These will be
1080 used to set attributes on the mock after it is created.
1081 """
1082
1083
1084
1085def _dot_lookup(thing, comp, import_path):
1086 try:
1087 return getattr(thing, comp)
1088 except AttributeError:
1089 __import__(import_path)
1090 return getattr(thing, comp)
1091
1092
1093def _importer(target):
1094 components = target.split('.')
1095 import_path = components.pop(0)
1096 thing = __import__(import_path)
1097
1098 for comp in components:
1099 import_path += ".%s" % comp
1100 thing = _dot_lookup(thing, comp, import_path)
1101 return thing
1102
1103
1104def _is_started(patcher):
1105 # XXXX horrible
1106 return hasattr(patcher, 'is_local')
1107
1108
1109class _patch(object):
1110
1111 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001112 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001113
1114 def __init__(
1115 self, getter, attribute, new, spec, create,
1116 spec_set, autospec, new_callable, kwargs
1117 ):
1118 if new_callable is not None:
1119 if new is not DEFAULT:
1120 raise ValueError(
1121 "Cannot use 'new' and 'new_callable' together"
1122 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001123 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001124 raise ValueError(
1125 "Cannot use 'autospec' and 'new_callable' together"
1126 )
1127
1128 self.getter = getter
1129 self.attribute = attribute
1130 self.new = new
1131 self.new_callable = new_callable
1132 self.spec = spec
1133 self.create = create
1134 self.has_local = False
1135 self.spec_set = spec_set
1136 self.autospec = autospec
1137 self.kwargs = kwargs
1138 self.additional_patchers = []
1139
1140
1141 def copy(self):
1142 patcher = _patch(
1143 self.getter, self.attribute, self.new, self.spec,
1144 self.create, self.spec_set,
1145 self.autospec, self.new_callable, self.kwargs
1146 )
1147 patcher.attribute_name = self.attribute_name
1148 patcher.additional_patchers = [
1149 p.copy() for p in self.additional_patchers
1150 ]
1151 return patcher
1152
1153
1154 def __call__(self, func):
1155 if isinstance(func, type):
1156 return self.decorate_class(func)
1157 return self.decorate_callable(func)
1158
1159
1160 def decorate_class(self, klass):
1161 for attr in dir(klass):
1162 if not attr.startswith(patch.TEST_PREFIX):
1163 continue
1164
1165 attr_value = getattr(klass, attr)
1166 if not hasattr(attr_value, "__call__"):
1167 continue
1168
1169 patcher = self.copy()
1170 setattr(klass, attr, patcher(attr_value))
1171 return klass
1172
1173
1174 def decorate_callable(self, func):
1175 if hasattr(func, 'patchings'):
1176 func.patchings.append(self)
1177 return func
1178
1179 @wraps(func)
1180 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001181 extra_args = []
1182 entered_patchers = []
1183
Michael Foord50a8c0e2012-03-25 18:57:58 +01001184 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001185 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001186 for patching in patched.patchings:
1187 arg = patching.__enter__()
1188 entered_patchers.append(patching)
1189 if patching.attribute_name is not None:
1190 keywargs.update(arg)
1191 elif patching.new is DEFAULT:
1192 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001193
Michael Foordd7c65e22012-03-14 14:56:54 -07001194 args += tuple(extra_args)
1195 return func(*args, **keywargs)
1196 except:
1197 if (patching not in entered_patchers and
1198 _is_started(patching)):
1199 # the patcher may have been started, but an exception
1200 # raised whilst entering one of its additional_patchers
1201 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001202 # Pass the exception to __exit__
1203 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001204 # re-raise the exception
1205 raise
Michael Foord345266a2012-03-14 12:24:34 -07001206 finally:
1207 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001208 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001209
1210 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001211 return patched
1212
1213
1214 def get_original(self):
1215 target = self.getter()
1216 name = self.attribute
1217
1218 original = DEFAULT
1219 local = False
1220
1221 try:
1222 original = target.__dict__[name]
1223 except (AttributeError, KeyError):
1224 original = getattr(target, name, DEFAULT)
1225 else:
1226 local = True
1227
Michael Foordfddcfa22014-04-14 16:25:20 -04001228 if name in _builtins and isinstance(target, ModuleType):
1229 self.create = True
1230
Michael Foord345266a2012-03-14 12:24:34 -07001231 if not self.create and original is DEFAULT:
1232 raise AttributeError(
1233 "%s does not have the attribute %r" % (target, name)
1234 )
1235 return original, local
1236
1237
1238 def __enter__(self):
1239 """Perform the patch."""
1240 new, spec, spec_set = self.new, self.spec, self.spec_set
1241 autospec, kwargs = self.autospec, self.kwargs
1242 new_callable = self.new_callable
1243 self.target = self.getter()
1244
Michael Foord50a8c0e2012-03-25 18:57:58 +01001245 # normalise False to None
1246 if spec is False:
1247 spec = None
1248 if spec_set is False:
1249 spec_set = None
1250 if autospec is False:
1251 autospec = None
1252
1253 if spec is not None and autospec is not None:
1254 raise TypeError("Can't specify spec and autospec")
1255 if ((spec is not None or autospec is not None) and
1256 spec_set not in (True, None)):
1257 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1258
Michael Foord345266a2012-03-14 12:24:34 -07001259 original, local = self.get_original()
1260
Michael Foord50a8c0e2012-03-25 18:57:58 +01001261 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001262 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001263 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001264 # set spec to the object we are replacing
1265 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001266 if spec_set is True:
1267 spec_set = original
1268 spec = None
1269 elif spec is not None:
1270 if spec_set is True:
1271 spec_set = spec
1272 spec = None
1273 elif spec_set is True:
1274 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001275
Michael Foord50a8c0e2012-03-25 18:57:58 +01001276 if spec is not None or spec_set is not None:
1277 if original is DEFAULT:
1278 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001279 if isinstance(original, type):
1280 # If we're patching out a class and there is a spec
1281 inherit = True
1282
1283 Klass = MagicMock
1284 _kwargs = {}
1285 if new_callable is not None:
1286 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001287 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001288 this_spec = spec
1289 if spec_set is not None:
1290 this_spec = spec_set
1291 if _is_list(this_spec):
1292 not_callable = '__call__' not in this_spec
1293 else:
1294 not_callable = not callable(this_spec)
1295 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001296 Klass = NonCallableMagicMock
1297
1298 if spec is not None:
1299 _kwargs['spec'] = spec
1300 if spec_set is not None:
1301 _kwargs['spec_set'] = spec_set
1302
1303 # add a name to mocks
1304 if (isinstance(Klass, type) and
1305 issubclass(Klass, NonCallableMock) and self.attribute):
1306 _kwargs['name'] = self.attribute
1307
1308 _kwargs.update(kwargs)
1309 new = Klass(**_kwargs)
1310
1311 if inherit and _is_instance_mock(new):
1312 # we can only tell if the instance should be callable if the
1313 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001314 this_spec = spec
1315 if spec_set is not None:
1316 this_spec = spec_set
1317 if (not _is_list(this_spec) and not
1318 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001319 Klass = NonCallableMagicMock
1320
1321 _kwargs.pop('name')
1322 new.return_value = Klass(_new_parent=new, _new_name='()',
1323 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001324 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001325 # spec is ignored, new *must* be default, spec_set is treated
1326 # as a boolean. Should we check spec is not None and that spec_set
1327 # is a bool?
1328 if new is not DEFAULT:
1329 raise TypeError(
1330 "autospec creates the mock for you. Can't specify "
1331 "autospec and new."
1332 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001333 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001334 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001335 spec_set = bool(spec_set)
1336 if autospec is True:
1337 autospec = original
1338
1339 new = create_autospec(autospec, spec_set=spec_set,
1340 _name=self.attribute, **kwargs)
1341 elif kwargs:
1342 # can't set keyword args when we aren't creating the mock
1343 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1344 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1345
1346 new_attr = new
1347
1348 self.temp_original = original
1349 self.is_local = local
1350 setattr(self.target, self.attribute, new_attr)
1351 if self.attribute_name is not None:
1352 extra_args = {}
1353 if self.new is DEFAULT:
1354 extra_args[self.attribute_name] = new
1355 for patching in self.additional_patchers:
1356 arg = patching.__enter__()
1357 if patching.new is DEFAULT:
1358 extra_args.update(arg)
1359 return extra_args
1360
1361 return new
1362
1363
Michael Foord50a8c0e2012-03-25 18:57:58 +01001364 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001365 """Undo the patch."""
1366 if not _is_started(self):
1367 raise RuntimeError('stop called on unstarted patcher')
1368
1369 if self.is_local and self.temp_original is not DEFAULT:
1370 setattr(self.target, self.attribute, self.temp_original)
1371 else:
1372 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001373 if not self.create and (not hasattr(self.target, self.attribute) or
1374 self.attribute in ('__doc__', '__module__',
1375 '__defaults__', '__annotations__',
1376 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001377 # needed for proxy objects like django settings
1378 setattr(self.target, self.attribute, self.temp_original)
1379
1380 del self.temp_original
1381 del self.is_local
1382 del self.target
1383 for patcher in reversed(self.additional_patchers):
1384 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001385 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001386
Michael Foordf7c41582012-06-10 20:36:32 +01001387
1388 def start(self):
1389 """Activate a patch, returning any created mock."""
1390 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001391 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001392 return result
1393
1394
1395 def stop(self):
1396 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001397 try:
1398 self._active_patches.remove(self)
1399 except ValueError:
1400 # If the patch hasn't been started this will fail
1401 pass
1402
Michael Foordf7c41582012-06-10 20:36:32 +01001403 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001404
1405
1406
1407def _get_target(target):
1408 try:
1409 target, attribute = target.rsplit('.', 1)
1410 except (TypeError, ValueError):
1411 raise TypeError("Need a valid target to patch. You supplied: %r" %
1412 (target,))
1413 getter = lambda: _importer(target)
1414 return getter, attribute
1415
1416
1417def _patch_object(
1418 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001419 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001420 new_callable=None, **kwargs
1421 ):
1422 """
Michael Foord345266a2012-03-14 12:24:34 -07001423 patch the named member (`attribute`) on an object (`target`) with a mock
1424 object.
1425
1426 `patch.object` can be used as a decorator, class decorator or a context
1427 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1428 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1429 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1430 the mock object it creates.
1431
1432 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1433 for choosing which methods to wrap.
1434 """
1435 getter = lambda: target
1436 return _patch(
1437 getter, attribute, new, spec, create,
1438 spec_set, autospec, new_callable, kwargs
1439 )
1440
1441
Michael Foord50a8c0e2012-03-25 18:57:58 +01001442def _patch_multiple(target, spec=None, create=False, spec_set=None,
1443 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001444 """Perform multiple patches in a single call. It takes the object to be
1445 patched (either as an object or a string to fetch the object by importing)
1446 and keyword arguments for the patches::
1447
1448 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1449 ...
1450
1451 Use `DEFAULT` as the value if you want `patch.multiple` to create
1452 mocks for you. In this case the created mocks are passed into a decorated
1453 function by keyword, and a dictionary is returned when `patch.multiple` is
1454 used as a context manager.
1455
1456 `patch.multiple` can be used as a decorator, class decorator or a context
1457 manager. The arguments `spec`, `spec_set`, `create`,
1458 `autospec` and `new_callable` have the same meaning as for `patch`. These
1459 arguments will be applied to *all* patches done by `patch.multiple`.
1460
1461 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1462 for choosing which methods to wrap.
1463 """
1464 if type(target) is str:
1465 getter = lambda: _importer(target)
1466 else:
1467 getter = lambda: target
1468
1469 if not kwargs:
1470 raise ValueError(
1471 'Must supply at least one keyword argument with patch.multiple'
1472 )
1473 # need to wrap in a list for python 3, where items is a view
1474 items = list(kwargs.items())
1475 attribute, new = items[0]
1476 patcher = _patch(
1477 getter, attribute, new, spec, create, spec_set,
1478 autospec, new_callable, {}
1479 )
1480 patcher.attribute_name = attribute
1481 for attribute, new in items[1:]:
1482 this_patcher = _patch(
1483 getter, attribute, new, spec, create, spec_set,
1484 autospec, new_callable, {}
1485 )
1486 this_patcher.attribute_name = attribute
1487 patcher.additional_patchers.append(this_patcher)
1488 return patcher
1489
1490
1491def patch(
1492 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001493 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001494 ):
1495 """
1496 `patch` acts as a function decorator, class decorator or a context
1497 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001498 is patched with a `new` object. When the function/with statement exits
1499 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001500
Michael Foord54b3db82012-03-28 15:08:08 +01001501 If `new` is omitted, then the target is replaced with a
1502 `MagicMock`. If `patch` is used as a decorator and `new` is
1503 omitted, the created mock is passed in as an extra argument to the
1504 decorated function. If `patch` is used as a context manager the created
1505 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001506
Michael Foord54b3db82012-03-28 15:08:08 +01001507 `target` should be a string in the form `'package.module.ClassName'`. The
1508 `target` is imported and the specified object replaced with the `new`
1509 object, so the `target` must be importable from the environment you are
1510 calling `patch` from. The target is imported when the decorated function
1511 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001512
1513 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1514 if patch is creating one for you.
1515
1516 In addition you can pass `spec=True` or `spec_set=True`, which causes
1517 patch to pass in the object being mocked as the spec/spec_set object.
1518
1519 `new_callable` allows you to specify a different class, or callable object,
1520 that will be called to create the `new` object. By default `MagicMock` is
1521 used.
1522
1523 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001524 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001525 All attributes of the mock will also have the spec of the corresponding
1526 attribute of the object being replaced. Methods and functions being
1527 mocked will have their arguments checked and will raise a `TypeError` if
1528 they are called with the wrong signature. For mocks replacing a class,
1529 their return value (the 'instance') will have the same spec as the class.
1530
1531 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1532 arbitrary object as the spec instead of the one being replaced.
1533
1534 By default `patch` will fail to replace attributes that don't exist. If
1535 you pass in `create=True`, and the attribute doesn't exist, patch will
1536 create the attribute for you when the patched function is called, and
1537 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001538 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001539 default because it can be dangerous. With it switched on you can write
1540 passing tests against APIs that don't actually exist!
1541
1542 Patch can be used as a `TestCase` class decorator. It works by
1543 decorating each test method in the class. This reduces the boilerplate
1544 code when your test methods share a common patchings set. `patch` finds
1545 tests by looking for method names that start with `patch.TEST_PREFIX`.
1546 By default this is `test`, which matches the way `unittest` finds tests.
1547 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1548
1549 Patch can be used as a context manager, with the with statement. Here the
1550 patching applies to the indented block after the with statement. If you
1551 use "as" then the patched object will be bound to the name after the
1552 "as"; very useful if `patch` is creating a mock object for you.
1553
1554 `patch` takes arbitrary keyword arguments. These will be passed to
1555 the `Mock` (or `new_callable`) on construction.
1556
1557 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1558 available for alternate use-cases.
1559 """
1560 getter, attribute = _get_target(target)
1561 return _patch(
1562 getter, attribute, new, spec, create,
1563 spec_set, autospec, new_callable, kwargs
1564 )
1565
1566
1567class _patch_dict(object):
1568 """
1569 Patch a dictionary, or dictionary like object, and restore the dictionary
1570 to its original state after the test.
1571
1572 `in_dict` can be a dictionary or a mapping like container. If it is a
1573 mapping then it must at least support getting, setting and deleting items
1574 plus iterating over keys.
1575
1576 `in_dict` can also be a string specifying the name of the dictionary, which
1577 will then be fetched by importing it.
1578
1579 `values` can be a dictionary of values to set in the dictionary. `values`
1580 can also be an iterable of `(key, value)` pairs.
1581
1582 If `clear` is True then the dictionary will be cleared before the new
1583 values are set.
1584
1585 `patch.dict` can also be called with arbitrary keyword arguments to set
1586 values in the dictionary::
1587
1588 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1589 ...
1590
1591 `patch.dict` can be used as a context manager, decorator or class
1592 decorator. When used as a class decorator `patch.dict` honours
1593 `patch.TEST_PREFIX` for choosing which methods to wrap.
1594 """
1595
1596 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1597 if isinstance(in_dict, str):
1598 in_dict = _importer(in_dict)
1599 self.in_dict = in_dict
1600 # support any argument supported by dict(...) constructor
1601 self.values = dict(values)
1602 self.values.update(kwargs)
1603 self.clear = clear
1604 self._original = None
1605
1606
1607 def __call__(self, f):
1608 if isinstance(f, type):
1609 return self.decorate_class(f)
1610 @wraps(f)
1611 def _inner(*args, **kw):
1612 self._patch_dict()
1613 try:
1614 return f(*args, **kw)
1615 finally:
1616 self._unpatch_dict()
1617
1618 return _inner
1619
1620
1621 def decorate_class(self, klass):
1622 for attr in dir(klass):
1623 attr_value = getattr(klass, attr)
1624 if (attr.startswith(patch.TEST_PREFIX) and
1625 hasattr(attr_value, "__call__")):
1626 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1627 decorated = decorator(attr_value)
1628 setattr(klass, attr, decorated)
1629 return klass
1630
1631
1632 def __enter__(self):
1633 """Patch the dict."""
1634 self._patch_dict()
1635
1636
1637 def _patch_dict(self):
1638 values = self.values
1639 in_dict = self.in_dict
1640 clear = self.clear
1641
1642 try:
1643 original = in_dict.copy()
1644 except AttributeError:
1645 # dict like object with no copy method
1646 # must support iteration over keys
1647 original = {}
1648 for key in in_dict:
1649 original[key] = in_dict[key]
1650 self._original = original
1651
1652 if clear:
1653 _clear_dict(in_dict)
1654
1655 try:
1656 in_dict.update(values)
1657 except AttributeError:
1658 # dict like object with no update method
1659 for key in values:
1660 in_dict[key] = values[key]
1661
1662
1663 def _unpatch_dict(self):
1664 in_dict = self.in_dict
1665 original = self._original
1666
1667 _clear_dict(in_dict)
1668
1669 try:
1670 in_dict.update(original)
1671 except AttributeError:
1672 for key in original:
1673 in_dict[key] = original[key]
1674
1675
1676 def __exit__(self, *args):
1677 """Unpatch the dict."""
1678 self._unpatch_dict()
1679 return False
1680
1681 start = __enter__
1682 stop = __exit__
1683
1684
1685def _clear_dict(in_dict):
1686 try:
1687 in_dict.clear()
1688 except AttributeError:
1689 keys = list(in_dict)
1690 for key in keys:
1691 del in_dict[key]
1692
1693
Michael Foordf7c41582012-06-10 20:36:32 +01001694def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001695 """Stop all active patches. LIFO to unroll nested patches."""
1696 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001697 patch.stop()
1698
1699
Michael Foord345266a2012-03-14 12:24:34 -07001700patch.object = _patch_object
1701patch.dict = _patch_dict
1702patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001703patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001704patch.TEST_PREFIX = 'test'
1705
1706magic_methods = (
1707 "lt le gt ge eq ne "
1708 "getitem setitem delitem "
1709 "len contains iter "
1710 "hash str sizeof "
1711 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001712 # we added divmod and rdivmod here instead of numerics
1713 # because there is no idivmod
1714 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001715 "complex int float index "
1716 "trunc floor ceil "
1717 "bool next "
1718)
1719
Michael Foordd2623d72014-04-14 11:23:48 -04001720numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001721 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001722)
Michael Foord345266a2012-03-14 12:24:34 -07001723inplace = ' '.join('i%s' % n for n in numerics.split())
1724right = ' '.join('r%s' % n for n in numerics.split())
1725
1726# not including __prepare__, __instancecheck__, __subclasscheck__
1727# (as they are metaclass methods)
1728# __del__ is not supported at all as it causes problems if it exists
1729
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001730_non_defaults = {
1731 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1732 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1733 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1734 '__repr__', '__dir__', '__subclasses__', '__format__',
Serhiy Storchaka5943ea72016-06-19 18:30:43 +03001735 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001736}
Michael Foord345266a2012-03-14 12:24:34 -07001737
1738
1739def _get_method(name, func):
1740 "Turns a callable object (like a mock) into a real function"
1741 def method(self, *args, **kw):
1742 return func(self, *args, **kw)
1743 method.__name__ = name
1744 return method
1745
1746
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001747_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001748 '__%s__' % method for method in
1749 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001750}
Michael Foord345266a2012-03-14 12:24:34 -07001751
1752_all_magics = _magics | _non_defaults
1753
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001754_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001755 '__getattr__', '__setattr__',
Miss Islington (bot)7beb8c52018-11-05 06:52:58 -08001756 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001757 '__instancecheck__', '__subclasscheck__',
1758 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001759}
Michael Foord345266a2012-03-14 12:24:34 -07001760
1761_calculate_return_value = {
1762 '__hash__': lambda self: object.__hash__(self),
1763 '__str__': lambda self: object.__str__(self),
1764 '__sizeof__': lambda self: object.__sizeof__(self),
1765}
1766
1767_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001768 '__lt__': NotImplemented,
1769 '__gt__': NotImplemented,
1770 '__le__': NotImplemented,
1771 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001772 '__int__': 1,
1773 '__contains__': False,
1774 '__len__': 0,
1775 '__exit__': False,
1776 '__complex__': 1j,
1777 '__float__': 1.0,
1778 '__bool__': True,
1779 '__index__': 1,
1780}
1781
1782
1783def _get_eq(self):
1784 def __eq__(other):
1785 ret_val = self.__eq__._mock_return_value
1786 if ret_val is not DEFAULT:
1787 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001788 if self is other:
1789 return True
1790 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001791 return __eq__
1792
1793def _get_ne(self):
1794 def __ne__(other):
1795 if self.__ne__._mock_return_value is not DEFAULT:
1796 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001797 if self is other:
1798 return False
1799 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001800 return __ne__
1801
1802def _get_iter(self):
1803 def __iter__():
1804 ret_val = self.__iter__._mock_return_value
1805 if ret_val is DEFAULT:
1806 return iter([])
1807 # if ret_val was already an iterator, then calling iter on it should
1808 # return the iterator unchanged
1809 return iter(ret_val)
1810 return __iter__
1811
1812_side_effect_methods = {
1813 '__eq__': _get_eq,
1814 '__ne__': _get_ne,
1815 '__iter__': _get_iter,
1816}
1817
1818
1819
1820def _set_return_value(mock, method, name):
1821 fixed = _return_values.get(name, DEFAULT)
1822 if fixed is not DEFAULT:
1823 method.return_value = fixed
1824 return
1825
1826 return_calulator = _calculate_return_value.get(name)
1827 if return_calulator is not None:
1828 try:
1829 return_value = return_calulator(mock)
1830 except AttributeError:
1831 # XXXX why do we return AttributeError here?
1832 # set it as a side_effect instead?
1833 return_value = AttributeError(name)
1834 method.return_value = return_value
1835 return
1836
1837 side_effector = _side_effect_methods.get(name)
1838 if side_effector is not None:
1839 method.side_effect = side_effector(mock)
1840
1841
1842
1843class MagicMixin(object):
1844 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001845 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001846 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001847 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001848
1849
1850 def _mock_set_magics(self):
1851 these_magics = _magics
1852
Łukasz Langaa468db92015-04-13 23:12:42 -07001853 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001854 these_magics = _magics.intersection(self._mock_methods)
1855
1856 remove_magics = set()
1857 remove_magics = _magics - these_magics
1858
1859 for entry in remove_magics:
1860 if entry in type(self).__dict__:
1861 # remove unneeded magic methods
1862 delattr(self, entry)
1863
1864 # don't overwrite existing attributes if called a second time
1865 these_magics = these_magics - set(type(self).__dict__)
1866
1867 _type = type(self)
1868 for entry in these_magics:
1869 setattr(_type, entry, MagicProxy(entry, self))
1870
1871
1872
1873class NonCallableMagicMock(MagicMixin, NonCallableMock):
1874 """A version of `MagicMock` that isn't callable."""
1875 def mock_add_spec(self, spec, spec_set=False):
1876 """Add a spec to a mock. `spec` can either be an object or a
1877 list of strings. Only attributes on the `spec` can be fetched as
1878 attributes from the mock.
1879
1880 If `spec_set` is True then only attributes on the spec can be set."""
1881 self._mock_add_spec(spec, spec_set)
1882 self._mock_set_magics()
1883
1884
1885
1886class MagicMock(MagicMixin, Mock):
1887 """
1888 MagicMock is a subclass of Mock with default implementations
1889 of most of the magic methods. You can use MagicMock without having to
1890 configure the magic methods yourself.
1891
1892 If you use the `spec` or `spec_set` arguments then *only* magic
1893 methods that exist in the spec will be created.
1894
1895 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1896 """
1897 def mock_add_spec(self, spec, spec_set=False):
1898 """Add a spec to a mock. `spec` can either be an object or a
1899 list of strings. Only attributes on the `spec` can be fetched as
1900 attributes from the mock.
1901
1902 If `spec_set` is True then only attributes on the spec can be set."""
1903 self._mock_add_spec(spec, spec_set)
1904 self._mock_set_magics()
1905
1906
1907
1908class MagicProxy(object):
1909 def __init__(self, name, parent):
1910 self.name = name
1911 self.parent = parent
1912
1913 def __call__(self, *args, **kwargs):
1914 m = self.create_mock()
1915 return m(*args, **kwargs)
1916
1917 def create_mock(self):
1918 entry = self.name
1919 parent = self.parent
1920 m = parent._get_child_mock(name=entry, _new_name=entry,
1921 _new_parent=parent)
1922 setattr(parent, entry, m)
1923 _set_return_value(parent, m, entry)
1924 return m
1925
1926 def __get__(self, obj, _type=None):
1927 return self.create_mock()
1928
1929
1930
1931class _ANY(object):
1932 "A helper object that compares equal to everything."
1933
1934 def __eq__(self, other):
1935 return True
1936
1937 def __ne__(self, other):
1938 return False
1939
1940 def __repr__(self):
1941 return '<ANY>'
1942
1943ANY = _ANY()
1944
1945
1946
1947def _format_call_signature(name, args, kwargs):
1948 message = '%s(%%s)' % name
1949 formatted_args = ''
1950 args_string = ', '.join([repr(arg) for arg in args])
1951 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301952 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001953 ])
1954 if args_string:
1955 formatted_args = args_string
1956 if kwargs_string:
1957 if formatted_args:
1958 formatted_args += ', '
1959 formatted_args += kwargs_string
1960
1961 return message % formatted_args
1962
1963
1964
1965class _Call(tuple):
1966 """
1967 A tuple for holding the results of a call to a mock, either in the form
1968 `(args, kwargs)` or `(name, args, kwargs)`.
1969
1970 If args or kwargs are empty then a call tuple will compare equal to
1971 a tuple without those values. This makes comparisons less verbose::
1972
1973 _Call(('name', (), {})) == ('name',)
1974 _Call(('name', (1,), {})) == ('name', (1,))
1975 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1976
1977 The `_Call` object provides a useful shortcut for comparing with call::
1978
1979 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1980 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1981
1982 If the _Call has no name then it will match any name.
1983 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01001984 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07001985 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07001986 args = ()
1987 kwargs = {}
1988 _len = len(value)
1989 if _len == 3:
1990 name, args, kwargs = value
1991 elif _len == 2:
1992 first, second = value
1993 if isinstance(first, str):
1994 name = first
1995 if isinstance(second, tuple):
1996 args = second
1997 else:
1998 kwargs = second
1999 else:
2000 args, kwargs = first, second
2001 elif _len == 1:
2002 value, = value
2003 if isinstance(value, str):
2004 name = value
2005 elif isinstance(value, tuple):
2006 args = value
2007 else:
2008 kwargs = value
2009
2010 if two:
2011 return tuple.__new__(cls, (args, kwargs))
2012
2013 return tuple.__new__(cls, (name, args, kwargs))
2014
2015
2016 def __init__(self, value=(), name=None, parent=None, two=False,
2017 from_kall=True):
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002018 self._mock_name = name
2019 self._mock_parent = parent
2020 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002021
2022
2023 def __eq__(self, other):
2024 if other is ANY:
2025 return True
2026 try:
2027 len_other = len(other)
2028 except TypeError:
2029 return False
2030
2031 self_name = ''
2032 if len(self) == 2:
2033 self_args, self_kwargs = self
2034 else:
2035 self_name, self_args, self_kwargs = self
2036
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002037 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2038 and self._mock_parent != other._mock_parent):
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -08002039 return False
2040
Michael Foord345266a2012-03-14 12:24:34 -07002041 other_name = ''
2042 if len_other == 0:
2043 other_args, other_kwargs = (), {}
2044 elif len_other == 3:
2045 other_name, other_args, other_kwargs = other
2046 elif len_other == 1:
2047 value, = other
2048 if isinstance(value, tuple):
2049 other_args = value
2050 other_kwargs = {}
2051 elif isinstance(value, str):
2052 other_name = value
2053 other_args, other_kwargs = (), {}
2054 else:
2055 other_args = ()
2056 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002057 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002058 # could be (name, args) or (name, kwargs) or (args, kwargs)
2059 first, second = other
2060 if isinstance(first, str):
2061 other_name = first
2062 if isinstance(second, tuple):
2063 other_args, other_kwargs = second, {}
2064 else:
2065 other_args, other_kwargs = (), second
2066 else:
2067 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002068 else:
2069 return False
Michael Foord345266a2012-03-14 12:24:34 -07002070
2071 if self_name and other_name != self_name:
2072 return False
2073
2074 # this order is important for ANY to work!
2075 return (other_args, other_kwargs) == (self_args, self_kwargs)
2076
2077
Berker Peksagce913872016-03-28 00:30:02 +03002078 __ne__ = object.__ne__
2079
2080
Michael Foord345266a2012-03-14 12:24:34 -07002081 def __call__(self, *args, **kwargs):
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002082 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002083 return _Call(('', args, kwargs), name='()')
2084
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002085 name = self._mock_name + '()'
2086 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002087
2088
2089 def __getattr__(self, attr):
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002090 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002091 return _Call(name=attr, from_kall=False)
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002092 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002093 return _Call(name=name, parent=self, from_kall=False)
2094
2095
Kushal Dasa37b9582014-09-16 18:33:37 +05302096 def count(self, *args, **kwargs):
2097 return self.__getattr__('count')(*args, **kwargs)
2098
2099 def index(self, *args, **kwargs):
2100 return self.__getattr__('index')(*args, **kwargs)
2101
Michael Foord345266a2012-03-14 12:24:34 -07002102 def __repr__(self):
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002103 if not self._mock_from_kall:
2104 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002105 if name.startswith('()'):
2106 name = 'call%s' % name
2107 return name
2108
2109 if len(self) == 2:
2110 name = 'call'
2111 args, kwargs = self
2112 else:
2113 name, args, kwargs = self
2114 if not name:
2115 name = 'call'
2116 elif not name.startswith('()'):
2117 name = 'call.%s' % name
2118 else:
2119 name = 'call%s' % name
2120 return _format_call_signature(name, args, kwargs)
2121
2122
2123 def call_list(self):
2124 """For a call object that represents multiple calls, `call_list`
2125 returns a list of all the intermediate calls as well as the
2126 final call."""
2127 vals = []
2128 thing = self
2129 while thing is not None:
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002130 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002131 vals.append(thing)
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002132 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002133 return _CallList(reversed(vals))
2134
2135
2136call = _Call(from_kall=False)
2137
2138
2139
2140def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2141 _name=None, **kwargs):
2142 """Create a mock object using another object as a spec. Attributes on the
2143 mock will use the corresponding attribute on the `spec` object as their
2144 spec.
2145
2146 Functions or methods being mocked will have their arguments checked
2147 to check that they are called with the correct signature.
2148
2149 If `spec_set` is True then attempting to set attributes that don't exist
2150 on the spec object will raise an `AttributeError`.
2151
2152 If a class is used as a spec then the return value of the mock (the
2153 instance of the class) will have the same spec. You can use a class as the
2154 spec for an instance object by passing `instance=True`. The returned mock
2155 will only be callable if instances of the mock are callable.
2156
2157 `create_autospec` also takes arbitrary keyword arguments that are passed to
2158 the constructor of the created mock."""
2159 if _is_list(spec):
2160 # can't pass a list instance to the mock constructor as it will be
2161 # interpreted as a list of strings
2162 spec = type(spec)
2163
2164 is_type = isinstance(spec, type)
2165
2166 _kwargs = {'spec': spec}
2167 if spec_set:
2168 _kwargs = {'spec_set': spec}
2169 elif spec is None:
2170 # None we mock with a normal mock without a spec
2171 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002172 if _kwargs and instance:
2173 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002174
2175 _kwargs.update(kwargs)
2176
2177 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002178 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002179 # descriptors don't have a spec
2180 # because we don't know what type they return
2181 _kwargs = {}
2182 elif not _callable(spec):
2183 Klass = NonCallableMagicMock
2184 elif is_type and instance and not _instance_callable(spec):
2185 Klass = NonCallableMagicMock
2186
Kushal Das484f8a82014-04-16 01:05:50 +05302187 _name = _kwargs.pop('name', _name)
2188
Michael Foord345266a2012-03-14 12:24:34 -07002189 _new_name = _name
2190 if _parent is None:
2191 # for a top level object no _new_name should be set
2192 _new_name = ''
2193
2194 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2195 name=_name, **_kwargs)
2196
2197 if isinstance(spec, FunctionTypes):
2198 # should only happen at the top level because we don't
2199 # recurse for functions
2200 mock = _set_signature(mock, spec)
2201 else:
2202 _check_signature(spec, mock, is_type, instance)
2203
2204 if _parent is not None and not instance:
2205 _parent._mock_children[_name] = mock
2206
2207 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002208 mock.return_value = create_autospec(spec, spec_set, instance=True,
2209 _name='()', _parent=mock)
2210
2211 for entry in dir(spec):
2212 if _is_magic(entry):
2213 # MagicMock already does the useful magic methods for us
2214 continue
2215
Michael Foord345266a2012-03-14 12:24:34 -07002216 # XXXX do we need a better way of getting attributes without
2217 # triggering code execution (?) Probably not - we need the actual
2218 # object to mock it so we would rather trigger a property than mock
2219 # the property descriptor. Likewise we want to mock out dynamically
2220 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002221 # XXXX what about attributes that raise exceptions other than
2222 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002223 # we could be resilient against it, or catch and propagate the
2224 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002225 try:
2226 original = getattr(spec, entry)
2227 except AttributeError:
2228 continue
Michael Foord345266a2012-03-14 12:24:34 -07002229
2230 kwargs = {'spec': original}
2231 if spec_set:
2232 kwargs = {'spec_set': original}
2233
2234 if not isinstance(original, FunctionTypes):
2235 new = _SpecState(original, spec_set, mock, entry, instance)
2236 mock._mock_children[entry] = new
2237 else:
2238 parent = mock
2239 if isinstance(spec, FunctionTypes):
2240 parent = mock.mock
2241
Michael Foord345266a2012-03-14 12:24:34 -07002242 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002243 kwargs['_eat_self'] = skipfirst
2244 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2245 _new_parent=parent,
2246 **kwargs)
2247 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002248 _check_signature(original, new, skipfirst=skipfirst)
2249
2250 # so functions created with _set_signature become instance attributes,
2251 # *plus* their underlying mock exists in _mock_children of the parent
2252 # mock. Adding to _mock_children may be unnecessary where we are also
2253 # setting as an instance attribute?
2254 if isinstance(new, FunctionTypes):
2255 setattr(mock, entry, new)
2256
2257 return mock
2258
2259
2260def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002261 """
2262 Return whether we should skip the first argument on spec's `entry`
2263 attribute.
2264 """
Michael Foord345266a2012-03-14 12:24:34 -07002265 if not isinstance(spec, type):
2266 if entry in getattr(spec, '__dict__', {}):
2267 # instance attribute - shouldn't skip
2268 return False
Michael Foord345266a2012-03-14 12:24:34 -07002269 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002270
2271 for klass in spec.__mro__:
2272 result = klass.__dict__.get(entry, DEFAULT)
2273 if result is DEFAULT:
2274 continue
2275 if isinstance(result, (staticmethod, classmethod)):
2276 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002277 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2278 # Normal method => skip if looked up on type
2279 # (if looked up on instance, self is already skipped)
2280 return is_type
2281 else:
2282 return False
Michael Foord345266a2012-03-14 12:24:34 -07002283
2284 # shouldn't get here unless function is a dynamically provided attribute
2285 # XXXX untested behaviour
2286 return is_type
2287
2288
2289def _get_class(obj):
2290 try:
2291 return obj.__class__
2292 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002293 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002294 return type(obj)
2295
2296
2297class _SpecState(object):
2298
2299 def __init__(self, spec, spec_set=False, parent=None,
2300 name=None, ids=None, instance=False):
2301 self.spec = spec
2302 self.ids = ids
2303 self.spec_set = spec_set
2304 self.parent = parent
2305 self.instance = instance
2306 self.name = name
2307
2308
2309FunctionTypes = (
2310 # python function
2311 type(create_autospec),
2312 # instance method
2313 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002314)
2315
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002316MethodWrapperTypes = (
2317 type(ANY.__eq__.__get__),
2318)
2319
Michael Foord345266a2012-03-14 12:24:34 -07002320
Michael Foorda74561a2012-03-25 19:03:13 +01002321file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002322
Michael Foord04cbe0c2013-03-19 17:22:51 -07002323def _iterate_read_data(read_data):
2324 # Helper for mock_open:
2325 # Retrieve lines from read_data via a generator so that separate calls to
2326 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002327 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2328 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002329
Berker Peksag86b34da2015-08-06 13:15:51 +03002330 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002331 # If the last line ended in a newline, the list comprehension will have an
2332 # extra entry that's just a newline. Remove this.
2333 data_as_list = data_as_list[:-1]
2334 else:
2335 # If there wasn't an extra newline by itself, then the file being
2336 # emulated doesn't have a newline to end the last line remove the
2337 # newline that our naive format() added
2338 data_as_list[-1] = data_as_list[-1][:-1]
2339
2340 for line in data_as_list:
2341 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002342
Robert Collins5329aaa2015-07-17 20:08:45 +12002343
Michael Foord0dccf652012-03-25 19:11:50 +01002344def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002345 """
2346 A helper function to create a mock to replace the use of `open`. It works
2347 for `open` called directly or used as a context manager.
2348
2349 The `mock` argument is the mock object to configure. If `None` (the
2350 default) then a `MagicMock` will be created for you, with the API limited
2351 to methods or attributes available on standard file handles.
2352
Michael Foord04cbe0c2013-03-19 17:22:51 -07002353 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2354 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002355 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002356 def _readlines_side_effect(*args, **kwargs):
2357 if handle.readlines.return_value is not None:
2358 return handle.readlines.return_value
2359 return list(_state[0])
2360
2361 def _read_side_effect(*args, **kwargs):
2362 if handle.read.return_value is not None:
2363 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002364 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002365
2366 def _readline_side_effect():
Miss Islington (bot)c83c3752018-09-14 14:30:04 -07002367 yield from _iter_side_effect()
2368 while True:
2369 yield type(read_data)()
2370
2371 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002372 if handle.readline.return_value is not None:
2373 while True:
2374 yield handle.readline.return_value
2375 for line in _state[0]:
2376 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002377
Michael Foorda74561a2012-03-25 19:03:13 +01002378 global file_spec
2379 if file_spec is None:
2380 import _io
2381 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2382
Michael Foord345266a2012-03-14 12:24:34 -07002383 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002384 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002385
Robert Collinsca647ef2015-07-24 03:48:20 +12002386 handle = MagicMock(spec=file_spec)
2387 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002388
Robert Collinsca647ef2015-07-24 03:48:20 +12002389 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002390
Robert Collinsca647ef2015-07-24 03:48:20 +12002391 handle.write.return_value = None
2392 handle.read.return_value = None
2393 handle.readline.return_value = None
2394 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002395
Robert Collinsca647ef2015-07-24 03:48:20 +12002396 handle.read.side_effect = _read_side_effect
2397 _state[1] = _readline_side_effect()
2398 handle.readline.side_effect = _state[1]
2399 handle.readlines.side_effect = _readlines_side_effect
Miss Islington (bot)c83c3752018-09-14 14:30:04 -07002400 handle.__iter__.side_effect = _iter_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002401
Robert Collinsca647ef2015-07-24 03:48:20 +12002402 def reset_data(*args, **kwargs):
2403 _state[0] = _iterate_read_data(read_data)
2404 if handle.readline.side_effect == _state[1]:
2405 # Only reset the side effect if the user hasn't overridden it.
2406 _state[1] = _readline_side_effect()
2407 handle.readline.side_effect = _state[1]
2408 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002409
Robert Collinsca647ef2015-07-24 03:48:20 +12002410 mock.side_effect = reset_data
2411 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002412 return mock
2413
2414
2415class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002416 """
2417 A mock intended to be used as a property, or other descriptor, on a class.
2418 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2419 a return value when it is fetched.
2420
2421 Fetching a `PropertyMock` instance from an object calls the mock, with
2422 no args. Setting it calls the mock with the value being set.
2423 """
Michael Foordc2870622012-04-13 16:57:22 +01002424 def _get_child_mock(self, **kwargs):
2425 return MagicMock(**kwargs)
2426
Michael Foord345266a2012-03-14 12:24:34 -07002427 def __get__(self, obj, obj_type):
2428 return self()
2429 def __set__(self, obj, val):
2430 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002431
2432
2433def seal(mock):
Miss Islington (bot)984a8002018-10-19 15:17:31 -07002434 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002435
2436 Given an input Mock, seals it to ensure no further mocks will be generated
2437 when accessing an attribute that was not already defined.
2438
Miss Islington (bot)984a8002018-10-19 15:17:31 -07002439 The operation recursively seals the mock passed in, meaning that
2440 the mock itself, any mocks generated by accessing one of its attributes,
2441 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002442 """
2443 mock._mock_sealed = True
2444 for attr in dir(mock):
2445 try:
2446 m = getattr(mock, attr)
2447 except AttributeError:
2448 continue
2449 if not isinstance(m, NonCallableMock):
2450 continue
2451 if m._mock_new_parent is mock:
2452 seal(m)