blob: ef5c55d6a1654d2b450bf2b3e99c05efc24723d5 [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001# mock.py
2# Test tools for mocking and patching.
Michael Foordc17adf42012-03-14 13:30:29 -07003# Maintained by Michael Foord
4# Backport for other versions of Python available from
Ned Deily9d6d06e2018-06-11 00:45:50 -04005# https://pypi.org/project/mock
Michael Foord345266a2012-03-14 12:24:34 -07006
7__all__ = (
8 'Mock',
9 'MagicMock',
10 'patch',
11 'sentinel',
12 'DEFAULT',
13 'ANY',
14 'call',
15 'create_autospec',
16 'FILTER_DIR',
17 'NonCallableMock',
18 'NonCallableMagicMock',
19 'mock_open',
20 'PropertyMock',
Mario Corchero552be9d2017-10-17 12:35:11 +010021 'seal',
Michael Foord345266a2012-03-14 12:24:34 -070022)
23
24
25__version__ = '1.0'
26
27
28import inspect
29import pprint
30import sys
Michael Foordfddcfa22014-04-14 16:25:20 -040031import builtins
32from types import ModuleType
Petter Strandmark47d94242018-10-28 21:37:10 +010033from unittest.util import safe_repr
Antoine Pitrou5c64df72013-02-03 00:23:58 +010034from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070035
36
Michael Foordfddcfa22014-04-14 16:25:20 -040037_builtins = {name for name in dir(builtins) if not name.startswith('_')}
38
Michael Foord345266a2012-03-14 12:24:34 -070039BaseExceptions = (BaseException,)
40if 'java' in sys.platform:
41 # jython
42 import java
43 BaseExceptions = (BaseException, java.lang.Throwable)
44
45
46FILTER_DIR = True
47
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100048# Workaround for issue #12370
49# Without this, the __class__ properties wouldn't be set correctly
50_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070051
52def _is_instance_mock(obj):
53 # can't use isinstance on Mock objects because they override __class__
54 # The base class for all mocks is NonCallableMock
55 return issubclass(type(obj), NonCallableMock)
56
57
58def _is_exception(obj):
59 return (
60 isinstance(obj, BaseExceptions) or
61 isinstance(obj, type) and issubclass(obj, BaseExceptions)
62 )
63
64
Antoine Pitrou5c64df72013-02-03 00:23:58 +010065def _get_signature_object(func, as_instance, eat_self):
66 """
67 Given an arbitrary, possibly callable object, try to create a suitable
68 signature object.
69 Return a (reduced func, signature) tuple, or None.
70 """
71 if isinstance(func, type) and not as_instance:
72 # If it's a type and should be modelled as a type, use __init__.
Michael Foord345266a2012-03-14 12:24:34 -070073 try:
74 func = func.__init__
75 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010076 return None
77 # Skip the `self` argument in __init__
78 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070079 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010080 # If we really want to model an instance of the passed type,
81 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070082 try:
83 func = func.__call__
84 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010085 return None
86 if eat_self:
87 sig_func = partial(func, None)
88 else:
89 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -070090 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010091 return func, inspect.signature(sig_func)
92 except ValueError:
93 # Certain callable types are not supported by inspect.signature()
94 return None
Michael Foord345266a2012-03-14 12:24:34 -070095
96
97def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010098 sig = _get_signature_object(func, instance, skipfirst)
99 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700100 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100101 func, sig = sig
102 def checksig(_mock_self, *args, **kwargs):
103 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700104 _copy_func_details(func, checksig)
105 type(mock)._mock_check_sig = checksig
Xtreakf7fa62e2018-12-12 13:24:54 +0530106 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700107
108
109def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700110 # we explicitly don't copy func.__dict__ into this copy as it would
111 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300112 for attribute in (
113 '__name__', '__doc__', '__text_signature__',
114 '__module__', '__defaults__', '__kwdefaults__',
115 ):
116 try:
117 setattr(funcopy, attribute, getattr(func, attribute))
118 except AttributeError:
119 pass
Michael Foord345266a2012-03-14 12:24:34 -0700120
121
122def _callable(obj):
123 if isinstance(obj, type):
124 return True
125 if getattr(obj, '__call__', None) is not None:
126 return True
127 return False
128
129
130def _is_list(obj):
131 # checks for list or tuples
132 # XXXX badly named!
133 return type(obj) in (list, tuple)
134
135
136def _instance_callable(obj):
137 """Given an object, return True if the object is callable.
138 For classes, return True if instances would be callable."""
139 if not isinstance(obj, type):
140 # already an instance
141 return getattr(obj, '__call__', None) is not None
142
Michael Foorda74b3aa2012-03-14 14:40:22 -0700143 # *could* be broken by a class overriding __mro__ or __dict__ via
144 # a metaclass
145 for base in (obj,) + obj.__mro__:
146 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700147 return True
148 return False
149
150
151def _set_signature(mock, original, instance=False):
152 # creates a function with signature (*args, **kwargs) that delegates to a
153 # mock. It still does signature checking by calling a lambda with the same
154 # signature as the original.
155 if not _callable(original):
156 return
157
158 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100159 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700160 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700161 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100162 func, sig = result
163 def checksig(*args, **kwargs):
164 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700165 _copy_func_details(func, checksig)
166
167 name = original.__name__
168 if not name.isidentifier():
169 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100170 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700171 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100172 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700173 return mock(*args, **kwargs)""" % name
174 exec (src, context)
175 funcopy = context[name]
Xtreakf7fa62e2018-12-12 13:24:54 +0530176 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700177 return funcopy
178
179
Xtreakf7fa62e2018-12-12 13:24:54 +0530180def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700181 funcopy.mock = mock
182
183 # can't use isinstance with mocks
184 if not _is_instance_mock(mock):
185 return
186
187 def assert_called_with(*args, **kwargs):
188 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700189 def assert_called(*args, **kwargs):
190 return mock.assert_called(*args, **kwargs)
191 def assert_not_called(*args, **kwargs):
192 return mock.assert_not_called(*args, **kwargs)
193 def assert_called_once(*args, **kwargs):
194 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700195 def assert_called_once_with(*args, **kwargs):
196 return mock.assert_called_once_with(*args, **kwargs)
197 def assert_has_calls(*args, **kwargs):
198 return mock.assert_has_calls(*args, **kwargs)
199 def assert_any_call(*args, **kwargs):
200 return mock.assert_any_call(*args, **kwargs)
201 def reset_mock():
202 funcopy.method_calls = _CallList()
203 funcopy.mock_calls = _CallList()
204 mock.reset_mock()
205 ret = funcopy.return_value
206 if _is_instance_mock(ret) and not ret is mock:
207 ret.reset_mock()
208
209 funcopy.called = False
210 funcopy.call_count = 0
211 funcopy.call_args = None
212 funcopy.call_args_list = _CallList()
213 funcopy.method_calls = _CallList()
214 funcopy.mock_calls = _CallList()
215
216 funcopy.return_value = mock.return_value
217 funcopy.side_effect = mock.side_effect
218 funcopy._mock_children = mock._mock_children
219
220 funcopy.assert_called_with = assert_called_with
221 funcopy.assert_called_once_with = assert_called_once_with
222 funcopy.assert_has_calls = assert_has_calls
223 funcopy.assert_any_call = assert_any_call
224 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700225 funcopy.assert_called = assert_called
226 funcopy.assert_not_called = assert_not_called
227 funcopy.assert_called_once = assert_called_once
Xtreakf7fa62e2018-12-12 13:24:54 +0530228 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700229
230 mock._mock_delegate = funcopy
231
232
233def _is_magic(name):
234 return '__%s__' % name[2:-2] == name
235
236
237class _SentinelObject(object):
238 "A unique, named, sentinel object."
239 def __init__(self, name):
240 self.name = name
241
242 def __repr__(self):
243 return 'sentinel.%s' % self.name
244
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200245 def __reduce__(self):
246 return 'sentinel.%s' % self.name
247
Michael Foord345266a2012-03-14 12:24:34 -0700248
249class _Sentinel(object):
250 """Access attributes to return a named object, usable as a sentinel."""
251 def __init__(self):
252 self._sentinels = {}
253
254 def __getattr__(self, name):
255 if name == '__bases__':
256 # Without this help(unittest.mock) raises an exception
257 raise AttributeError
258 return self._sentinels.setdefault(name, _SentinelObject(name))
259
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200260 def __reduce__(self):
261 return 'sentinel'
262
Michael Foord345266a2012-03-14 12:24:34 -0700263
264sentinel = _Sentinel()
265
266DEFAULT = sentinel.DEFAULT
267_missing = sentinel.MISSING
268_deleted = sentinel.DELETED
269
270
Michael Foord345266a2012-03-14 12:24:34 -0700271def _copy(value):
272 if type(value) in (dict, list, tuple, set):
273 return type(value)(value)
274 return value
275
276
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200277_allowed_names = {
278 'return_value', '_mock_return_value', 'side_effect',
279 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
280 '_mock_name', '_mock_new_name'
281}
Michael Foord345266a2012-03-14 12:24:34 -0700282
283
284def _delegating_property(name):
285 _allowed_names.add(name)
286 _the_name = '_mock_' + name
287 def _get(self, name=name, _the_name=_the_name):
288 sig = self._mock_delegate
289 if sig is None:
290 return getattr(self, _the_name)
291 return getattr(sig, name)
292 def _set(self, value, name=name, _the_name=_the_name):
293 sig = self._mock_delegate
294 if sig is None:
295 self.__dict__[_the_name] = value
296 else:
297 setattr(sig, name, value)
298
299 return property(_get, _set)
300
301
302
303class _CallList(list):
304
305 def __contains__(self, value):
306 if not isinstance(value, list):
307 return list.__contains__(self, value)
308 len_value = len(value)
309 len_self = len(self)
310 if len_value > len_self:
311 return False
312
313 for i in range(0, len_self - len_value + 1):
314 sub_list = self[i:i+len_value]
315 if sub_list == value:
316 return True
317 return False
318
319 def __repr__(self):
320 return pprint.pformat(list(self))
321
322
323def _check_and_set_parent(parent, value, name, new_name):
324 if not _is_instance_mock(value):
325 return False
326 if ((value._mock_name or value._mock_new_name) or
327 (value._mock_parent is not None) or
328 (value._mock_new_parent is not None)):
329 return False
330
331 _parent = parent
332 while _parent is not None:
333 # setting a mock (value) as a child or return value of itself
334 # should not modify the mock
335 if _parent is value:
336 return False
337 _parent = _parent._mock_new_parent
338
339 if new_name:
340 value._mock_new_parent = parent
341 value._mock_new_name = new_name
342 if name:
343 value._mock_parent = parent
344 value._mock_name = name
345 return True
346
Michael Foord01bafdc2014-04-14 16:09:42 -0400347# Internal class to identify if we wrapped an iterator object or not.
348class _MockIter(object):
349 def __init__(self, obj):
350 self.obj = iter(obj)
351 def __iter__(self):
352 return self
353 def __next__(self):
354 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700355
356class Base(object):
357 _mock_return_value = DEFAULT
358 _mock_side_effect = None
359 def __init__(self, *args, **kwargs):
360 pass
361
362
363
364class NonCallableMock(Base):
365 """A non-callable version of `Mock`"""
366
367 def __new__(cls, *args, **kw):
368 # every instance has its own class
369 # so we can create magic methods on the
370 # class without stomping on other mocks
371 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
372 instance = object.__new__(new)
373 return instance
374
375
376 def __init__(
377 self, spec=None, wraps=None, name=None, spec_set=None,
378 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530379 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700380 ):
381 if _new_parent is None:
382 _new_parent = parent
383
384 __dict__ = self.__dict__
385 __dict__['_mock_parent'] = parent
386 __dict__['_mock_name'] = name
387 __dict__['_mock_new_name'] = _new_name
388 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100389 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700390
391 if spec_set is not None:
392 spec = spec_set
393 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100394 if _eat_self is None:
395 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700396
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100397 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700398
399 __dict__['_mock_children'] = {}
400 __dict__['_mock_wraps'] = wraps
401 __dict__['_mock_delegate'] = None
402
403 __dict__['_mock_called'] = False
404 __dict__['_mock_call_args'] = None
405 __dict__['_mock_call_count'] = 0
406 __dict__['_mock_call_args_list'] = _CallList()
407 __dict__['_mock_mock_calls'] = _CallList()
408
409 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530410 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700411
412 if kwargs:
413 self.configure_mock(**kwargs)
414
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000415 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700416 spec, wraps, name, spec_set, parent,
417 _spec_state
418 )
419
420
421 def attach_mock(self, mock, attribute):
422 """
423 Attach a mock as an attribute of this one, replacing its name and
424 parent. Calls to the attached mock will be recorded in the
425 `method_calls` and `mock_calls` attributes of this one."""
426 mock._mock_parent = None
427 mock._mock_new_parent = None
428 mock._mock_name = ''
429 mock._mock_new_name = None
430
431 setattr(self, attribute, mock)
432
433
434 def mock_add_spec(self, spec, spec_set=False):
435 """Add a spec to a mock. `spec` can either be an object or a
436 list of strings. Only attributes on the `spec` can be fetched as
437 attributes from the mock.
438
439 If `spec_set` is True then only attributes on the spec can be set."""
440 self._mock_add_spec(spec, spec_set)
441
442
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100443 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
444 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700445 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100446 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700447
448 if spec is not None and not _is_list(spec):
449 if isinstance(spec, type):
450 _spec_class = spec
451 else:
452 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100453 res = _get_signature_object(spec,
454 _spec_as_instance, _eat_self)
455 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700456
457 spec = dir(spec)
458
459 __dict__ = self.__dict__
460 __dict__['_spec_class'] = _spec_class
461 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100462 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700463 __dict__['_mock_methods'] = spec
464
465
466 def __get_return_value(self):
467 ret = self._mock_return_value
468 if self._mock_delegate is not None:
469 ret = self._mock_delegate.return_value
470
471 if ret is DEFAULT:
472 ret = self._get_child_mock(
473 _new_parent=self, _new_name='()'
474 )
475 self.return_value = ret
476 return ret
477
478
479 def __set_return_value(self, value):
480 if self._mock_delegate is not None:
481 self._mock_delegate.return_value = value
482 else:
483 self._mock_return_value = value
484 _check_and_set_parent(self, value, None, '()')
485
486 __return_value_doc = "The value to be returned when the mock is called."
487 return_value = property(__get_return_value, __set_return_value,
488 __return_value_doc)
489
490
491 @property
492 def __class__(self):
493 if self._spec_class is None:
494 return type(self)
495 return self._spec_class
496
497 called = _delegating_property('called')
498 call_count = _delegating_property('call_count')
499 call_args = _delegating_property('call_args')
500 call_args_list = _delegating_property('call_args_list')
501 mock_calls = _delegating_property('mock_calls')
502
503
504 def __get_side_effect(self):
505 delegated = self._mock_delegate
506 if delegated is None:
507 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400508 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200509 if (sf is not None and not callable(sf)
510 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400511 sf = _MockIter(sf)
512 delegated.side_effect = sf
513 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700514
515 def __set_side_effect(self, value):
516 value = _try_iter(value)
517 delegated = self._mock_delegate
518 if delegated is None:
519 self._mock_side_effect = value
520 else:
521 delegated.side_effect = value
522
523 side_effect = property(__get_side_effect, __set_side_effect)
524
525
Kushal Das9cd39a12016-06-02 10:20:16 -0700526 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700527 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200528 if visited is None:
529 visited = []
530 if id(self) in visited:
531 return
532 visited.append(id(self))
533
Michael Foord345266a2012-03-14 12:24:34 -0700534 self.called = False
535 self.call_args = None
536 self.call_count = 0
537 self.mock_calls = _CallList()
538 self.call_args_list = _CallList()
539 self.method_calls = _CallList()
540
Kushal Das9cd39a12016-06-02 10:20:16 -0700541 if return_value:
542 self._mock_return_value = DEFAULT
543 if side_effect:
544 self._mock_side_effect = None
545
Michael Foord345266a2012-03-14 12:24:34 -0700546 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530547 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100548 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200549 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700550
551 ret = self._mock_return_value
552 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200553 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700554
555
556 def configure_mock(self, **kwargs):
557 """Set attributes on the mock through keyword arguments.
558
559 Attributes plus return values and side effects can be set on child
560 mocks using standard dot notation and unpacking a dictionary in the
561 method call:
562
563 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
564 >>> mock.configure_mock(**attrs)"""
565 for arg, val in sorted(kwargs.items(),
566 # we sort on the number of dots so that
567 # attributes are set before we set attributes on
568 # attributes
569 key=lambda entry: entry[0].count('.')):
570 args = arg.split('.')
571 final = args.pop()
572 obj = self
573 for entry in args:
574 obj = getattr(obj, entry)
575 setattr(obj, final, val)
576
577
578 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530579 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700580 raise AttributeError(name)
581 elif self._mock_methods is not None:
582 if name not in self._mock_methods or name in _all_magics:
583 raise AttributeError("Mock object has no attribute %r" % name)
584 elif _is_magic(name):
585 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530586 if not self._mock_unsafe:
587 if name.startswith(('assert', 'assret')):
588 raise AttributeError(name)
Michael Foord345266a2012-03-14 12:24:34 -0700589
590 result = self._mock_children.get(name)
591 if result is _deleted:
592 raise AttributeError(name)
593 elif result is None:
594 wraps = None
595 if self._mock_wraps is not None:
596 # XXXX should we get the attribute without triggering code
597 # execution?
598 wraps = getattr(self._mock_wraps, name)
599
600 result = self._get_child_mock(
601 parent=self, name=name, wraps=wraps, _new_name=name,
602 _new_parent=self
603 )
604 self._mock_children[name] = result
605
606 elif isinstance(result, _SpecState):
607 result = create_autospec(
608 result.spec, result.spec_set, result.instance,
609 result.parent, result.name
610 )
611 self._mock_children[name] = result
612
613 return result
614
615
Mario Corchero552be9d2017-10-17 12:35:11 +0100616 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700617 _name_list = [self._mock_new_name]
618 _parent = self._mock_new_parent
619 last = self
620
621 dot = '.'
622 if _name_list == ['()']:
623 dot = ''
624 seen = set()
625 while _parent is not None:
626 last = _parent
627
628 _name_list.append(_parent._mock_new_name + dot)
629 dot = '.'
630 if _parent._mock_new_name == '()':
631 dot = ''
632
633 _parent = _parent._mock_new_parent
634
635 # use ids here so as not to call __hash__ on the mocks
636 if id(_parent) in seen:
637 break
638 seen.add(id(_parent))
639
640 _name_list = list(reversed(_name_list))
641 _first = last._mock_name or 'mock'
642 if len(_name_list) > 1:
643 if _name_list[1] not in ('()', '().'):
644 _first += '.'
645 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100646 return ''.join(_name_list)
647
648 def __repr__(self):
649 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700650
651 name_string = ''
652 if name not in ('mock', 'mock.'):
653 name_string = ' name=%r' % name
654
655 spec_string = ''
656 if self._spec_class is not None:
657 spec_string = ' spec=%r'
658 if self._spec_set:
659 spec_string = ' spec_set=%r'
660 spec_string = spec_string % self._spec_class.__name__
661 return "<%s%s%s id='%s'>" % (
662 type(self).__name__,
663 name_string,
664 spec_string,
665 id(self)
666 )
667
668
669 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700670 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100671 if not FILTER_DIR:
672 return object.__dir__(self)
673
Michael Foord345266a2012-03-14 12:24:34 -0700674 extras = self._mock_methods or []
675 from_type = dir(type(self))
676 from_dict = list(self.__dict__)
677
Michael Foord313f85f2012-03-25 18:16:07 +0100678 from_type = [e for e in from_type if not e.startswith('_')]
679 from_dict = [e for e in from_dict if not e.startswith('_') or
680 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700681 return sorted(set(extras + from_type + from_dict +
682 list(self._mock_children)))
683
684
685 def __setattr__(self, name, value):
686 if name in _allowed_names:
687 # property setters go through here
688 return object.__setattr__(self, name, value)
689 elif (self._spec_set and self._mock_methods is not None and
690 name not in self._mock_methods and
691 name not in self.__dict__):
692 raise AttributeError("Mock object has no attribute '%s'" % name)
693 elif name in _unsupported_magics:
694 msg = 'Attempting to set unsupported magic method %r.' % name
695 raise AttributeError(msg)
696 elif name in _all_magics:
697 if self._mock_methods is not None and name not in self._mock_methods:
698 raise AttributeError("Mock object has no attribute '%s'" % name)
699
700 if not _is_instance_mock(value):
701 setattr(type(self), name, _get_method(name, value))
702 original = value
703 value = lambda *args, **kw: original(self, *args, **kw)
704 else:
705 # only set _new_name and not name so that mock_calls is tracked
706 # but not method calls
707 _check_and_set_parent(self, value, None, name)
708 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100709 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700710 elif name == '__class__':
711 self._spec_class = value
712 return
713 else:
714 if _check_and_set_parent(self, value, name, name):
715 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100716
717 if self._mock_sealed and not hasattr(self, name):
718 mock_name = f'{self._extract_mock_name()}.{name}'
719 raise AttributeError(f'Cannot set {mock_name}')
720
Michael Foord345266a2012-03-14 12:24:34 -0700721 return object.__setattr__(self, name, value)
722
723
724 def __delattr__(self, name):
725 if name in _all_magics and name in type(self).__dict__:
726 delattr(type(self), name)
727 if name not in self.__dict__:
728 # for magic methods that are still MagicProxy objects and
729 # not set on the instance itself
730 return
731
Michael Foord345266a2012-03-14 12:24:34 -0700732 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000733 if name in self.__dict__:
734 super().__delattr__(name)
735 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700736 raise AttributeError(name)
737 if obj is not _missing:
738 del self._mock_children[name]
739 self._mock_children[name] = _deleted
740
741
Michael Foord345266a2012-03-14 12:24:34 -0700742 def _format_mock_call_signature(self, args, kwargs):
743 name = self._mock_name or 'mock'
744 return _format_call_signature(name, args, kwargs)
745
746
747 def _format_mock_failure_message(self, args, kwargs):
748 message = 'Expected call: %s\nActual call: %s'
749 expected_string = self._format_mock_call_signature(args, kwargs)
750 call_args = self.call_args
751 if len(call_args) == 3:
752 call_args = call_args[1:]
753 actual_string = self._format_mock_call_signature(*call_args)
754 return message % (expected_string, actual_string)
755
756
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100757 def _call_matcher(self, _call):
758 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000759 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100760 comparison key suitable for matching with other calls.
761 This is a best effort method which relies on the spec's signature,
762 if available, or falls back on the arguments themselves.
763 """
764 sig = self._spec_signature
765 if sig is not None:
766 if len(_call) == 2:
767 name = ''
768 args, kwargs = _call
769 else:
770 name, args, kwargs = _call
771 try:
772 return name, sig.bind(*args, **kwargs)
773 except TypeError as e:
774 return e.with_traceback(None)
775 else:
776 return _call
777
Kushal Das68290f42014-04-17 01:54:07 +0530778 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530779 """assert that the mock was never called.
780 """
781 self = _mock_self
782 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100783 msg = ("Expected '%s' to not have been called. Called %s times.%s"
784 % (self._mock_name or 'mock',
785 self.call_count,
786 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530787 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100788
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100789 def assert_called(_mock_self):
790 """assert that the mock was called at least once
791 """
792 self = _mock_self
793 if self.call_count == 0:
794 msg = ("Expected '%s' to have been called." %
795 self._mock_name or 'mock')
796 raise AssertionError(msg)
797
798 def assert_called_once(_mock_self):
799 """assert that the mock was called only once.
800 """
801 self = _mock_self
802 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100803 msg = ("Expected '%s' to have been called once. Called %s times.%s"
804 % (self._mock_name or 'mock',
805 self.call_count,
806 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100807 raise AssertionError(msg)
808
Michael Foord345266a2012-03-14 12:24:34 -0700809 def assert_called_with(_mock_self, *args, **kwargs):
810 """assert that the mock was called with the specified arguments.
811
812 Raises an AssertionError if the args and keyword args passed in are
813 different to the last call to the mock."""
814 self = _mock_self
815 if self.call_args is None:
816 expected = self._format_mock_call_signature(args, kwargs)
817 raise AssertionError('Expected call: %s\nNot called' % (expected,))
818
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100819 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700820 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100821 return msg
822 expected = self._call_matcher((args, kwargs))
823 actual = self._call_matcher(self.call_args)
824 if expected != actual:
825 cause = expected if isinstance(expected, Exception) else None
826 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700827
828
829 def assert_called_once_with(_mock_self, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100830 """assert that the mock was called exactly once and that that call was
831 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700832 self = _mock_self
833 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100834 msg = ("Expected '%s' to be called once. Called %s times.%s"
835 % (self._mock_name or 'mock',
836 self.call_count,
837 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700838 raise AssertionError(msg)
839 return self.assert_called_with(*args, **kwargs)
840
841
842 def assert_has_calls(self, calls, any_order=False):
843 """assert the mock has been called with the specified calls.
844 The `mock_calls` list is checked for the calls.
845
846 If `any_order` is False (the default) then the calls must be
847 sequential. There can be extra calls before or after the
848 specified calls.
849
850 If `any_order` is True then the calls can be in any order, but
851 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100852 expected = [self._call_matcher(c) for c in calls]
853 cause = expected if isinstance(expected, Exception) else None
854 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700855 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100856 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700857 raise AssertionError(
Petter Strandmark47d94242018-10-28 21:37:10 +0100858 'Calls not found.\nExpected: %r%s'
859 % (_CallList(calls), self._calls_repr(prefix="Actual"))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100860 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700861 return
862
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100863 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700864
865 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100866 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700867 try:
868 all_calls.remove(kall)
869 except ValueError:
870 not_found.append(kall)
871 if not_found:
872 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400873 '%r does not contain all of %r in its call list, '
874 'found %r instead' % (self._mock_name or 'mock',
875 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100876 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700877
878
879 def assert_any_call(self, *args, **kwargs):
880 """assert the mock has been called with the specified arguments.
881
882 The assert passes if the mock has *ever* been called, unlike
883 `assert_called_with` and `assert_called_once_with` that only pass if
884 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100885 expected = self._call_matcher((args, kwargs))
886 actual = [self._call_matcher(c) for c in self.call_args_list]
887 if expected not in actual:
888 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700889 expected_string = self._format_mock_call_signature(args, kwargs)
890 raise AssertionError(
891 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100892 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700893
894
895 def _get_child_mock(self, **kw):
896 """Create the child mocks for attributes and return value.
897 By default child mocks will be the same type as the parent.
898 Subclasses of Mock may want to override this to customize the way
899 child mocks are made.
900
901 For non-callable mocks the callable variant will be used (rather than
902 any custom subclass)."""
903 _type = type(self)
904 if not issubclass(_type, CallableMixin):
905 if issubclass(_type, NonCallableMagicMock):
906 klass = MagicMock
907 elif issubclass(_type, NonCallableMock) :
908 klass = Mock
909 else:
910 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +0100911
912 if self._mock_sealed:
913 attribute = "." + kw["name"] if "name" in kw else "()"
914 mock_name = self._extract_mock_name() + attribute
915 raise AttributeError(mock_name)
916
Michael Foord345266a2012-03-14 12:24:34 -0700917 return klass(**kw)
918
919
Petter Strandmark47d94242018-10-28 21:37:10 +0100920 def _calls_repr(self, prefix="Calls"):
921 """Renders self.mock_calls as a string.
922
923 Example: "\nCalls: [call(1), call(2)]."
924
925 If self.mock_calls is empty, an empty string is returned. The
926 output will be truncated if very long.
927 """
928 if not self.mock_calls:
929 return ""
930 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
931
932
Michael Foord345266a2012-03-14 12:24:34 -0700933
934def _try_iter(obj):
935 if obj is None:
936 return obj
937 if _is_exception(obj):
938 return obj
939 if _callable(obj):
940 return obj
941 try:
942 return iter(obj)
943 except TypeError:
944 # XXXX backwards compatibility
945 # but this will blow up on first call - so maybe we should fail early?
946 return obj
947
948
949
950class CallableMixin(Base):
951
952 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
953 wraps=None, name=None, spec_set=None, parent=None,
954 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
955 self.__dict__['_mock_return_value'] = return_value
956
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000957 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700958 spec, wraps, name, spec_set, parent,
959 _spec_state, _new_name, _new_parent, **kwargs
960 )
961
962 self.side_effect = side_effect
963
964
965 def _mock_check_sig(self, *args, **kwargs):
966 # stub method that can be replaced with one with a specific signature
967 pass
968
969
970 def __call__(_mock_self, *args, **kwargs):
971 # can't use self in-case a function / method we are mocking uses self
972 # in the signature
973 _mock_self._mock_check_sig(*args, **kwargs)
974 return _mock_self._mock_call(*args, **kwargs)
975
976
977 def _mock_call(_mock_self, *args, **kwargs):
978 self = _mock_self
979 self.called = True
980 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100981
Chris Withers8ca0fa92018-12-03 21:31:37 +0000982 # handle call_args
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100983 _call = _Call((args, kwargs), two=True)
984 self.call_args = _call
985 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700986
987 seen = set()
Chris Withers8ca0fa92018-12-03 21:31:37 +0000988
989 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700990 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +0000991 method_call_name = self._mock_name
992
993 # initial stuff for mock_calls:
994 mock_call_name = self._mock_new_name
995 is_a_call = mock_call_name == '()'
996 self.mock_calls.append(_Call(('', args, kwargs)))
997
998 # follow up the chain of mocks:
999 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001000 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001001
Chris Withers8ca0fa92018-12-03 21:31:37 +00001002 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001003 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001004 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001005 do_method_calls = _new_parent._mock_parent is not None
1006 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001007 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001008
Chris Withers8ca0fa92018-12-03 21:31:37 +00001009 # handle mock_calls:
1010 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001011 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001012
1013 if _new_parent._mock_new_name:
1014 if is_a_call:
1015 dot = ''
1016 else:
1017 dot = '.'
1018 is_a_call = _new_parent._mock_new_name == '()'
1019 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1020
1021 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001022 _new_parent = _new_parent._mock_new_parent
1023
Chris Withers8ca0fa92018-12-03 21:31:37 +00001024 # check we're not in an infinite loop:
1025 # ( use ids here so as not to call __hash__ on the mocks)
Michael Foord345266a2012-03-14 12:24:34 -07001026 _new_parent_id = id(_new_parent)
1027 if _new_parent_id in seen:
1028 break
1029 seen.add(_new_parent_id)
1030
Michael Foord345266a2012-03-14 12:24:34 -07001031 effect = self.side_effect
1032 if effect is not None:
1033 if _is_exception(effect):
1034 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001035 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001036 result = next(effect)
1037 if _is_exception(result):
1038 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001039 else:
1040 result = effect(*args, **kwargs)
1041
1042 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001043 return result
Michael Foord345266a2012-03-14 12:24:34 -07001044
Mario Corcherof05df0a2018-12-08 11:25:02 +00001045 if self._mock_return_value is not DEFAULT:
1046 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001047
Mario Corcherof05df0a2018-12-08 11:25:02 +00001048 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001049 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001050
1051 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001052
1053
1054
1055class Mock(CallableMixin, NonCallableMock):
1056 """
1057 Create a new `Mock` object. `Mock` takes several optional arguments
1058 that specify the behaviour of the Mock object:
1059
1060 * `spec`: This can be either a list of strings or an existing object (a
1061 class or instance) that acts as the specification for the mock object. If
1062 you pass in an object then a list of strings is formed by calling dir on
1063 the object (excluding unsupported magic attributes and methods). Accessing
1064 any attribute not in this list will raise an `AttributeError`.
1065
1066 If `spec` is an object (rather than a list of strings) then
1067 `mock.__class__` returns the class of the spec object. This allows mocks
1068 to pass `isinstance` tests.
1069
1070 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1071 or get an attribute on the mock that isn't on the object passed as
1072 `spec_set` will raise an `AttributeError`.
1073
1074 * `side_effect`: A function to be called whenever the Mock is called. See
1075 the `side_effect` attribute. Useful for raising exceptions or
1076 dynamically changing return values. The function is called with the same
1077 arguments as the mock, and unless it returns `DEFAULT`, the return
1078 value of this function is used as the return value.
1079
Michael Foord2cd48732012-04-21 15:52:11 +01001080 If `side_effect` is an iterable then each call to the mock will return
1081 the next value from the iterable. If any of the members of the iterable
1082 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001083
Michael Foord345266a2012-03-14 12:24:34 -07001084 * `return_value`: The value returned when the mock is called. By default
1085 this is a new Mock (created on first access). See the
1086 `return_value` attribute.
1087
Michael Foord0682a0c2012-04-13 20:51:20 +01001088 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1089 calling the Mock will pass the call through to the wrapped object
1090 (returning the real result). Attribute access on the mock will return a
1091 Mock object that wraps the corresponding attribute of the wrapped object
1092 (so attempting to access an attribute that doesn't exist will raise an
1093 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001094
1095 If the mock has an explicit `return_value` set then calls are not passed
1096 to the wrapped object and the `return_value` is returned instead.
1097
1098 * `name`: If the mock has a name then it will be used in the repr of the
1099 mock. This can be useful for debugging. The name is propagated to child
1100 mocks.
1101
1102 Mocks can also be called with arbitrary keyword arguments. These will be
1103 used to set attributes on the mock after it is created.
1104 """
1105
1106
1107
1108def _dot_lookup(thing, comp, import_path):
1109 try:
1110 return getattr(thing, comp)
1111 except AttributeError:
1112 __import__(import_path)
1113 return getattr(thing, comp)
1114
1115
1116def _importer(target):
1117 components = target.split('.')
1118 import_path = components.pop(0)
1119 thing = __import__(import_path)
1120
1121 for comp in components:
1122 import_path += ".%s" % comp
1123 thing = _dot_lookup(thing, comp, import_path)
1124 return thing
1125
1126
1127def _is_started(patcher):
1128 # XXXX horrible
1129 return hasattr(patcher, 'is_local')
1130
1131
1132class _patch(object):
1133
1134 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001135 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001136
1137 def __init__(
1138 self, getter, attribute, new, spec, create,
1139 spec_set, autospec, new_callable, kwargs
1140 ):
1141 if new_callable is not None:
1142 if new is not DEFAULT:
1143 raise ValueError(
1144 "Cannot use 'new' and 'new_callable' together"
1145 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001146 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001147 raise ValueError(
1148 "Cannot use 'autospec' and 'new_callable' together"
1149 )
1150
1151 self.getter = getter
1152 self.attribute = attribute
1153 self.new = new
1154 self.new_callable = new_callable
1155 self.spec = spec
1156 self.create = create
1157 self.has_local = False
1158 self.spec_set = spec_set
1159 self.autospec = autospec
1160 self.kwargs = kwargs
1161 self.additional_patchers = []
1162
1163
1164 def copy(self):
1165 patcher = _patch(
1166 self.getter, self.attribute, self.new, self.spec,
1167 self.create, self.spec_set,
1168 self.autospec, self.new_callable, self.kwargs
1169 )
1170 patcher.attribute_name = self.attribute_name
1171 patcher.additional_patchers = [
1172 p.copy() for p in self.additional_patchers
1173 ]
1174 return patcher
1175
1176
1177 def __call__(self, func):
1178 if isinstance(func, type):
1179 return self.decorate_class(func)
1180 return self.decorate_callable(func)
1181
1182
1183 def decorate_class(self, klass):
1184 for attr in dir(klass):
1185 if not attr.startswith(patch.TEST_PREFIX):
1186 continue
1187
1188 attr_value = getattr(klass, attr)
1189 if not hasattr(attr_value, "__call__"):
1190 continue
1191
1192 patcher = self.copy()
1193 setattr(klass, attr, patcher(attr_value))
1194 return klass
1195
1196
1197 def decorate_callable(self, func):
1198 if hasattr(func, 'patchings'):
1199 func.patchings.append(self)
1200 return func
1201
1202 @wraps(func)
1203 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001204 extra_args = []
1205 entered_patchers = []
1206
Michael Foord50a8c0e2012-03-25 18:57:58 +01001207 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001208 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001209 for patching in patched.patchings:
1210 arg = patching.__enter__()
1211 entered_patchers.append(patching)
1212 if patching.attribute_name is not None:
1213 keywargs.update(arg)
1214 elif patching.new is DEFAULT:
1215 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001216
Michael Foordd7c65e22012-03-14 14:56:54 -07001217 args += tuple(extra_args)
1218 return func(*args, **keywargs)
1219 except:
1220 if (patching not in entered_patchers and
1221 _is_started(patching)):
1222 # the patcher may have been started, but an exception
1223 # raised whilst entering one of its additional_patchers
1224 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001225 # Pass the exception to __exit__
1226 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001227 # re-raise the exception
1228 raise
Michael Foord345266a2012-03-14 12:24:34 -07001229 finally:
1230 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001231 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001232
1233 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001234 return patched
1235
1236
1237 def get_original(self):
1238 target = self.getter()
1239 name = self.attribute
1240
1241 original = DEFAULT
1242 local = False
1243
1244 try:
1245 original = target.__dict__[name]
1246 except (AttributeError, KeyError):
1247 original = getattr(target, name, DEFAULT)
1248 else:
1249 local = True
1250
Michael Foordfddcfa22014-04-14 16:25:20 -04001251 if name in _builtins and isinstance(target, ModuleType):
1252 self.create = True
1253
Michael Foord345266a2012-03-14 12:24:34 -07001254 if not self.create and original is DEFAULT:
1255 raise AttributeError(
1256 "%s does not have the attribute %r" % (target, name)
1257 )
1258 return original, local
1259
1260
1261 def __enter__(self):
1262 """Perform the patch."""
1263 new, spec, spec_set = self.new, self.spec, self.spec_set
1264 autospec, kwargs = self.autospec, self.kwargs
1265 new_callable = self.new_callable
1266 self.target = self.getter()
1267
Michael Foord50a8c0e2012-03-25 18:57:58 +01001268 # normalise False to None
1269 if spec is False:
1270 spec = None
1271 if spec_set is False:
1272 spec_set = None
1273 if autospec is False:
1274 autospec = None
1275
1276 if spec is not None and autospec is not None:
1277 raise TypeError("Can't specify spec and autospec")
1278 if ((spec is not None or autospec is not None) and
1279 spec_set not in (True, None)):
1280 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1281
Michael Foord345266a2012-03-14 12:24:34 -07001282 original, local = self.get_original()
1283
Michael Foord50a8c0e2012-03-25 18:57:58 +01001284 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001285 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001286 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001287 # set spec to the object we are replacing
1288 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001289 if spec_set is True:
1290 spec_set = original
1291 spec = None
1292 elif spec is not None:
1293 if spec_set is True:
1294 spec_set = spec
1295 spec = None
1296 elif spec_set is True:
1297 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001298
Michael Foord50a8c0e2012-03-25 18:57:58 +01001299 if spec is not None or spec_set is not None:
1300 if original is DEFAULT:
1301 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001302 if isinstance(original, type):
1303 # If we're patching out a class and there is a spec
1304 inherit = True
1305
1306 Klass = MagicMock
1307 _kwargs = {}
1308 if new_callable is not None:
1309 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001310 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001311 this_spec = spec
1312 if spec_set is not None:
1313 this_spec = spec_set
1314 if _is_list(this_spec):
1315 not_callable = '__call__' not in this_spec
1316 else:
1317 not_callable = not callable(this_spec)
1318 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001319 Klass = NonCallableMagicMock
1320
1321 if spec is not None:
1322 _kwargs['spec'] = spec
1323 if spec_set is not None:
1324 _kwargs['spec_set'] = spec_set
1325
1326 # add a name to mocks
1327 if (isinstance(Klass, type) and
1328 issubclass(Klass, NonCallableMock) and self.attribute):
1329 _kwargs['name'] = self.attribute
1330
1331 _kwargs.update(kwargs)
1332 new = Klass(**_kwargs)
1333
1334 if inherit and _is_instance_mock(new):
1335 # we can only tell if the instance should be callable if the
1336 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001337 this_spec = spec
1338 if spec_set is not None:
1339 this_spec = spec_set
1340 if (not _is_list(this_spec) and not
1341 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001342 Klass = NonCallableMagicMock
1343
1344 _kwargs.pop('name')
1345 new.return_value = Klass(_new_parent=new, _new_name='()',
1346 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001347 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001348 # spec is ignored, new *must* be default, spec_set is treated
1349 # as a boolean. Should we check spec is not None and that spec_set
1350 # is a bool?
1351 if new is not DEFAULT:
1352 raise TypeError(
1353 "autospec creates the mock for you. Can't specify "
1354 "autospec and new."
1355 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001356 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001357 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001358 spec_set = bool(spec_set)
1359 if autospec is True:
1360 autospec = original
1361
1362 new = create_autospec(autospec, spec_set=spec_set,
1363 _name=self.attribute, **kwargs)
1364 elif kwargs:
1365 # can't set keyword args when we aren't creating the mock
1366 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1367 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1368
1369 new_attr = new
1370
1371 self.temp_original = original
1372 self.is_local = local
1373 setattr(self.target, self.attribute, new_attr)
1374 if self.attribute_name is not None:
1375 extra_args = {}
1376 if self.new is DEFAULT:
1377 extra_args[self.attribute_name] = new
1378 for patching in self.additional_patchers:
1379 arg = patching.__enter__()
1380 if patching.new is DEFAULT:
1381 extra_args.update(arg)
1382 return extra_args
1383
1384 return new
1385
1386
Michael Foord50a8c0e2012-03-25 18:57:58 +01001387 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001388 """Undo the patch."""
1389 if not _is_started(self):
1390 raise RuntimeError('stop called on unstarted patcher')
1391
1392 if self.is_local and self.temp_original is not DEFAULT:
1393 setattr(self.target, self.attribute, self.temp_original)
1394 else:
1395 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001396 if not self.create and (not hasattr(self.target, self.attribute) or
1397 self.attribute in ('__doc__', '__module__',
1398 '__defaults__', '__annotations__',
1399 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001400 # needed for proxy objects like django settings
1401 setattr(self.target, self.attribute, self.temp_original)
1402
1403 del self.temp_original
1404 del self.is_local
1405 del self.target
1406 for patcher in reversed(self.additional_patchers):
1407 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001408 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001409
Michael Foordf7c41582012-06-10 20:36:32 +01001410
1411 def start(self):
1412 """Activate a patch, returning any created mock."""
1413 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001414 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001415 return result
1416
1417
1418 def stop(self):
1419 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001420 try:
1421 self._active_patches.remove(self)
1422 except ValueError:
1423 # If the patch hasn't been started this will fail
1424 pass
1425
Michael Foordf7c41582012-06-10 20:36:32 +01001426 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001427
1428
1429
1430def _get_target(target):
1431 try:
1432 target, attribute = target.rsplit('.', 1)
1433 except (TypeError, ValueError):
1434 raise TypeError("Need a valid target to patch. You supplied: %r" %
1435 (target,))
1436 getter = lambda: _importer(target)
1437 return getter, attribute
1438
1439
1440def _patch_object(
1441 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001442 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001443 new_callable=None, **kwargs
1444 ):
1445 """
Michael Foord345266a2012-03-14 12:24:34 -07001446 patch the named member (`attribute`) on an object (`target`) with a mock
1447 object.
1448
1449 `patch.object` can be used as a decorator, class decorator or a context
1450 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1451 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1452 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1453 the mock object it creates.
1454
1455 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1456 for choosing which methods to wrap.
1457 """
1458 getter = lambda: target
1459 return _patch(
1460 getter, attribute, new, spec, create,
1461 spec_set, autospec, new_callable, kwargs
1462 )
1463
1464
Michael Foord50a8c0e2012-03-25 18:57:58 +01001465def _patch_multiple(target, spec=None, create=False, spec_set=None,
1466 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001467 """Perform multiple patches in a single call. It takes the object to be
1468 patched (either as an object or a string to fetch the object by importing)
1469 and keyword arguments for the patches::
1470
1471 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1472 ...
1473
1474 Use `DEFAULT` as the value if you want `patch.multiple` to create
1475 mocks for you. In this case the created mocks are passed into a decorated
1476 function by keyword, and a dictionary is returned when `patch.multiple` is
1477 used as a context manager.
1478
1479 `patch.multiple` can be used as a decorator, class decorator or a context
1480 manager. The arguments `spec`, `spec_set`, `create`,
1481 `autospec` and `new_callable` have the same meaning as for `patch`. These
1482 arguments will be applied to *all* patches done by `patch.multiple`.
1483
1484 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1485 for choosing which methods to wrap.
1486 """
1487 if type(target) is str:
1488 getter = lambda: _importer(target)
1489 else:
1490 getter = lambda: target
1491
1492 if not kwargs:
1493 raise ValueError(
1494 'Must supply at least one keyword argument with patch.multiple'
1495 )
1496 # need to wrap in a list for python 3, where items is a view
1497 items = list(kwargs.items())
1498 attribute, new = items[0]
1499 patcher = _patch(
1500 getter, attribute, new, spec, create, spec_set,
1501 autospec, new_callable, {}
1502 )
1503 patcher.attribute_name = attribute
1504 for attribute, new in items[1:]:
1505 this_patcher = _patch(
1506 getter, attribute, new, spec, create, spec_set,
1507 autospec, new_callable, {}
1508 )
1509 this_patcher.attribute_name = attribute
1510 patcher.additional_patchers.append(this_patcher)
1511 return patcher
1512
1513
1514def patch(
1515 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001516 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001517 ):
1518 """
1519 `patch` acts as a function decorator, class decorator or a context
1520 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001521 is patched with a `new` object. When the function/with statement exits
1522 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001523
Michael Foord54b3db82012-03-28 15:08:08 +01001524 If `new` is omitted, then the target is replaced with a
1525 `MagicMock`. If `patch` is used as a decorator and `new` is
1526 omitted, the created mock is passed in as an extra argument to the
1527 decorated function. If `patch` is used as a context manager the created
1528 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001529
Michael Foord54b3db82012-03-28 15:08:08 +01001530 `target` should be a string in the form `'package.module.ClassName'`. The
1531 `target` is imported and the specified object replaced with the `new`
1532 object, so the `target` must be importable from the environment you are
1533 calling `patch` from. The target is imported when the decorated function
1534 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001535
1536 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1537 if patch is creating one for you.
1538
1539 In addition you can pass `spec=True` or `spec_set=True`, which causes
1540 patch to pass in the object being mocked as the spec/spec_set object.
1541
1542 `new_callable` allows you to specify a different class, or callable object,
1543 that will be called to create the `new` object. By default `MagicMock` is
1544 used.
1545
1546 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001547 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001548 All attributes of the mock will also have the spec of the corresponding
1549 attribute of the object being replaced. Methods and functions being
1550 mocked will have their arguments checked and will raise a `TypeError` if
1551 they are called with the wrong signature. For mocks replacing a class,
1552 their return value (the 'instance') will have the same spec as the class.
1553
1554 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1555 arbitrary object as the spec instead of the one being replaced.
1556
1557 By default `patch` will fail to replace attributes that don't exist. If
1558 you pass in `create=True`, and the attribute doesn't exist, patch will
1559 create the attribute for you when the patched function is called, and
1560 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001561 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001562 default because it can be dangerous. With it switched on you can write
1563 passing tests against APIs that don't actually exist!
1564
1565 Patch can be used as a `TestCase` class decorator. It works by
1566 decorating each test method in the class. This reduces the boilerplate
1567 code when your test methods share a common patchings set. `patch` finds
1568 tests by looking for method names that start with `patch.TEST_PREFIX`.
1569 By default this is `test`, which matches the way `unittest` finds tests.
1570 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1571
1572 Patch can be used as a context manager, with the with statement. Here the
1573 patching applies to the indented block after the with statement. If you
1574 use "as" then the patched object will be bound to the name after the
1575 "as"; very useful if `patch` is creating a mock object for you.
1576
1577 `patch` takes arbitrary keyword arguments. These will be passed to
1578 the `Mock` (or `new_callable`) on construction.
1579
1580 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1581 available for alternate use-cases.
1582 """
1583 getter, attribute = _get_target(target)
1584 return _patch(
1585 getter, attribute, new, spec, create,
1586 spec_set, autospec, new_callable, kwargs
1587 )
1588
1589
1590class _patch_dict(object):
1591 """
1592 Patch a dictionary, or dictionary like object, and restore the dictionary
1593 to its original state after the test.
1594
1595 `in_dict` can be a dictionary or a mapping like container. If it is a
1596 mapping then it must at least support getting, setting and deleting items
1597 plus iterating over keys.
1598
1599 `in_dict` can also be a string specifying the name of the dictionary, which
1600 will then be fetched by importing it.
1601
1602 `values` can be a dictionary of values to set in the dictionary. `values`
1603 can also be an iterable of `(key, value)` pairs.
1604
1605 If `clear` is True then the dictionary will be cleared before the new
1606 values are set.
1607
1608 `patch.dict` can also be called with arbitrary keyword arguments to set
1609 values in the dictionary::
1610
1611 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1612 ...
1613
1614 `patch.dict` can be used as a context manager, decorator or class
1615 decorator. When used as a class decorator `patch.dict` honours
1616 `patch.TEST_PREFIX` for choosing which methods to wrap.
1617 """
1618
1619 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1620 if isinstance(in_dict, str):
1621 in_dict = _importer(in_dict)
1622 self.in_dict = in_dict
1623 # support any argument supported by dict(...) constructor
1624 self.values = dict(values)
1625 self.values.update(kwargs)
1626 self.clear = clear
1627 self._original = None
1628
1629
1630 def __call__(self, f):
1631 if isinstance(f, type):
1632 return self.decorate_class(f)
1633 @wraps(f)
1634 def _inner(*args, **kw):
1635 self._patch_dict()
1636 try:
1637 return f(*args, **kw)
1638 finally:
1639 self._unpatch_dict()
1640
1641 return _inner
1642
1643
1644 def decorate_class(self, klass):
1645 for attr in dir(klass):
1646 attr_value = getattr(klass, attr)
1647 if (attr.startswith(patch.TEST_PREFIX) and
1648 hasattr(attr_value, "__call__")):
1649 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1650 decorated = decorator(attr_value)
1651 setattr(klass, attr, decorated)
1652 return klass
1653
1654
1655 def __enter__(self):
1656 """Patch the dict."""
1657 self._patch_dict()
1658
1659
1660 def _patch_dict(self):
1661 values = self.values
1662 in_dict = self.in_dict
1663 clear = self.clear
1664
1665 try:
1666 original = in_dict.copy()
1667 except AttributeError:
1668 # dict like object with no copy method
1669 # must support iteration over keys
1670 original = {}
1671 for key in in_dict:
1672 original[key] = in_dict[key]
1673 self._original = original
1674
1675 if clear:
1676 _clear_dict(in_dict)
1677
1678 try:
1679 in_dict.update(values)
1680 except AttributeError:
1681 # dict like object with no update method
1682 for key in values:
1683 in_dict[key] = values[key]
1684
1685
1686 def _unpatch_dict(self):
1687 in_dict = self.in_dict
1688 original = self._original
1689
1690 _clear_dict(in_dict)
1691
1692 try:
1693 in_dict.update(original)
1694 except AttributeError:
1695 for key in original:
1696 in_dict[key] = original[key]
1697
1698
1699 def __exit__(self, *args):
1700 """Unpatch the dict."""
1701 self._unpatch_dict()
1702 return False
1703
1704 start = __enter__
1705 stop = __exit__
1706
1707
1708def _clear_dict(in_dict):
1709 try:
1710 in_dict.clear()
1711 except AttributeError:
1712 keys = list(in_dict)
1713 for key in keys:
1714 del in_dict[key]
1715
1716
Michael Foordf7c41582012-06-10 20:36:32 +01001717def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001718 """Stop all active patches. LIFO to unroll nested patches."""
1719 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001720 patch.stop()
1721
1722
Michael Foord345266a2012-03-14 12:24:34 -07001723patch.object = _patch_object
1724patch.dict = _patch_dict
1725patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001726patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001727patch.TEST_PREFIX = 'test'
1728
1729magic_methods = (
1730 "lt le gt ge eq ne "
1731 "getitem setitem delitem "
1732 "len contains iter "
1733 "hash str sizeof "
1734 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001735 # we added divmod and rdivmod here instead of numerics
1736 # because there is no idivmod
1737 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001738 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001739 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001740 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001741 "fspath "
Michael Foord345266a2012-03-14 12:24:34 -07001742)
1743
Michael Foordd2623d72014-04-14 11:23:48 -04001744numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001745 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001746)
Michael Foord345266a2012-03-14 12:24:34 -07001747inplace = ' '.join('i%s' % n for n in numerics.split())
1748right = ' '.join('r%s' % n for n in numerics.split())
1749
1750# not including __prepare__, __instancecheck__, __subclasscheck__
1751# (as they are metaclass methods)
1752# __del__ is not supported at all as it causes problems if it exists
1753
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001754_non_defaults = {
1755 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1756 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1757 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1758 '__repr__', '__dir__', '__subclasses__', '__format__',
Serhiy Storchaka5943ea72016-06-19 18:30:43 +03001759 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001760}
Michael Foord345266a2012-03-14 12:24:34 -07001761
1762
1763def _get_method(name, func):
1764 "Turns a callable object (like a mock) into a real function"
1765 def method(self, *args, **kw):
1766 return func(self, *args, **kw)
1767 method.__name__ = name
1768 return method
1769
1770
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001771_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001772 '__%s__' % method for method in
1773 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001774}
Michael Foord345266a2012-03-14 12:24:34 -07001775
1776_all_magics = _magics | _non_defaults
1777
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001778_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001779 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001780 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001781 '__instancecheck__', '__subclasscheck__',
1782 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001783}
Michael Foord345266a2012-03-14 12:24:34 -07001784
1785_calculate_return_value = {
1786 '__hash__': lambda self: object.__hash__(self),
1787 '__str__': lambda self: object.__str__(self),
1788 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001789 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001790}
1791
1792_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001793 '__lt__': NotImplemented,
1794 '__gt__': NotImplemented,
1795 '__le__': NotImplemented,
1796 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001797 '__int__': 1,
1798 '__contains__': False,
1799 '__len__': 0,
1800 '__exit__': False,
1801 '__complex__': 1j,
1802 '__float__': 1.0,
1803 '__bool__': True,
1804 '__index__': 1,
1805}
1806
1807
1808def _get_eq(self):
1809 def __eq__(other):
1810 ret_val = self.__eq__._mock_return_value
1811 if ret_val is not DEFAULT:
1812 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001813 if self is other:
1814 return True
1815 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001816 return __eq__
1817
1818def _get_ne(self):
1819 def __ne__(other):
1820 if self.__ne__._mock_return_value is not DEFAULT:
1821 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001822 if self is other:
1823 return False
1824 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001825 return __ne__
1826
1827def _get_iter(self):
1828 def __iter__():
1829 ret_val = self.__iter__._mock_return_value
1830 if ret_val is DEFAULT:
1831 return iter([])
1832 # if ret_val was already an iterator, then calling iter on it should
1833 # return the iterator unchanged
1834 return iter(ret_val)
1835 return __iter__
1836
1837_side_effect_methods = {
1838 '__eq__': _get_eq,
1839 '__ne__': _get_ne,
1840 '__iter__': _get_iter,
1841}
1842
1843
1844
1845def _set_return_value(mock, method, name):
1846 fixed = _return_values.get(name, DEFAULT)
1847 if fixed is not DEFAULT:
1848 method.return_value = fixed
1849 return
1850
1851 return_calulator = _calculate_return_value.get(name)
1852 if return_calulator is not None:
1853 try:
1854 return_value = return_calulator(mock)
1855 except AttributeError:
1856 # XXXX why do we return AttributeError here?
1857 # set it as a side_effect instead?
1858 return_value = AttributeError(name)
1859 method.return_value = return_value
1860 return
1861
1862 side_effector = _side_effect_methods.get(name)
1863 if side_effector is not None:
1864 method.side_effect = side_effector(mock)
1865
1866
1867
1868class MagicMixin(object):
1869 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001870 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001871 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001872 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001873
1874
1875 def _mock_set_magics(self):
1876 these_magics = _magics
1877
Łukasz Langaa468db92015-04-13 23:12:42 -07001878 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001879 these_magics = _magics.intersection(self._mock_methods)
1880
1881 remove_magics = set()
1882 remove_magics = _magics - these_magics
1883
1884 for entry in remove_magics:
1885 if entry in type(self).__dict__:
1886 # remove unneeded magic methods
1887 delattr(self, entry)
1888
1889 # don't overwrite existing attributes if called a second time
1890 these_magics = these_magics - set(type(self).__dict__)
1891
1892 _type = type(self)
1893 for entry in these_magics:
1894 setattr(_type, entry, MagicProxy(entry, self))
1895
1896
1897
1898class NonCallableMagicMock(MagicMixin, NonCallableMock):
1899 """A version of `MagicMock` that isn't callable."""
1900 def mock_add_spec(self, spec, spec_set=False):
1901 """Add a spec to a mock. `spec` can either be an object or a
1902 list of strings. Only attributes on the `spec` can be fetched as
1903 attributes from the mock.
1904
1905 If `spec_set` is True then only attributes on the spec can be set."""
1906 self._mock_add_spec(spec, spec_set)
1907 self._mock_set_magics()
1908
1909
1910
1911class MagicMock(MagicMixin, Mock):
1912 """
1913 MagicMock is a subclass of Mock with default implementations
1914 of most of the magic methods. You can use MagicMock without having to
1915 configure the magic methods yourself.
1916
1917 If you use the `spec` or `spec_set` arguments then *only* magic
1918 methods that exist in the spec will be created.
1919
1920 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1921 """
1922 def mock_add_spec(self, spec, spec_set=False):
1923 """Add a spec to a mock. `spec` can either be an object or a
1924 list of strings. Only attributes on the `spec` can be fetched as
1925 attributes from the mock.
1926
1927 If `spec_set` is True then only attributes on the spec can be set."""
1928 self._mock_add_spec(spec, spec_set)
1929 self._mock_set_magics()
1930
1931
1932
1933class MagicProxy(object):
1934 def __init__(self, name, parent):
1935 self.name = name
1936 self.parent = parent
1937
1938 def __call__(self, *args, **kwargs):
1939 m = self.create_mock()
1940 return m(*args, **kwargs)
1941
1942 def create_mock(self):
1943 entry = self.name
1944 parent = self.parent
1945 m = parent._get_child_mock(name=entry, _new_name=entry,
1946 _new_parent=parent)
1947 setattr(parent, entry, m)
1948 _set_return_value(parent, m, entry)
1949 return m
1950
1951 def __get__(self, obj, _type=None):
1952 return self.create_mock()
1953
1954
1955
1956class _ANY(object):
1957 "A helper object that compares equal to everything."
1958
1959 def __eq__(self, other):
1960 return True
1961
1962 def __ne__(self, other):
1963 return False
1964
1965 def __repr__(self):
1966 return '<ANY>'
1967
1968ANY = _ANY()
1969
1970
1971
1972def _format_call_signature(name, args, kwargs):
1973 message = '%s(%%s)' % name
1974 formatted_args = ''
1975 args_string = ', '.join([repr(arg) for arg in args])
1976 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301977 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001978 ])
1979 if args_string:
1980 formatted_args = args_string
1981 if kwargs_string:
1982 if formatted_args:
1983 formatted_args += ', '
1984 formatted_args += kwargs_string
1985
1986 return message % formatted_args
1987
1988
1989
1990class _Call(tuple):
1991 """
1992 A tuple for holding the results of a call to a mock, either in the form
1993 `(args, kwargs)` or `(name, args, kwargs)`.
1994
1995 If args or kwargs are empty then a call tuple will compare equal to
1996 a tuple without those values. This makes comparisons less verbose::
1997
1998 _Call(('name', (), {})) == ('name',)
1999 _Call(('name', (1,), {})) == ('name', (1,))
2000 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2001
2002 The `_Call` object provides a useful shortcut for comparing with call::
2003
2004 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2005 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2006
2007 If the _Call has no name then it will match any name.
2008 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002009 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002010 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002011 args = ()
2012 kwargs = {}
2013 _len = len(value)
2014 if _len == 3:
2015 name, args, kwargs = value
2016 elif _len == 2:
2017 first, second = value
2018 if isinstance(first, str):
2019 name = first
2020 if isinstance(second, tuple):
2021 args = second
2022 else:
2023 kwargs = second
2024 else:
2025 args, kwargs = first, second
2026 elif _len == 1:
2027 value, = value
2028 if isinstance(value, str):
2029 name = value
2030 elif isinstance(value, tuple):
2031 args = value
2032 else:
2033 kwargs = value
2034
2035 if two:
2036 return tuple.__new__(cls, (args, kwargs))
2037
2038 return tuple.__new__(cls, (name, args, kwargs))
2039
2040
2041 def __init__(self, value=(), name=None, parent=None, two=False,
2042 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002043 self._mock_name = name
2044 self._mock_parent = parent
2045 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002046
2047
2048 def __eq__(self, other):
2049 if other is ANY:
2050 return True
2051 try:
2052 len_other = len(other)
2053 except TypeError:
2054 return False
2055
2056 self_name = ''
2057 if len(self) == 2:
2058 self_args, self_kwargs = self
2059 else:
2060 self_name, self_args, self_kwargs = self
2061
Andrew Dunaie63e6172018-12-04 11:08:45 +02002062 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2063 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002064 return False
2065
Michael Foord345266a2012-03-14 12:24:34 -07002066 other_name = ''
2067 if len_other == 0:
2068 other_args, other_kwargs = (), {}
2069 elif len_other == 3:
2070 other_name, other_args, other_kwargs = other
2071 elif len_other == 1:
2072 value, = other
2073 if isinstance(value, tuple):
2074 other_args = value
2075 other_kwargs = {}
2076 elif isinstance(value, str):
2077 other_name = value
2078 other_args, other_kwargs = (), {}
2079 else:
2080 other_args = ()
2081 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002082 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002083 # could be (name, args) or (name, kwargs) or (args, kwargs)
2084 first, second = other
2085 if isinstance(first, str):
2086 other_name = first
2087 if isinstance(second, tuple):
2088 other_args, other_kwargs = second, {}
2089 else:
2090 other_args, other_kwargs = (), second
2091 else:
2092 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002093 else:
2094 return False
Michael Foord345266a2012-03-14 12:24:34 -07002095
2096 if self_name and other_name != self_name:
2097 return False
2098
2099 # this order is important for ANY to work!
2100 return (other_args, other_kwargs) == (self_args, self_kwargs)
2101
2102
Berker Peksagce913872016-03-28 00:30:02 +03002103 __ne__ = object.__ne__
2104
2105
Michael Foord345266a2012-03-14 12:24:34 -07002106 def __call__(self, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002107 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002108 return _Call(('', args, kwargs), name='()')
2109
Andrew Dunaie63e6172018-12-04 11:08:45 +02002110 name = self._mock_name + '()'
2111 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002112
2113
2114 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002115 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002116 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002117 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002118 return _Call(name=name, parent=self, from_kall=False)
2119
2120
Kushal Dasa37b9582014-09-16 18:33:37 +05302121 def count(self, *args, **kwargs):
2122 return self.__getattr__('count')(*args, **kwargs)
2123
2124 def index(self, *args, **kwargs):
2125 return self.__getattr__('index')(*args, **kwargs)
2126
Michael Foord345266a2012-03-14 12:24:34 -07002127 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002128 if not self._mock_from_kall:
2129 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002130 if name.startswith('()'):
2131 name = 'call%s' % name
2132 return name
2133
2134 if len(self) == 2:
2135 name = 'call'
2136 args, kwargs = self
2137 else:
2138 name, args, kwargs = self
2139 if not name:
2140 name = 'call'
2141 elif not name.startswith('()'):
2142 name = 'call.%s' % name
2143 else:
2144 name = 'call%s' % name
2145 return _format_call_signature(name, args, kwargs)
2146
2147
2148 def call_list(self):
2149 """For a call object that represents multiple calls, `call_list`
2150 returns a list of all the intermediate calls as well as the
2151 final call."""
2152 vals = []
2153 thing = self
2154 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002155 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002156 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002157 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002158 return _CallList(reversed(vals))
2159
2160
2161call = _Call(from_kall=False)
2162
2163
2164
2165def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2166 _name=None, **kwargs):
2167 """Create a mock object using another object as a spec. Attributes on the
2168 mock will use the corresponding attribute on the `spec` object as their
2169 spec.
2170
2171 Functions or methods being mocked will have their arguments checked
2172 to check that they are called with the correct signature.
2173
2174 If `spec_set` is True then attempting to set attributes that don't exist
2175 on the spec object will raise an `AttributeError`.
2176
2177 If a class is used as a spec then the return value of the mock (the
2178 instance of the class) will have the same spec. You can use a class as the
2179 spec for an instance object by passing `instance=True`. The returned mock
2180 will only be callable if instances of the mock are callable.
2181
2182 `create_autospec` also takes arbitrary keyword arguments that are passed to
2183 the constructor of the created mock."""
2184 if _is_list(spec):
2185 # can't pass a list instance to the mock constructor as it will be
2186 # interpreted as a list of strings
2187 spec = type(spec)
2188
2189 is_type = isinstance(spec, type)
2190
2191 _kwargs = {'spec': spec}
2192 if spec_set:
2193 _kwargs = {'spec_set': spec}
2194 elif spec is None:
2195 # None we mock with a normal mock without a spec
2196 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002197 if _kwargs and instance:
2198 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002199
2200 _kwargs.update(kwargs)
2201
2202 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002203 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002204 # descriptors don't have a spec
2205 # because we don't know what type they return
2206 _kwargs = {}
2207 elif not _callable(spec):
2208 Klass = NonCallableMagicMock
2209 elif is_type and instance and not _instance_callable(spec):
2210 Klass = NonCallableMagicMock
2211
Kushal Das484f8a82014-04-16 01:05:50 +05302212 _name = _kwargs.pop('name', _name)
2213
Michael Foord345266a2012-03-14 12:24:34 -07002214 _new_name = _name
2215 if _parent is None:
2216 # for a top level object no _new_name should be set
2217 _new_name = ''
2218
2219 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2220 name=_name, **_kwargs)
2221
2222 if isinstance(spec, FunctionTypes):
2223 # should only happen at the top level because we don't
2224 # recurse for functions
2225 mock = _set_signature(mock, spec)
2226 else:
2227 _check_signature(spec, mock, is_type, instance)
2228
2229 if _parent is not None and not instance:
2230 _parent._mock_children[_name] = mock
2231
2232 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002233 mock.return_value = create_autospec(spec, spec_set, instance=True,
2234 _name='()', _parent=mock)
2235
2236 for entry in dir(spec):
2237 if _is_magic(entry):
2238 # MagicMock already does the useful magic methods for us
2239 continue
2240
Michael Foord345266a2012-03-14 12:24:34 -07002241 # XXXX do we need a better way of getting attributes without
2242 # triggering code execution (?) Probably not - we need the actual
2243 # object to mock it so we would rather trigger a property than mock
2244 # the property descriptor. Likewise we want to mock out dynamically
2245 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002246 # XXXX what about attributes that raise exceptions other than
2247 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002248 # we could be resilient against it, or catch and propagate the
2249 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002250 try:
2251 original = getattr(spec, entry)
2252 except AttributeError:
2253 continue
Michael Foord345266a2012-03-14 12:24:34 -07002254
2255 kwargs = {'spec': original}
2256 if spec_set:
2257 kwargs = {'spec_set': original}
2258
2259 if not isinstance(original, FunctionTypes):
2260 new = _SpecState(original, spec_set, mock, entry, instance)
2261 mock._mock_children[entry] = new
2262 else:
2263 parent = mock
2264 if isinstance(spec, FunctionTypes):
2265 parent = mock.mock
2266
Michael Foord345266a2012-03-14 12:24:34 -07002267 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002268 kwargs['_eat_self'] = skipfirst
2269 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2270 _new_parent=parent,
2271 **kwargs)
2272 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002273 _check_signature(original, new, skipfirst=skipfirst)
2274
2275 # so functions created with _set_signature become instance attributes,
2276 # *plus* their underlying mock exists in _mock_children of the parent
2277 # mock. Adding to _mock_children may be unnecessary where we are also
2278 # setting as an instance attribute?
2279 if isinstance(new, FunctionTypes):
2280 setattr(mock, entry, new)
2281
2282 return mock
2283
2284
2285def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002286 """
2287 Return whether we should skip the first argument on spec's `entry`
2288 attribute.
2289 """
Michael Foord345266a2012-03-14 12:24:34 -07002290 if not isinstance(spec, type):
2291 if entry in getattr(spec, '__dict__', {}):
2292 # instance attribute - shouldn't skip
2293 return False
Michael Foord345266a2012-03-14 12:24:34 -07002294 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002295
2296 for klass in spec.__mro__:
2297 result = klass.__dict__.get(entry, DEFAULT)
2298 if result is DEFAULT:
2299 continue
2300 if isinstance(result, (staticmethod, classmethod)):
2301 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002302 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2303 # Normal method => skip if looked up on type
2304 # (if looked up on instance, self is already skipped)
2305 return is_type
2306 else:
2307 return False
Michael Foord345266a2012-03-14 12:24:34 -07002308
2309 # shouldn't get here unless function is a dynamically provided attribute
2310 # XXXX untested behaviour
2311 return is_type
2312
2313
2314def _get_class(obj):
2315 try:
2316 return obj.__class__
2317 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002318 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002319 return type(obj)
2320
2321
2322class _SpecState(object):
2323
2324 def __init__(self, spec, spec_set=False, parent=None,
2325 name=None, ids=None, instance=False):
2326 self.spec = spec
2327 self.ids = ids
2328 self.spec_set = spec_set
2329 self.parent = parent
2330 self.instance = instance
2331 self.name = name
2332
2333
2334FunctionTypes = (
2335 # python function
2336 type(create_autospec),
2337 # instance method
2338 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002339)
2340
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002341MethodWrapperTypes = (
2342 type(ANY.__eq__.__get__),
2343)
2344
Michael Foord345266a2012-03-14 12:24:34 -07002345
Michael Foorda74561a2012-03-25 19:03:13 +01002346file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002347
Michael Foord04cbe0c2013-03-19 17:22:51 -07002348def _iterate_read_data(read_data):
2349 # Helper for mock_open:
2350 # Retrieve lines from read_data via a generator so that separate calls to
2351 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002352 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2353 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002354
Berker Peksag86b34da2015-08-06 13:15:51 +03002355 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002356 # If the last line ended in a newline, the list comprehension will have an
2357 # extra entry that's just a newline. Remove this.
2358 data_as_list = data_as_list[:-1]
2359 else:
2360 # If there wasn't an extra newline by itself, then the file being
2361 # emulated doesn't have a newline to end the last line remove the
2362 # newline that our naive format() added
2363 data_as_list[-1] = data_as_list[-1][:-1]
2364
2365 for line in data_as_list:
2366 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002367
Robert Collins5329aaa2015-07-17 20:08:45 +12002368
Michael Foord0dccf652012-03-25 19:11:50 +01002369def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002370 """
2371 A helper function to create a mock to replace the use of `open`. It works
2372 for `open` called directly or used as a context manager.
2373
2374 The `mock` argument is the mock object to configure. If `None` (the
2375 default) then a `MagicMock` will be created for you, with the API limited
2376 to methods or attributes available on standard file handles.
2377
Xtreak71f82a22018-12-20 21:30:21 +05302378 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002379 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002380 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002381 def _readlines_side_effect(*args, **kwargs):
2382 if handle.readlines.return_value is not None:
2383 return handle.readlines.return_value
2384 return list(_state[0])
2385
2386 def _read_side_effect(*args, **kwargs):
2387 if handle.read.return_value is not None:
2388 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002389 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002390
2391 def _readline_side_effect():
Tony Flury20870232018-09-12 23:21:16 +01002392 yield from _iter_side_effect()
2393 while True:
2394 yield type(read_data)()
2395
2396 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002397 if handle.readline.return_value is not None:
2398 while True:
2399 yield handle.readline.return_value
2400 for line in _state[0]:
2401 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002402
Michael Foorda74561a2012-03-25 19:03:13 +01002403 global file_spec
2404 if file_spec is None:
2405 import _io
2406 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2407
Michael Foord345266a2012-03-14 12:24:34 -07002408 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002409 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002410
Robert Collinsca647ef2015-07-24 03:48:20 +12002411 handle = MagicMock(spec=file_spec)
2412 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002413
Robert Collinsca647ef2015-07-24 03:48:20 +12002414 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002415
Robert Collinsca647ef2015-07-24 03:48:20 +12002416 handle.write.return_value = None
2417 handle.read.return_value = None
2418 handle.readline.return_value = None
2419 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002420
Robert Collinsca647ef2015-07-24 03:48:20 +12002421 handle.read.side_effect = _read_side_effect
2422 _state[1] = _readline_side_effect()
2423 handle.readline.side_effect = _state[1]
2424 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002425 handle.__iter__.side_effect = _iter_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002426
Robert Collinsca647ef2015-07-24 03:48:20 +12002427 def reset_data(*args, **kwargs):
2428 _state[0] = _iterate_read_data(read_data)
2429 if handle.readline.side_effect == _state[1]:
2430 # Only reset the side effect if the user hasn't overridden it.
2431 _state[1] = _readline_side_effect()
2432 handle.readline.side_effect = _state[1]
2433 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002434
Robert Collinsca647ef2015-07-24 03:48:20 +12002435 mock.side_effect = reset_data
2436 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002437 return mock
2438
2439
2440class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002441 """
2442 A mock intended to be used as a property, or other descriptor, on a class.
2443 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2444 a return value when it is fetched.
2445
2446 Fetching a `PropertyMock` instance from an object calls the mock, with
2447 no args. Setting it calls the mock with the value being set.
2448 """
Michael Foordc2870622012-04-13 16:57:22 +01002449 def _get_child_mock(self, **kwargs):
2450 return MagicMock(**kwargs)
2451
Michael Foord345266a2012-03-14 12:24:34 -07002452 def __get__(self, obj, obj_type):
2453 return self()
2454 def __set__(self, obj, val):
2455 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002456
2457
2458def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002459 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002460
2461 Given an input Mock, seals it to ensure no further mocks will be generated
2462 when accessing an attribute that was not already defined.
2463
Mario Corchero96200eb2018-10-19 22:57:37 +01002464 The operation recursively seals the mock passed in, meaning that
2465 the mock itself, any mocks generated by accessing one of its attributes,
2466 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002467 """
2468 mock._mock_sealed = True
2469 for attr in dir(mock):
2470 try:
2471 m = getattr(mock, attr)
2472 except AttributeError:
2473 continue
2474 if not isinstance(m, NonCallableMock):
2475 continue
2476 if m._mock_new_parent is mock:
2477 seal(m)