blob: 47ed06c6f486afc99a67c345c3e4d2fdc14dc959 [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001# mock.py
2# Test tools for mocking and patching.
Michael Foordc17adf42012-03-14 13:30:29 -07003# Maintained by Michael Foord
4# Backport for other versions of Python available from
Ned Deily9d6d06e2018-06-11 00:45:50 -04005# https://pypi.org/project/mock
Michael Foord345266a2012-03-14 12:24:34 -07006
7__all__ = (
8 'Mock',
9 'MagicMock',
10 'patch',
11 'sentinel',
12 'DEFAULT',
13 'ANY',
14 'call',
15 'create_autospec',
16 'FILTER_DIR',
17 'NonCallableMock',
18 'NonCallableMagicMock',
19 'mock_open',
20 'PropertyMock',
Mario Corchero552be9d2017-10-17 12:35:11 +010021 'seal',
Michael Foord345266a2012-03-14 12:24:34 -070022)
23
24
25__version__ = '1.0'
26
27
Rémi Lapeyre11a88322019-05-07 12:48:36 +020028import io
Michael Foord345266a2012-03-14 12:24:34 -070029import inspect
30import pprint
31import sys
Michael Foordfddcfa22014-04-14 16:25:20 -040032import builtins
Xtreak9b218562019-04-22 08:00:23 +053033from types import ModuleType, MethodType
Petter Strandmark47d94242018-10-28 21:37:10 +010034from unittest.util import safe_repr
Antoine Pitrou5c64df72013-02-03 00:23:58 +010035from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070036
37
Michael Foordfddcfa22014-04-14 16:25:20 -040038_builtins = {name for name in dir(builtins) if not name.startswith('_')}
39
Michael Foord345266a2012-03-14 12:24:34 -070040FILTER_DIR = True
41
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100042# Workaround for issue #12370
43# Without this, the __class__ properties wouldn't be set correctly
44_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070045
46def _is_instance_mock(obj):
47 # can't use isinstance on Mock objects because they override __class__
48 # The base class for all mocks is NonCallableMock
49 return issubclass(type(obj), NonCallableMock)
50
51
52def _is_exception(obj):
53 return (
Chris Withers49e27f02019-05-01 08:48:44 +010054 isinstance(obj, BaseException) or
55 isinstance(obj, type) and issubclass(obj, BaseException)
Michael Foord345266a2012-03-14 12:24:34 -070056 )
57
58
Antoine Pitrou5c64df72013-02-03 00:23:58 +010059def _get_signature_object(func, as_instance, eat_self):
60 """
61 Given an arbitrary, possibly callable object, try to create a suitable
62 signature object.
63 Return a (reduced func, signature) tuple, or None.
64 """
65 if isinstance(func, type) and not as_instance:
66 # If it's a type and should be modelled as a type, use __init__.
Chris Withersadbf1782019-05-01 23:04:04 +010067 func = func.__init__
Antoine Pitrou5c64df72013-02-03 00:23:58 +010068 # Skip the `self` argument in __init__
69 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070070 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010071 # If we really want to model an instance of the passed type,
72 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070073 try:
74 func = func.__call__
75 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010076 return None
77 if eat_self:
78 sig_func = partial(func, None)
79 else:
80 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -070081 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010082 return func, inspect.signature(sig_func)
83 except ValueError:
84 # Certain callable types are not supported by inspect.signature()
85 return None
Michael Foord345266a2012-03-14 12:24:34 -070086
87
88def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010089 sig = _get_signature_object(func, instance, skipfirst)
90 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -070091 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +010092 func, sig = sig
93 def checksig(_mock_self, *args, **kwargs):
94 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -070095 _copy_func_details(func, checksig)
96 type(mock)._mock_check_sig = checksig
Xtreakf7fa62e2018-12-12 13:24:54 +053097 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -070098
99
100def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700101 # we explicitly don't copy func.__dict__ into this copy as it would
102 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300103 for attribute in (
104 '__name__', '__doc__', '__text_signature__',
105 '__module__', '__defaults__', '__kwdefaults__',
106 ):
107 try:
108 setattr(funcopy, attribute, getattr(func, attribute))
109 except AttributeError:
110 pass
Michael Foord345266a2012-03-14 12:24:34 -0700111
112
113def _callable(obj):
114 if isinstance(obj, type):
115 return True
Xtreak9b218562019-04-22 08:00:23 +0530116 if isinstance(obj, (staticmethod, classmethod, MethodType)):
117 return _callable(obj.__func__)
Michael Foord345266a2012-03-14 12:24:34 -0700118 if getattr(obj, '__call__', None) is not None:
119 return True
120 return False
121
122
123def _is_list(obj):
124 # checks for list or tuples
125 # XXXX badly named!
126 return type(obj) in (list, tuple)
127
128
129def _instance_callable(obj):
130 """Given an object, return True if the object is callable.
131 For classes, return True if instances would be callable."""
132 if not isinstance(obj, type):
133 # already an instance
134 return getattr(obj, '__call__', None) is not None
135
Michael Foorda74b3aa2012-03-14 14:40:22 -0700136 # *could* be broken by a class overriding __mro__ or __dict__ via
137 # a metaclass
138 for base in (obj,) + obj.__mro__:
139 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700140 return True
141 return False
142
143
144def _set_signature(mock, original, instance=False):
145 # creates a function with signature (*args, **kwargs) that delegates to a
146 # mock. It still does signature checking by calling a lambda with the same
147 # signature as the original.
Michael Foord345266a2012-03-14 12:24:34 -0700148
149 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100150 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700151 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700152 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100153 func, sig = result
154 def checksig(*args, **kwargs):
155 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700156 _copy_func_details(func, checksig)
157
158 name = original.__name__
159 if not name.isidentifier():
160 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100161 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700162 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100163 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700164 return mock(*args, **kwargs)""" % name
165 exec (src, context)
166 funcopy = context[name]
Xtreakf7fa62e2018-12-12 13:24:54 +0530167 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700168 return funcopy
169
170
Xtreakf7fa62e2018-12-12 13:24:54 +0530171def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700172 funcopy.mock = mock
173
Michael Foord345266a2012-03-14 12:24:34 -0700174 def assert_called_with(*args, **kwargs):
175 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700176 def assert_called(*args, **kwargs):
177 return mock.assert_called(*args, **kwargs)
178 def assert_not_called(*args, **kwargs):
179 return mock.assert_not_called(*args, **kwargs)
180 def assert_called_once(*args, **kwargs):
181 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700182 def assert_called_once_with(*args, **kwargs):
183 return mock.assert_called_once_with(*args, **kwargs)
184 def assert_has_calls(*args, **kwargs):
185 return mock.assert_has_calls(*args, **kwargs)
186 def assert_any_call(*args, **kwargs):
187 return mock.assert_any_call(*args, **kwargs)
188 def reset_mock():
189 funcopy.method_calls = _CallList()
190 funcopy.mock_calls = _CallList()
191 mock.reset_mock()
192 ret = funcopy.return_value
193 if _is_instance_mock(ret) and not ret is mock:
194 ret.reset_mock()
195
196 funcopy.called = False
197 funcopy.call_count = 0
198 funcopy.call_args = None
199 funcopy.call_args_list = _CallList()
200 funcopy.method_calls = _CallList()
201 funcopy.mock_calls = _CallList()
202
203 funcopy.return_value = mock.return_value
204 funcopy.side_effect = mock.side_effect
205 funcopy._mock_children = mock._mock_children
206
207 funcopy.assert_called_with = assert_called_with
208 funcopy.assert_called_once_with = assert_called_once_with
209 funcopy.assert_has_calls = assert_has_calls
210 funcopy.assert_any_call = assert_any_call
211 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700212 funcopy.assert_called = assert_called
213 funcopy.assert_not_called = assert_not_called
214 funcopy.assert_called_once = assert_called_once
Xtreakf7fa62e2018-12-12 13:24:54 +0530215 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700216
217 mock._mock_delegate = funcopy
218
219
220def _is_magic(name):
221 return '__%s__' % name[2:-2] == name
222
223
224class _SentinelObject(object):
225 "A unique, named, sentinel object."
226 def __init__(self, name):
227 self.name = name
228
229 def __repr__(self):
230 return 'sentinel.%s' % self.name
231
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200232 def __reduce__(self):
233 return 'sentinel.%s' % self.name
234
Michael Foord345266a2012-03-14 12:24:34 -0700235
236class _Sentinel(object):
237 """Access attributes to return a named object, usable as a sentinel."""
238 def __init__(self):
239 self._sentinels = {}
240
241 def __getattr__(self, name):
242 if name == '__bases__':
243 # Without this help(unittest.mock) raises an exception
244 raise AttributeError
245 return self._sentinels.setdefault(name, _SentinelObject(name))
246
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200247 def __reduce__(self):
248 return 'sentinel'
249
Michael Foord345266a2012-03-14 12:24:34 -0700250
251sentinel = _Sentinel()
252
253DEFAULT = sentinel.DEFAULT
254_missing = sentinel.MISSING
255_deleted = sentinel.DELETED
256
257
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200258_allowed_names = {
259 'return_value', '_mock_return_value', 'side_effect',
260 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
261 '_mock_name', '_mock_new_name'
262}
Michael Foord345266a2012-03-14 12:24:34 -0700263
264
265def _delegating_property(name):
266 _allowed_names.add(name)
267 _the_name = '_mock_' + name
268 def _get(self, name=name, _the_name=_the_name):
269 sig = self._mock_delegate
270 if sig is None:
271 return getattr(self, _the_name)
272 return getattr(sig, name)
273 def _set(self, value, name=name, _the_name=_the_name):
274 sig = self._mock_delegate
275 if sig is None:
276 self.__dict__[_the_name] = value
277 else:
278 setattr(sig, name, value)
279
280 return property(_get, _set)
281
282
283
284class _CallList(list):
285
286 def __contains__(self, value):
287 if not isinstance(value, list):
288 return list.__contains__(self, value)
289 len_value = len(value)
290 len_self = len(self)
291 if len_value > len_self:
292 return False
293
294 for i in range(0, len_self - len_value + 1):
295 sub_list = self[i:i+len_value]
296 if sub_list == value:
297 return True
298 return False
299
300 def __repr__(self):
301 return pprint.pformat(list(self))
302
303
304def _check_and_set_parent(parent, value, name, new_name):
Xtreak9c3f2842019-02-26 03:16:34 +0530305 # function passed to create_autospec will have mock
306 # attribute attached to which parent must be set
307 if isinstance(value, FunctionTypes):
308 try:
309 value = value.mock
310 except AttributeError:
311 pass
312
Michael Foord345266a2012-03-14 12:24:34 -0700313 if not _is_instance_mock(value):
314 return False
315 if ((value._mock_name or value._mock_new_name) or
316 (value._mock_parent is not None) or
317 (value._mock_new_parent is not None)):
318 return False
319
320 _parent = parent
321 while _parent is not None:
322 # setting a mock (value) as a child or return value of itself
323 # should not modify the mock
324 if _parent is value:
325 return False
326 _parent = _parent._mock_new_parent
327
328 if new_name:
329 value._mock_new_parent = parent
330 value._mock_new_name = new_name
331 if name:
332 value._mock_parent = parent
333 value._mock_name = name
334 return True
335
Michael Foord01bafdc2014-04-14 16:09:42 -0400336# Internal class to identify if we wrapped an iterator object or not.
337class _MockIter(object):
338 def __init__(self, obj):
339 self.obj = iter(obj)
Michael Foord01bafdc2014-04-14 16:09:42 -0400340 def __next__(self):
341 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700342
343class Base(object):
344 _mock_return_value = DEFAULT
345 _mock_side_effect = None
346 def __init__(self, *args, **kwargs):
347 pass
348
349
350
351class NonCallableMock(Base):
352 """A non-callable version of `Mock`"""
353
354 def __new__(cls, *args, **kw):
355 # every instance has its own class
356 # so we can create magic methods on the
357 # class without stomping on other mocks
358 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
359 instance = object.__new__(new)
360 return instance
361
362
363 def __init__(
364 self, spec=None, wraps=None, name=None, spec_set=None,
365 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530366 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700367 ):
368 if _new_parent is None:
369 _new_parent = parent
370
371 __dict__ = self.__dict__
372 __dict__['_mock_parent'] = parent
373 __dict__['_mock_name'] = name
374 __dict__['_mock_new_name'] = _new_name
375 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100376 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700377
378 if spec_set is not None:
379 spec = spec_set
380 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100381 if _eat_self is None:
382 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700383
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100384 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700385
386 __dict__['_mock_children'] = {}
387 __dict__['_mock_wraps'] = wraps
388 __dict__['_mock_delegate'] = None
389
390 __dict__['_mock_called'] = False
391 __dict__['_mock_call_args'] = None
392 __dict__['_mock_call_count'] = 0
393 __dict__['_mock_call_args_list'] = _CallList()
394 __dict__['_mock_mock_calls'] = _CallList()
395
396 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530397 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700398
399 if kwargs:
400 self.configure_mock(**kwargs)
401
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000402 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700403 spec, wraps, name, spec_set, parent,
404 _spec_state
405 )
406
407
408 def attach_mock(self, mock, attribute):
409 """
410 Attach a mock as an attribute of this one, replacing its name and
411 parent. Calls to the attached mock will be recorded in the
412 `method_calls` and `mock_calls` attributes of this one."""
413 mock._mock_parent = None
414 mock._mock_new_parent = None
415 mock._mock_name = ''
416 mock._mock_new_name = None
417
418 setattr(self, attribute, mock)
419
420
421 def mock_add_spec(self, spec, spec_set=False):
422 """Add a spec to a mock. `spec` can either be an object or a
423 list of strings. Only attributes on the `spec` can be fetched as
424 attributes from the mock.
425
426 If `spec_set` is True then only attributes on the spec can be set."""
427 self._mock_add_spec(spec, spec_set)
428
429
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100430 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
431 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700432 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100433 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700434
435 if spec is not None and not _is_list(spec):
436 if isinstance(spec, type):
437 _spec_class = spec
438 else:
Chris Withersadbf1782019-05-01 23:04:04 +0100439 _spec_class = type(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100440 res = _get_signature_object(spec,
441 _spec_as_instance, _eat_self)
442 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700443
444 spec = dir(spec)
445
446 __dict__ = self.__dict__
447 __dict__['_spec_class'] = _spec_class
448 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100449 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700450 __dict__['_mock_methods'] = spec
451
452
453 def __get_return_value(self):
454 ret = self._mock_return_value
455 if self._mock_delegate is not None:
456 ret = self._mock_delegate.return_value
457
458 if ret is DEFAULT:
459 ret = self._get_child_mock(
460 _new_parent=self, _new_name='()'
461 )
462 self.return_value = ret
463 return ret
464
465
466 def __set_return_value(self, value):
467 if self._mock_delegate is not None:
468 self._mock_delegate.return_value = value
469 else:
470 self._mock_return_value = value
471 _check_and_set_parent(self, value, None, '()')
472
473 __return_value_doc = "The value to be returned when the mock is called."
474 return_value = property(__get_return_value, __set_return_value,
475 __return_value_doc)
476
477
478 @property
479 def __class__(self):
480 if self._spec_class is None:
481 return type(self)
482 return self._spec_class
483
484 called = _delegating_property('called')
485 call_count = _delegating_property('call_count')
486 call_args = _delegating_property('call_args')
487 call_args_list = _delegating_property('call_args_list')
488 mock_calls = _delegating_property('mock_calls')
489
490
491 def __get_side_effect(self):
492 delegated = self._mock_delegate
493 if delegated is None:
494 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400495 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200496 if (sf is not None and not callable(sf)
497 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400498 sf = _MockIter(sf)
499 delegated.side_effect = sf
500 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700501
502 def __set_side_effect(self, value):
503 value = _try_iter(value)
504 delegated = self._mock_delegate
505 if delegated is None:
506 self._mock_side_effect = value
507 else:
508 delegated.side_effect = value
509
510 side_effect = property(__get_side_effect, __set_side_effect)
511
512
Kushal Das9cd39a12016-06-02 10:20:16 -0700513 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700514 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200515 if visited is None:
516 visited = []
517 if id(self) in visited:
518 return
519 visited.append(id(self))
520
Michael Foord345266a2012-03-14 12:24:34 -0700521 self.called = False
522 self.call_args = None
523 self.call_count = 0
524 self.mock_calls = _CallList()
525 self.call_args_list = _CallList()
526 self.method_calls = _CallList()
527
Kushal Das9cd39a12016-06-02 10:20:16 -0700528 if return_value:
529 self._mock_return_value = DEFAULT
530 if side_effect:
531 self._mock_side_effect = None
532
Michael Foord345266a2012-03-14 12:24:34 -0700533 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530534 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100535 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200536 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700537
538 ret = self._mock_return_value
539 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200540 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700541
542
543 def configure_mock(self, **kwargs):
544 """Set attributes on the mock through keyword arguments.
545
546 Attributes plus return values and side effects can be set on child
547 mocks using standard dot notation and unpacking a dictionary in the
548 method call:
549
550 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
551 >>> mock.configure_mock(**attrs)"""
552 for arg, val in sorted(kwargs.items(),
553 # we sort on the number of dots so that
554 # attributes are set before we set attributes on
555 # attributes
556 key=lambda entry: entry[0].count('.')):
557 args = arg.split('.')
558 final = args.pop()
559 obj = self
560 for entry in args:
561 obj = getattr(obj, entry)
562 setattr(obj, final, val)
563
564
565 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530566 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700567 raise AttributeError(name)
568 elif self._mock_methods is not None:
569 if name not in self._mock_methods or name in _all_magics:
570 raise AttributeError("Mock object has no attribute %r" % name)
571 elif _is_magic(name):
572 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530573 if not self._mock_unsafe:
574 if name.startswith(('assert', 'assret')):
Zackery Spytzb9b08cd2019-05-08 11:32:24 -0600575 raise AttributeError("Attributes cannot start with 'assert' "
576 "or 'assret'")
Michael Foord345266a2012-03-14 12:24:34 -0700577
578 result = self._mock_children.get(name)
579 if result is _deleted:
580 raise AttributeError(name)
581 elif result is None:
582 wraps = None
583 if self._mock_wraps is not None:
584 # XXXX should we get the attribute without triggering code
585 # execution?
586 wraps = getattr(self._mock_wraps, name)
587
588 result = self._get_child_mock(
589 parent=self, name=name, wraps=wraps, _new_name=name,
590 _new_parent=self
591 )
592 self._mock_children[name] = result
593
594 elif isinstance(result, _SpecState):
595 result = create_autospec(
596 result.spec, result.spec_set, result.instance,
597 result.parent, result.name
598 )
599 self._mock_children[name] = result
600
601 return result
602
603
Mario Corchero552be9d2017-10-17 12:35:11 +0100604 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700605 _name_list = [self._mock_new_name]
606 _parent = self._mock_new_parent
607 last = self
608
609 dot = '.'
610 if _name_list == ['()']:
611 dot = ''
Chris Withersadbf1782019-05-01 23:04:04 +0100612
Michael Foord345266a2012-03-14 12:24:34 -0700613 while _parent is not None:
614 last = _parent
615
616 _name_list.append(_parent._mock_new_name + dot)
617 dot = '.'
618 if _parent._mock_new_name == '()':
619 dot = ''
620
621 _parent = _parent._mock_new_parent
622
Michael Foord345266a2012-03-14 12:24:34 -0700623 _name_list = list(reversed(_name_list))
624 _first = last._mock_name or 'mock'
625 if len(_name_list) > 1:
626 if _name_list[1] not in ('()', '().'):
627 _first += '.'
628 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100629 return ''.join(_name_list)
630
631 def __repr__(self):
632 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700633
634 name_string = ''
635 if name not in ('mock', 'mock.'):
636 name_string = ' name=%r' % name
637
638 spec_string = ''
639 if self._spec_class is not None:
640 spec_string = ' spec=%r'
641 if self._spec_set:
642 spec_string = ' spec_set=%r'
643 spec_string = spec_string % self._spec_class.__name__
644 return "<%s%s%s id='%s'>" % (
645 type(self).__name__,
646 name_string,
647 spec_string,
648 id(self)
649 )
650
651
652 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700653 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100654 if not FILTER_DIR:
655 return object.__dir__(self)
656
Michael Foord345266a2012-03-14 12:24:34 -0700657 extras = self._mock_methods or []
658 from_type = dir(type(self))
659 from_dict = list(self.__dict__)
Mario Corchero0df635c2019-04-30 19:56:36 +0100660 from_child_mocks = [
661 m_name for m_name, m_value in self._mock_children.items()
662 if m_value is not _deleted]
Michael Foord345266a2012-03-14 12:24:34 -0700663
Michael Foord313f85f2012-03-25 18:16:07 +0100664 from_type = [e for e in from_type if not e.startswith('_')]
665 from_dict = [e for e in from_dict if not e.startswith('_') or
666 _is_magic(e)]
Mario Corchero0df635c2019-04-30 19:56:36 +0100667 return sorted(set(extras + from_type + from_dict + from_child_mocks))
Michael Foord345266a2012-03-14 12:24:34 -0700668
669
670 def __setattr__(self, name, value):
671 if name in _allowed_names:
672 # property setters go through here
673 return object.__setattr__(self, name, value)
674 elif (self._spec_set and self._mock_methods is not None and
675 name not in self._mock_methods and
676 name not in self.__dict__):
677 raise AttributeError("Mock object has no attribute '%s'" % name)
678 elif name in _unsupported_magics:
679 msg = 'Attempting to set unsupported magic method %r.' % name
680 raise AttributeError(msg)
681 elif name in _all_magics:
682 if self._mock_methods is not None and name not in self._mock_methods:
683 raise AttributeError("Mock object has no attribute '%s'" % name)
684
685 if not _is_instance_mock(value):
686 setattr(type(self), name, _get_method(name, value))
687 original = value
688 value = lambda *args, **kw: original(self, *args, **kw)
689 else:
690 # only set _new_name and not name so that mock_calls is tracked
691 # but not method calls
692 _check_and_set_parent(self, value, None, name)
693 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100694 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700695 elif name == '__class__':
696 self._spec_class = value
697 return
698 else:
699 if _check_and_set_parent(self, value, name, name):
700 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100701
702 if self._mock_sealed and not hasattr(self, name):
703 mock_name = f'{self._extract_mock_name()}.{name}'
704 raise AttributeError(f'Cannot set {mock_name}')
705
Michael Foord345266a2012-03-14 12:24:34 -0700706 return object.__setattr__(self, name, value)
707
708
709 def __delattr__(self, name):
710 if name in _all_magics and name in type(self).__dict__:
711 delattr(type(self), name)
712 if name not in self.__dict__:
713 # for magic methods that are still MagicProxy objects and
714 # not set on the instance itself
715 return
716
Michael Foord345266a2012-03-14 12:24:34 -0700717 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000718 if name in self.__dict__:
Xtreak830b43d2019-04-14 00:42:33 +0530719 _safe_super(NonCallableMock, self).__delattr__(name)
Pablo Galindo222d3032019-01-21 08:57:46 +0000720 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700721 raise AttributeError(name)
722 if obj is not _missing:
723 del self._mock_children[name]
724 self._mock_children[name] = _deleted
725
726
Michael Foord345266a2012-03-14 12:24:34 -0700727 def _format_mock_call_signature(self, args, kwargs):
728 name = self._mock_name or 'mock'
729 return _format_call_signature(name, args, kwargs)
730
731
732 def _format_mock_failure_message(self, args, kwargs):
Susan Su2bdd5852019-02-13 18:22:29 -0800733 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700734 expected_string = self._format_mock_call_signature(args, kwargs)
735 call_args = self.call_args
Michael Foord345266a2012-03-14 12:24:34 -0700736 actual_string = self._format_mock_call_signature(*call_args)
737 return message % (expected_string, actual_string)
738
739
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100740 def _call_matcher(self, _call):
741 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000742 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100743 comparison key suitable for matching with other calls.
744 This is a best effort method which relies on the spec's signature,
745 if available, or falls back on the arguments themselves.
746 """
747 sig = self._spec_signature
748 if sig is not None:
749 if len(_call) == 2:
750 name = ''
751 args, kwargs = _call
752 else:
753 name, args, kwargs = _call
754 try:
755 return name, sig.bind(*args, **kwargs)
756 except TypeError as e:
757 return e.with_traceback(None)
758 else:
759 return _call
760
Kushal Das68290f42014-04-17 01:54:07 +0530761 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530762 """assert that the mock was never called.
763 """
764 self = _mock_self
765 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100766 msg = ("Expected '%s' to not have been called. Called %s times.%s"
767 % (self._mock_name or 'mock',
768 self.call_count,
769 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530770 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100771
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100772 def assert_called(_mock_self):
773 """assert that the mock was called at least once
774 """
775 self = _mock_self
776 if self.call_count == 0:
777 msg = ("Expected '%s' to have been called." %
778 self._mock_name or 'mock')
779 raise AssertionError(msg)
780
781 def assert_called_once(_mock_self):
782 """assert that the mock was called only once.
783 """
784 self = _mock_self
785 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100786 msg = ("Expected '%s' to have been called once. Called %s times.%s"
787 % (self._mock_name or 'mock',
788 self.call_count,
789 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100790 raise AssertionError(msg)
791
Michael Foord345266a2012-03-14 12:24:34 -0700792 def assert_called_with(_mock_self, *args, **kwargs):
793 """assert that the mock was called with the specified arguments.
794
795 Raises an AssertionError if the args and keyword args passed in are
796 different to the last call to the mock."""
797 self = _mock_self
798 if self.call_args is None:
799 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800800 actual = 'not called.'
801 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
802 % (expected, actual))
803 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700804
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100805 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700806 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100807 return msg
808 expected = self._call_matcher((args, kwargs))
809 actual = self._call_matcher(self.call_args)
810 if expected != actual:
811 cause = expected if isinstance(expected, Exception) else None
812 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700813
814
815 def assert_called_once_with(_mock_self, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100816 """assert that the mock was called exactly once and that that call was
817 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700818 self = _mock_self
819 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100820 msg = ("Expected '%s' to be called once. Called %s times.%s"
821 % (self._mock_name or 'mock',
822 self.call_count,
823 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700824 raise AssertionError(msg)
825 return self.assert_called_with(*args, **kwargs)
826
827
828 def assert_has_calls(self, calls, any_order=False):
829 """assert the mock has been called with the specified calls.
830 The `mock_calls` list is checked for the calls.
831
832 If `any_order` is False (the default) then the calls must be
833 sequential. There can be extra calls before or after the
834 specified calls.
835
836 If `any_order` is True then the calls can be in any order, but
837 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100838 expected = [self._call_matcher(c) for c in calls]
839 cause = expected if isinstance(expected, Exception) else None
840 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700841 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100842 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700843 raise AssertionError(
Petter Strandmark47d94242018-10-28 21:37:10 +0100844 'Calls not found.\nExpected: %r%s'
845 % (_CallList(calls), self._calls_repr(prefix="Actual"))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100846 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700847 return
848
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100849 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700850
851 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100852 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700853 try:
854 all_calls.remove(kall)
855 except ValueError:
856 not_found.append(kall)
857 if not_found:
858 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400859 '%r does not contain all of %r in its call list, '
860 'found %r instead' % (self._mock_name or 'mock',
861 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100862 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700863
864
865 def assert_any_call(self, *args, **kwargs):
866 """assert the mock has been called with the specified arguments.
867
868 The assert passes if the mock has *ever* been called, unlike
869 `assert_called_with` and `assert_called_once_with` that only pass if
870 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100871 expected = self._call_matcher((args, kwargs))
872 actual = [self._call_matcher(c) for c in self.call_args_list]
873 if expected not in actual:
874 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700875 expected_string = self._format_mock_call_signature(args, kwargs)
876 raise AssertionError(
877 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100878 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700879
880
881 def _get_child_mock(self, **kw):
882 """Create the child mocks for attributes and return value.
883 By default child mocks will be the same type as the parent.
884 Subclasses of Mock may want to override this to customize the way
885 child mocks are made.
886
887 For non-callable mocks the callable variant will be used (rather than
888 any custom subclass)."""
889 _type = type(self)
890 if not issubclass(_type, CallableMixin):
891 if issubclass(_type, NonCallableMagicMock):
892 klass = MagicMock
893 elif issubclass(_type, NonCallableMock) :
894 klass = Mock
895 else:
896 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +0100897
898 if self._mock_sealed:
899 attribute = "." + kw["name"] if "name" in kw else "()"
900 mock_name = self._extract_mock_name() + attribute
901 raise AttributeError(mock_name)
902
Michael Foord345266a2012-03-14 12:24:34 -0700903 return klass(**kw)
904
905
Petter Strandmark47d94242018-10-28 21:37:10 +0100906 def _calls_repr(self, prefix="Calls"):
907 """Renders self.mock_calls as a string.
908
909 Example: "\nCalls: [call(1), call(2)]."
910
911 If self.mock_calls is empty, an empty string is returned. The
912 output will be truncated if very long.
913 """
914 if not self.mock_calls:
915 return ""
916 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
917
918
Michael Foord345266a2012-03-14 12:24:34 -0700919
920def _try_iter(obj):
921 if obj is None:
922 return obj
923 if _is_exception(obj):
924 return obj
925 if _callable(obj):
926 return obj
927 try:
928 return iter(obj)
929 except TypeError:
930 # XXXX backwards compatibility
931 # but this will blow up on first call - so maybe we should fail early?
932 return obj
933
934
935
936class CallableMixin(Base):
937
938 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
939 wraps=None, name=None, spec_set=None, parent=None,
940 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
941 self.__dict__['_mock_return_value'] = return_value
942
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000943 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700944 spec, wraps, name, spec_set, parent,
945 _spec_state, _new_name, _new_parent, **kwargs
946 )
947
948 self.side_effect = side_effect
949
950
951 def _mock_check_sig(self, *args, **kwargs):
952 # stub method that can be replaced with one with a specific signature
953 pass
954
955
956 def __call__(_mock_self, *args, **kwargs):
957 # can't use self in-case a function / method we are mocking uses self
958 # in the signature
959 _mock_self._mock_check_sig(*args, **kwargs)
960 return _mock_self._mock_call(*args, **kwargs)
961
962
963 def _mock_call(_mock_self, *args, **kwargs):
964 self = _mock_self
965 self.called = True
966 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100967
Chris Withers8ca0fa92018-12-03 21:31:37 +0000968 # handle call_args
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100969 _call = _Call((args, kwargs), two=True)
970 self.call_args = _call
971 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700972
Chris Withers8ca0fa92018-12-03 21:31:37 +0000973 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700974 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +0000975 method_call_name = self._mock_name
976
977 # initial stuff for mock_calls:
978 mock_call_name = self._mock_new_name
979 is_a_call = mock_call_name == '()'
980 self.mock_calls.append(_Call(('', args, kwargs)))
981
982 # follow up the chain of mocks:
983 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -0700984 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700985
Chris Withers8ca0fa92018-12-03 21:31:37 +0000986 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700987 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +0000988 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -0700989 do_method_calls = _new_parent._mock_parent is not None
990 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +0000991 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -0700992
Chris Withers8ca0fa92018-12-03 21:31:37 +0000993 # handle mock_calls:
994 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -0700995 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +0000996
997 if _new_parent._mock_new_name:
998 if is_a_call:
999 dot = ''
1000 else:
1001 dot = '.'
1002 is_a_call = _new_parent._mock_new_name == '()'
1003 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1004
1005 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001006 _new_parent = _new_parent._mock_new_parent
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
Mario Corcherof05df0a2018-12-08 11:25:02 +00001012 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001013 result = next(effect)
1014 if _is_exception(result):
1015 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001016 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
Mario Corcherof05df0a2018-12-08 11:25:02 +00001022 if self._mock_return_value is not DEFAULT:
1023 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001024
Mario Corcherof05df0a2018-12-08 11:25:02 +00001025 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001026 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001027
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):
Xtreak02b84cb2019-03-29 02:38:43 +05301367 return
Michael Foord345266a2012-03-14 12:24:34 -07001368
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):
Michael Foord345266a2012-03-14 12:24:34 -07001597 self.in_dict = in_dict
1598 # support any argument supported by dict(...) constructor
1599 self.values = dict(values)
1600 self.values.update(kwargs)
1601 self.clear = clear
1602 self._original = None
1603
1604
1605 def __call__(self, f):
1606 if isinstance(f, type):
1607 return self.decorate_class(f)
1608 @wraps(f)
1609 def _inner(*args, **kw):
1610 self._patch_dict()
1611 try:
1612 return f(*args, **kw)
1613 finally:
1614 self._unpatch_dict()
1615
1616 return _inner
1617
1618
1619 def decorate_class(self, klass):
1620 for attr in dir(klass):
1621 attr_value = getattr(klass, attr)
1622 if (attr.startswith(patch.TEST_PREFIX) and
1623 hasattr(attr_value, "__call__")):
1624 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1625 decorated = decorator(attr_value)
1626 setattr(klass, attr, decorated)
1627 return klass
1628
1629
1630 def __enter__(self):
1631 """Patch the dict."""
1632 self._patch_dict()
1633
1634
1635 def _patch_dict(self):
1636 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301637 if isinstance(self.in_dict, str):
1638 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001639 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 "
John Reese6c4fab02018-05-22 13:01:10 -07001716 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001717 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001718 "fspath "
Michael Foord345266a2012-03-14 12:24:34 -07001719)
1720
Michael Foordd2623d72014-04-14 11:23:48 -04001721numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001722 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001723)
Michael Foord345266a2012-03-14 12:24:34 -07001724inplace = ' '.join('i%s' % n for n in numerics.split())
1725right = ' '.join('r%s' % n for n in numerics.split())
1726
1727# not including __prepare__, __instancecheck__, __subclasscheck__
1728# (as they are metaclass methods)
1729# __del__ is not supported at all as it causes problems if it exists
1730
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001731_non_defaults = {
1732 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1733 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1734 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1735 '__repr__', '__dir__', '__subclasses__', '__format__',
Serhiy Storchaka5943ea72016-06-19 18:30:43 +03001736 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001737}
Michael Foord345266a2012-03-14 12:24:34 -07001738
1739
1740def _get_method(name, func):
1741 "Turns a callable object (like a mock) into a real function"
1742 def method(self, *args, **kw):
1743 return func(self, *args, **kw)
1744 method.__name__ = name
1745 return method
1746
1747
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001748_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001749 '__%s__' % method for method in
1750 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001751}
Michael Foord345266a2012-03-14 12:24:34 -07001752
1753_all_magics = _magics | _non_defaults
1754
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001755_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001756 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001757 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001758 '__instancecheck__', '__subclasscheck__',
1759 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001760}
Michael Foord345266a2012-03-14 12:24:34 -07001761
1762_calculate_return_value = {
1763 '__hash__': lambda self: object.__hash__(self),
1764 '__str__': lambda self: object.__str__(self),
1765 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001766 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001767}
1768
1769_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001770 '__lt__': NotImplemented,
1771 '__gt__': NotImplemented,
1772 '__le__': NotImplemented,
1773 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001774 '__int__': 1,
1775 '__contains__': False,
1776 '__len__': 0,
1777 '__exit__': False,
1778 '__complex__': 1j,
1779 '__float__': 1.0,
1780 '__bool__': True,
1781 '__index__': 1,
1782}
1783
1784
1785def _get_eq(self):
1786 def __eq__(other):
1787 ret_val = self.__eq__._mock_return_value
1788 if ret_val is not DEFAULT:
1789 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001790 if self is other:
1791 return True
1792 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001793 return __eq__
1794
1795def _get_ne(self):
1796 def __ne__(other):
1797 if self.__ne__._mock_return_value is not DEFAULT:
1798 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001799 if self is other:
1800 return False
1801 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001802 return __ne__
1803
1804def _get_iter(self):
1805 def __iter__():
1806 ret_val = self.__iter__._mock_return_value
1807 if ret_val is DEFAULT:
1808 return iter([])
1809 # if ret_val was already an iterator, then calling iter on it should
1810 # return the iterator unchanged
1811 return iter(ret_val)
1812 return __iter__
1813
1814_side_effect_methods = {
1815 '__eq__': _get_eq,
1816 '__ne__': _get_ne,
1817 '__iter__': _get_iter,
1818}
1819
1820
1821
1822def _set_return_value(mock, method, name):
1823 fixed = _return_values.get(name, DEFAULT)
1824 if fixed is not DEFAULT:
1825 method.return_value = fixed
1826 return
1827
1828 return_calulator = _calculate_return_value.get(name)
1829 if return_calulator is not None:
Chris Withersadbf1782019-05-01 23:04:04 +01001830 return_value = return_calulator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07001831 method.return_value = return_value
1832 return
1833
1834 side_effector = _side_effect_methods.get(name)
1835 if side_effector is not None:
1836 method.side_effect = side_effector(mock)
1837
1838
1839
1840class MagicMixin(object):
1841 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001842 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001843 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001844 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001845
1846
1847 def _mock_set_magics(self):
1848 these_magics = _magics
1849
Łukasz Langaa468db92015-04-13 23:12:42 -07001850 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001851 these_magics = _magics.intersection(self._mock_methods)
1852
1853 remove_magics = set()
1854 remove_magics = _magics - these_magics
1855
1856 for entry in remove_magics:
1857 if entry in type(self).__dict__:
1858 # remove unneeded magic methods
1859 delattr(self, entry)
1860
1861 # don't overwrite existing attributes if called a second time
1862 these_magics = these_magics - set(type(self).__dict__)
1863
1864 _type = type(self)
1865 for entry in these_magics:
1866 setattr(_type, entry, MagicProxy(entry, self))
1867
1868
1869
1870class NonCallableMagicMock(MagicMixin, NonCallableMock):
1871 """A version of `MagicMock` that isn't callable."""
1872 def mock_add_spec(self, spec, spec_set=False):
1873 """Add a spec to a mock. `spec` can either be an object or a
1874 list of strings. Only attributes on the `spec` can be fetched as
1875 attributes from the mock.
1876
1877 If `spec_set` is True then only attributes on the spec can be set."""
1878 self._mock_add_spec(spec, spec_set)
1879 self._mock_set_magics()
1880
1881
1882
1883class MagicMock(MagicMixin, Mock):
1884 """
1885 MagicMock is a subclass of Mock with default implementations
1886 of most of the magic methods. You can use MagicMock without having to
1887 configure the magic methods yourself.
1888
1889 If you use the `spec` or `spec_set` arguments then *only* magic
1890 methods that exist in the spec will be created.
1891
1892 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1893 """
1894 def mock_add_spec(self, spec, spec_set=False):
1895 """Add a spec to a mock. `spec` can either be an object or a
1896 list of strings. Only attributes on the `spec` can be fetched as
1897 attributes from the mock.
1898
1899 If `spec_set` is True then only attributes on the spec can be set."""
1900 self._mock_add_spec(spec, spec_set)
1901 self._mock_set_magics()
1902
1903
1904
1905class MagicProxy(object):
1906 def __init__(self, name, parent):
1907 self.name = name
1908 self.parent = parent
1909
Michael Foord345266a2012-03-14 12:24:34 -07001910 def create_mock(self):
1911 entry = self.name
1912 parent = self.parent
1913 m = parent._get_child_mock(name=entry, _new_name=entry,
1914 _new_parent=parent)
1915 setattr(parent, entry, m)
1916 _set_return_value(parent, m, entry)
1917 return m
1918
1919 def __get__(self, obj, _type=None):
1920 return self.create_mock()
1921
1922
1923
1924class _ANY(object):
1925 "A helper object that compares equal to everything."
1926
1927 def __eq__(self, other):
1928 return True
1929
1930 def __ne__(self, other):
1931 return False
1932
1933 def __repr__(self):
1934 return '<ANY>'
1935
1936ANY = _ANY()
1937
1938
1939
1940def _format_call_signature(name, args, kwargs):
1941 message = '%s(%%s)' % name
1942 formatted_args = ''
1943 args_string = ', '.join([repr(arg) for arg in args])
1944 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301945 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001946 ])
1947 if args_string:
1948 formatted_args = args_string
1949 if kwargs_string:
1950 if formatted_args:
1951 formatted_args += ', '
1952 formatted_args += kwargs_string
1953
1954 return message % formatted_args
1955
1956
1957
1958class _Call(tuple):
1959 """
1960 A tuple for holding the results of a call to a mock, either in the form
1961 `(args, kwargs)` or `(name, args, kwargs)`.
1962
1963 If args or kwargs are empty then a call tuple will compare equal to
1964 a tuple without those values. This makes comparisons less verbose::
1965
1966 _Call(('name', (), {})) == ('name',)
1967 _Call(('name', (1,), {})) == ('name', (1,))
1968 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1969
1970 The `_Call` object provides a useful shortcut for comparing with call::
1971
1972 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1973 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1974
1975 If the _Call has no name then it will match any name.
1976 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01001977 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07001978 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07001979 args = ()
1980 kwargs = {}
1981 _len = len(value)
1982 if _len == 3:
1983 name, args, kwargs = value
1984 elif _len == 2:
1985 first, second = value
1986 if isinstance(first, str):
1987 name = first
1988 if isinstance(second, tuple):
1989 args = second
1990 else:
1991 kwargs = second
1992 else:
1993 args, kwargs = first, second
1994 elif _len == 1:
1995 value, = value
1996 if isinstance(value, str):
1997 name = value
1998 elif isinstance(value, tuple):
1999 args = value
2000 else:
2001 kwargs = value
2002
2003 if two:
2004 return tuple.__new__(cls, (args, kwargs))
2005
2006 return tuple.__new__(cls, (name, args, kwargs))
2007
2008
2009 def __init__(self, value=(), name=None, parent=None, two=False,
2010 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002011 self._mock_name = name
2012 self._mock_parent = parent
2013 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002014
2015
2016 def __eq__(self, other):
2017 if other is ANY:
2018 return True
2019 try:
2020 len_other = len(other)
2021 except TypeError:
2022 return False
2023
2024 self_name = ''
2025 if len(self) == 2:
2026 self_args, self_kwargs = self
2027 else:
2028 self_name, self_args, self_kwargs = self
2029
Andrew Dunaie63e6172018-12-04 11:08:45 +02002030 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2031 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002032 return False
2033
Michael Foord345266a2012-03-14 12:24:34 -07002034 other_name = ''
2035 if len_other == 0:
2036 other_args, other_kwargs = (), {}
2037 elif len_other == 3:
2038 other_name, other_args, other_kwargs = other
2039 elif len_other == 1:
2040 value, = other
2041 if isinstance(value, tuple):
2042 other_args = value
2043 other_kwargs = {}
2044 elif isinstance(value, str):
2045 other_name = value
2046 other_args, other_kwargs = (), {}
2047 else:
2048 other_args = ()
2049 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002050 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002051 # could be (name, args) or (name, kwargs) or (args, kwargs)
2052 first, second = other
2053 if isinstance(first, str):
2054 other_name = first
2055 if isinstance(second, tuple):
2056 other_args, other_kwargs = second, {}
2057 else:
2058 other_args, other_kwargs = (), second
2059 else:
2060 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002061 else:
2062 return False
Michael Foord345266a2012-03-14 12:24:34 -07002063
2064 if self_name and other_name != self_name:
2065 return False
2066
2067 # this order is important for ANY to work!
2068 return (other_args, other_kwargs) == (self_args, self_kwargs)
2069
2070
Berker Peksagce913872016-03-28 00:30:02 +03002071 __ne__ = object.__ne__
2072
2073
Michael Foord345266a2012-03-14 12:24:34 -07002074 def __call__(self, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002075 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002076 return _Call(('', args, kwargs), name='()')
2077
Andrew Dunaie63e6172018-12-04 11:08:45 +02002078 name = self._mock_name + '()'
2079 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002080
2081
2082 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002083 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002084 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002085 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002086 return _Call(name=name, parent=self, from_kall=False)
2087
2088
Kushal Dasa37b9582014-09-16 18:33:37 +05302089 def count(self, *args, **kwargs):
2090 return self.__getattr__('count')(*args, **kwargs)
2091
2092 def index(self, *args, **kwargs):
2093 return self.__getattr__('index')(*args, **kwargs)
2094
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302095 def _get_call_arguments(self):
2096 if len(self) == 2:
2097 args, kwargs = self
2098 else:
2099 name, args, kwargs = self
2100
2101 return args, kwargs
2102
2103 @property
2104 def args(self):
2105 return self._get_call_arguments()[0]
2106
2107 @property
2108 def kwargs(self):
2109 return self._get_call_arguments()[1]
2110
Michael Foord345266a2012-03-14 12:24:34 -07002111 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002112 if not self._mock_from_kall:
2113 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002114 if name.startswith('()'):
2115 name = 'call%s' % name
2116 return name
2117
2118 if len(self) == 2:
2119 name = 'call'
2120 args, kwargs = self
2121 else:
2122 name, args, kwargs = self
2123 if not name:
2124 name = 'call'
2125 elif not name.startswith('()'):
2126 name = 'call.%s' % name
2127 else:
2128 name = 'call%s' % name
2129 return _format_call_signature(name, args, kwargs)
2130
2131
2132 def call_list(self):
2133 """For a call object that represents multiple calls, `call_list`
2134 returns a list of all the intermediate calls as well as the
2135 final call."""
2136 vals = []
2137 thing = self
2138 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002139 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002140 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002141 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002142 return _CallList(reversed(vals))
2143
2144
2145call = _Call(from_kall=False)
2146
2147
2148
2149def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2150 _name=None, **kwargs):
2151 """Create a mock object using another object as a spec. Attributes on the
2152 mock will use the corresponding attribute on the `spec` object as their
2153 spec.
2154
2155 Functions or methods being mocked will have their arguments checked
2156 to check that they are called with the correct signature.
2157
2158 If `spec_set` is True then attempting to set attributes that don't exist
2159 on the spec object will raise an `AttributeError`.
2160
2161 If a class is used as a spec then the return value of the mock (the
2162 instance of the class) will have the same spec. You can use a class as the
2163 spec for an instance object by passing `instance=True`. The returned mock
2164 will only be callable if instances of the mock are callable.
2165
2166 `create_autospec` also takes arbitrary keyword arguments that are passed to
2167 the constructor of the created mock."""
2168 if _is_list(spec):
2169 # can't pass a list instance to the mock constructor as it will be
2170 # interpreted as a list of strings
2171 spec = type(spec)
2172
2173 is_type = isinstance(spec, type)
2174
2175 _kwargs = {'spec': spec}
2176 if spec_set:
2177 _kwargs = {'spec_set': spec}
2178 elif spec is None:
2179 # None we mock with a normal mock without a spec
2180 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002181 if _kwargs and instance:
2182 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002183
2184 _kwargs.update(kwargs)
2185
2186 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002187 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002188 # descriptors don't have a spec
2189 # because we don't know what type they return
2190 _kwargs = {}
2191 elif not _callable(spec):
2192 Klass = NonCallableMagicMock
2193 elif is_type and instance and not _instance_callable(spec):
2194 Klass = NonCallableMagicMock
2195
Kushal Das484f8a82014-04-16 01:05:50 +05302196 _name = _kwargs.pop('name', _name)
2197
Michael Foord345266a2012-03-14 12:24:34 -07002198 _new_name = _name
2199 if _parent is None:
2200 # for a top level object no _new_name should be set
2201 _new_name = ''
2202
2203 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2204 name=_name, **_kwargs)
2205
2206 if isinstance(spec, FunctionTypes):
2207 # should only happen at the top level because we don't
2208 # recurse for functions
2209 mock = _set_signature(mock, spec)
2210 else:
2211 _check_signature(spec, mock, is_type, instance)
2212
2213 if _parent is not None and not instance:
2214 _parent._mock_children[_name] = mock
2215
2216 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002217 mock.return_value = create_autospec(spec, spec_set, instance=True,
2218 _name='()', _parent=mock)
2219
2220 for entry in dir(spec):
2221 if _is_magic(entry):
2222 # MagicMock already does the useful magic methods for us
2223 continue
2224
Michael Foord345266a2012-03-14 12:24:34 -07002225 # XXXX do we need a better way of getting attributes without
2226 # triggering code execution (?) Probably not - we need the actual
2227 # object to mock it so we would rather trigger a property than mock
2228 # the property descriptor. Likewise we want to mock out dynamically
2229 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002230 # XXXX what about attributes that raise exceptions other than
2231 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002232 # we could be resilient against it, or catch and propagate the
2233 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002234 try:
2235 original = getattr(spec, entry)
2236 except AttributeError:
2237 continue
Michael Foord345266a2012-03-14 12:24:34 -07002238
2239 kwargs = {'spec': original}
2240 if spec_set:
2241 kwargs = {'spec_set': original}
2242
2243 if not isinstance(original, FunctionTypes):
2244 new = _SpecState(original, spec_set, mock, entry, instance)
2245 mock._mock_children[entry] = new
2246 else:
2247 parent = mock
2248 if isinstance(spec, FunctionTypes):
2249 parent = mock.mock
2250
Michael Foord345266a2012-03-14 12:24:34 -07002251 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002252 kwargs['_eat_self'] = skipfirst
2253 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2254 _new_parent=parent,
2255 **kwargs)
2256 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002257 _check_signature(original, new, skipfirst=skipfirst)
2258
2259 # so functions created with _set_signature become instance attributes,
2260 # *plus* their underlying mock exists in _mock_children of the parent
2261 # mock. Adding to _mock_children may be unnecessary where we are also
2262 # setting as an instance attribute?
2263 if isinstance(new, FunctionTypes):
2264 setattr(mock, entry, new)
2265
2266 return mock
2267
2268
2269def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002270 """
2271 Return whether we should skip the first argument on spec's `entry`
2272 attribute.
2273 """
Michael Foord345266a2012-03-14 12:24:34 -07002274 if not isinstance(spec, type):
2275 if entry in getattr(spec, '__dict__', {}):
2276 # instance attribute - shouldn't skip
2277 return False
Michael Foord345266a2012-03-14 12:24:34 -07002278 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002279
2280 for klass in spec.__mro__:
2281 result = klass.__dict__.get(entry, DEFAULT)
2282 if result is DEFAULT:
2283 continue
2284 if isinstance(result, (staticmethod, classmethod)):
2285 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002286 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2287 # Normal method => skip if looked up on type
2288 # (if looked up on instance, self is already skipped)
2289 return is_type
2290 else:
2291 return False
Michael Foord345266a2012-03-14 12:24:34 -07002292
Chris Withersadbf1782019-05-01 23:04:04 +01002293 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002294 return is_type
2295
2296
Michael Foord345266a2012-03-14 12:24:34 -07002297class _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 -07002323
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002324def _to_stream(read_data):
2325 if isinstance(read_data, bytes):
2326 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002327 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002328 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002329
Robert Collins5329aaa2015-07-17 20:08:45 +12002330
Michael Foord0dccf652012-03-25 19:11:50 +01002331def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002332 """
2333 A helper function to create a mock to replace the use of `open`. It works
2334 for `open` called directly or used as a context manager.
2335
2336 The `mock` argument is the mock object to configure. If `None` (the
2337 default) then a `MagicMock` will be created for you, with the API limited
2338 to methods or attributes available on standard file handles.
2339
Xtreak71f82a22018-12-20 21:30:21 +05302340 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002341 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002342 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002343 _read_data = _to_stream(read_data)
2344 _state = [_read_data, None]
2345
Robert Collinsca647ef2015-07-24 03:48:20 +12002346 def _readlines_side_effect(*args, **kwargs):
2347 if handle.readlines.return_value is not None:
2348 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002349 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002350
2351 def _read_side_effect(*args, **kwargs):
2352 if handle.read.return_value is not None:
2353 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002354 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002355
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002356 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002357 yield from _iter_side_effect()
2358 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002359 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002360
2361 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002362 if handle.readline.return_value is not None:
2363 while True:
2364 yield handle.readline.return_value
2365 for line in _state[0]:
2366 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002367
Michael Foorda74561a2012-03-25 19:03:13 +01002368 global file_spec
2369 if file_spec is None:
2370 import _io
2371 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2372
Michael Foord345266a2012-03-14 12:24:34 -07002373 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002374 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002375
Robert Collinsca647ef2015-07-24 03:48:20 +12002376 handle = MagicMock(spec=file_spec)
2377 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002378
Robert Collinsca647ef2015-07-24 03:48:20 +12002379 handle.write.return_value = None
2380 handle.read.return_value = None
2381 handle.readline.return_value = None
2382 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002383
Robert Collinsca647ef2015-07-24 03:48:20 +12002384 handle.read.side_effect = _read_side_effect
2385 _state[1] = _readline_side_effect()
2386 handle.readline.side_effect = _state[1]
2387 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002388 handle.__iter__.side_effect = _iter_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002389
Robert Collinsca647ef2015-07-24 03:48:20 +12002390 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002391 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002392 if handle.readline.side_effect == _state[1]:
2393 # Only reset the side effect if the user hasn't overridden it.
2394 _state[1] = _readline_side_effect()
2395 handle.readline.side_effect = _state[1]
2396 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002397
Robert Collinsca647ef2015-07-24 03:48:20 +12002398 mock.side_effect = reset_data
2399 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002400 return mock
2401
2402
2403class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002404 """
2405 A mock intended to be used as a property, or other descriptor, on a class.
2406 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2407 a return value when it is fetched.
2408
2409 Fetching a `PropertyMock` instance from an object calls the mock, with
2410 no args. Setting it calls the mock with the value being set.
2411 """
Michael Foordc2870622012-04-13 16:57:22 +01002412 def _get_child_mock(self, **kwargs):
2413 return MagicMock(**kwargs)
2414
Michael Foord345266a2012-03-14 12:24:34 -07002415 def __get__(self, obj, obj_type):
2416 return self()
2417 def __set__(self, obj, val):
2418 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002419
2420
2421def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002422 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002423
2424 Given an input Mock, seals it to ensure no further mocks will be generated
2425 when accessing an attribute that was not already defined.
2426
Mario Corchero96200eb2018-10-19 22:57:37 +01002427 The operation recursively seals the mock passed in, meaning that
2428 the mock itself, any mocks generated by accessing one of its attributes,
2429 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002430 """
2431 mock._mock_sealed = True
2432 for attr in dir(mock):
2433 try:
2434 m = getattr(mock, attr)
2435 except AttributeError:
2436 continue
2437 if not isinstance(m, NonCallableMock):
2438 continue
2439 if m._mock_new_parent is mock:
2440 seal(m)