blob: 38189c9aec2ea332e4564f6117c3d4ea3ca9859a [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
732 if name in self.__dict__:
733 object.__delattr__(self, name)
734
735 obj = self._mock_children.get(name, _missing)
736 if obj is _deleted:
737 raise AttributeError(name)
738 if obj is not _missing:
739 del self._mock_children[name]
740 self._mock_children[name] = _deleted
741
742
Michael Foord345266a2012-03-14 12:24:34 -0700743 def _format_mock_call_signature(self, args, kwargs):
744 name = self._mock_name or 'mock'
745 return _format_call_signature(name, args, kwargs)
746
747
748 def _format_mock_failure_message(self, args, kwargs):
749 message = 'Expected call: %s\nActual call: %s'
750 expected_string = self._format_mock_call_signature(args, kwargs)
751 call_args = self.call_args
752 if len(call_args) == 3:
753 call_args = call_args[1:]
754 actual_string = self._format_mock_call_signature(*call_args)
755 return message % (expected_string, actual_string)
756
757
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100758 def _call_matcher(self, _call):
759 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000760 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100761 comparison key suitable for matching with other calls.
762 This is a best effort method which relies on the spec's signature,
763 if available, or falls back on the arguments themselves.
764 """
765 sig = self._spec_signature
766 if sig is not None:
767 if len(_call) == 2:
768 name = ''
769 args, kwargs = _call
770 else:
771 name, args, kwargs = _call
772 try:
773 return name, sig.bind(*args, **kwargs)
774 except TypeError as e:
775 return e.with_traceback(None)
776 else:
777 return _call
778
Kushal Das68290f42014-04-17 01:54:07 +0530779 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530780 """assert that the mock was never called.
781 """
782 self = _mock_self
783 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100784 msg = ("Expected '%s' to not have been called. Called %s times.%s"
785 % (self._mock_name or 'mock',
786 self.call_count,
787 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530788 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100789
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100790 def assert_called(_mock_self):
791 """assert that the mock was called at least once
792 """
793 self = _mock_self
794 if self.call_count == 0:
795 msg = ("Expected '%s' to have been called." %
796 self._mock_name or 'mock')
797 raise AssertionError(msg)
798
799 def assert_called_once(_mock_self):
800 """assert that the mock was called only once.
801 """
802 self = _mock_self
803 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100804 msg = ("Expected '%s' to have been called once. Called %s times.%s"
805 % (self._mock_name or 'mock',
806 self.call_count,
807 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100808 raise AssertionError(msg)
809
Michael Foord345266a2012-03-14 12:24:34 -0700810 def assert_called_with(_mock_self, *args, **kwargs):
811 """assert that the mock was called with the specified arguments.
812
813 Raises an AssertionError if the args and keyword args passed in are
814 different to the last call to the mock."""
815 self = _mock_self
816 if self.call_args is None:
817 expected = self._format_mock_call_signature(args, kwargs)
818 raise AssertionError('Expected call: %s\nNot called' % (expected,))
819
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100820 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700821 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100822 return msg
823 expected = self._call_matcher((args, kwargs))
824 actual = self._call_matcher(self.call_args)
825 if expected != actual:
826 cause = expected if isinstance(expected, Exception) else None
827 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700828
829
830 def assert_called_once_with(_mock_self, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100831 """assert that the mock was called exactly once and that that call was
832 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700833 self = _mock_self
834 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100835 msg = ("Expected '%s' to be called once. Called %s times.%s"
836 % (self._mock_name or 'mock',
837 self.call_count,
838 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700839 raise AssertionError(msg)
840 return self.assert_called_with(*args, **kwargs)
841
842
843 def assert_has_calls(self, calls, any_order=False):
844 """assert the mock has been called with the specified calls.
845 The `mock_calls` list is checked for the calls.
846
847 If `any_order` is False (the default) then the calls must be
848 sequential. There can be extra calls before or after the
849 specified calls.
850
851 If `any_order` is True then the calls can be in any order, but
852 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100853 expected = [self._call_matcher(c) for c in calls]
854 cause = expected if isinstance(expected, Exception) else None
855 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700856 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100857 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700858 raise AssertionError(
Petter Strandmark47d94242018-10-28 21:37:10 +0100859 'Calls not found.\nExpected: %r%s'
860 % (_CallList(calls), self._calls_repr(prefix="Actual"))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100861 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700862 return
863
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100864 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700865
866 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100867 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700868 try:
869 all_calls.remove(kall)
870 except ValueError:
871 not_found.append(kall)
872 if not_found:
873 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400874 '%r does not contain all of %r in its call list, '
875 'found %r instead' % (self._mock_name or 'mock',
876 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100877 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700878
879
880 def assert_any_call(self, *args, **kwargs):
881 """assert the mock has been called with the specified arguments.
882
883 The assert passes if the mock has *ever* been called, unlike
884 `assert_called_with` and `assert_called_once_with` that only pass if
885 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100886 expected = self._call_matcher((args, kwargs))
887 actual = [self._call_matcher(c) for c in self.call_args_list]
888 if expected not in actual:
889 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700890 expected_string = self._format_mock_call_signature(args, kwargs)
891 raise AssertionError(
892 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100893 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700894
895
896 def _get_child_mock(self, **kw):
897 """Create the child mocks for attributes and return value.
898 By default child mocks will be the same type as the parent.
899 Subclasses of Mock may want to override this to customize the way
900 child mocks are made.
901
902 For non-callable mocks the callable variant will be used (rather than
903 any custom subclass)."""
904 _type = type(self)
905 if not issubclass(_type, CallableMixin):
906 if issubclass(_type, NonCallableMagicMock):
907 klass = MagicMock
908 elif issubclass(_type, NonCallableMock) :
909 klass = Mock
910 else:
911 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +0100912
913 if self._mock_sealed:
914 attribute = "." + kw["name"] if "name" in kw else "()"
915 mock_name = self._extract_mock_name() + attribute
916 raise AttributeError(mock_name)
917
Michael Foord345266a2012-03-14 12:24:34 -0700918 return klass(**kw)
919
920
Petter Strandmark47d94242018-10-28 21:37:10 +0100921 def _calls_repr(self, prefix="Calls"):
922 """Renders self.mock_calls as a string.
923
924 Example: "\nCalls: [call(1), call(2)]."
925
926 If self.mock_calls is empty, an empty string is returned. The
927 output will be truncated if very long.
928 """
929 if not self.mock_calls:
930 return ""
931 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
932
933
Michael Foord345266a2012-03-14 12:24:34 -0700934
935def _try_iter(obj):
936 if obj is None:
937 return obj
938 if _is_exception(obj):
939 return obj
940 if _callable(obj):
941 return obj
942 try:
943 return iter(obj)
944 except TypeError:
945 # XXXX backwards compatibility
946 # but this will blow up on first call - so maybe we should fail early?
947 return obj
948
949
950
951class CallableMixin(Base):
952
953 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
954 wraps=None, name=None, spec_set=None, parent=None,
955 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
956 self.__dict__['_mock_return_value'] = return_value
957
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000958 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700959 spec, wraps, name, spec_set, parent,
960 _spec_state, _new_name, _new_parent, **kwargs
961 )
962
963 self.side_effect = side_effect
964
965
966 def _mock_check_sig(self, *args, **kwargs):
967 # stub method that can be replaced with one with a specific signature
968 pass
969
970
971 def __call__(_mock_self, *args, **kwargs):
972 # can't use self in-case a function / method we are mocking uses self
973 # in the signature
974 _mock_self._mock_check_sig(*args, **kwargs)
975 return _mock_self._mock_call(*args, **kwargs)
976
977
978 def _mock_call(_mock_self, *args, **kwargs):
979 self = _mock_self
980 self.called = True
981 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100982
Chris Withers8ca0fa92018-12-03 21:31:37 +0000983 # handle call_args
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100984 _call = _Call((args, kwargs), two=True)
985 self.call_args = _call
986 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700987
988 seen = set()
Chris Withers8ca0fa92018-12-03 21:31:37 +0000989
990 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700991 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +0000992 method_call_name = self._mock_name
993
994 # initial stuff for mock_calls:
995 mock_call_name = self._mock_new_name
996 is_a_call = mock_call_name == '()'
997 self.mock_calls.append(_Call(('', args, kwargs)))
998
999 # follow up the chain of mocks:
1000 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001001 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001002
Chris Withers8ca0fa92018-12-03 21:31:37 +00001003 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001004 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001005 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001006 do_method_calls = _new_parent._mock_parent is not None
1007 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001008 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001009
Chris Withers8ca0fa92018-12-03 21:31:37 +00001010 # handle mock_calls:
1011 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001012 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001013
1014 if _new_parent._mock_new_name:
1015 if is_a_call:
1016 dot = ''
1017 else:
1018 dot = '.'
1019 is_a_call = _new_parent._mock_new_name == '()'
1020 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1021
1022 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001023 _new_parent = _new_parent._mock_new_parent
1024
Chris Withers8ca0fa92018-12-03 21:31:37 +00001025 # check we're not in an infinite loop:
1026 # ( use ids here so as not to call __hash__ on the mocks)
Michael Foord345266a2012-03-14 12:24:34 -07001027 _new_parent_id = id(_new_parent)
1028 if _new_parent_id in seen:
1029 break
1030 seen.add(_new_parent_id)
1031
Michael Foord345266a2012-03-14 12:24:34 -07001032 effect = self.side_effect
1033 if effect is not None:
1034 if _is_exception(effect):
1035 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001036 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001037 result = next(effect)
1038 if _is_exception(result):
1039 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001040 else:
1041 result = effect(*args, **kwargs)
1042
1043 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001044 return result
Michael Foord345266a2012-03-14 12:24:34 -07001045
Mario Corcherof05df0a2018-12-08 11:25:02 +00001046 if self._mock_return_value is not DEFAULT:
1047 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001048
Mario Corcherof05df0a2018-12-08 11:25:02 +00001049 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001050 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001051
1052 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001053
1054
1055
1056class Mock(CallableMixin, NonCallableMock):
1057 """
1058 Create a new `Mock` object. `Mock` takes several optional arguments
1059 that specify the behaviour of the Mock object:
1060
1061 * `spec`: This can be either a list of strings or an existing object (a
1062 class or instance) that acts as the specification for the mock object. If
1063 you pass in an object then a list of strings is formed by calling dir on
1064 the object (excluding unsupported magic attributes and methods). Accessing
1065 any attribute not in this list will raise an `AttributeError`.
1066
1067 If `spec` is an object (rather than a list of strings) then
1068 `mock.__class__` returns the class of the spec object. This allows mocks
1069 to pass `isinstance` tests.
1070
1071 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1072 or get an attribute on the mock that isn't on the object passed as
1073 `spec_set` will raise an `AttributeError`.
1074
1075 * `side_effect`: A function to be called whenever the Mock is called. See
1076 the `side_effect` attribute. Useful for raising exceptions or
1077 dynamically changing return values. The function is called with the same
1078 arguments as the mock, and unless it returns `DEFAULT`, the return
1079 value of this function is used as the return value.
1080
Michael Foord2cd48732012-04-21 15:52:11 +01001081 If `side_effect` is an iterable then each call to the mock will return
1082 the next value from the iterable. If any of the members of the iterable
1083 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001084
Michael Foord345266a2012-03-14 12:24:34 -07001085 * `return_value`: The value returned when the mock is called. By default
1086 this is a new Mock (created on first access). See the
1087 `return_value` attribute.
1088
Michael Foord0682a0c2012-04-13 20:51:20 +01001089 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1090 calling the Mock will pass the call through to the wrapped object
1091 (returning the real result). Attribute access on the mock will return a
1092 Mock object that wraps the corresponding attribute of the wrapped object
1093 (so attempting to access an attribute that doesn't exist will raise an
1094 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001095
1096 If the mock has an explicit `return_value` set then calls are not passed
1097 to the wrapped object and the `return_value` is returned instead.
1098
1099 * `name`: If the mock has a name then it will be used in the repr of the
1100 mock. This can be useful for debugging. The name is propagated to child
1101 mocks.
1102
1103 Mocks can also be called with arbitrary keyword arguments. These will be
1104 used to set attributes on the mock after it is created.
1105 """
1106
1107
1108
1109def _dot_lookup(thing, comp, import_path):
1110 try:
1111 return getattr(thing, comp)
1112 except AttributeError:
1113 __import__(import_path)
1114 return getattr(thing, comp)
1115
1116
1117def _importer(target):
1118 components = target.split('.')
1119 import_path = components.pop(0)
1120 thing = __import__(import_path)
1121
1122 for comp in components:
1123 import_path += ".%s" % comp
1124 thing = _dot_lookup(thing, comp, import_path)
1125 return thing
1126
1127
1128def _is_started(patcher):
1129 # XXXX horrible
1130 return hasattr(patcher, 'is_local')
1131
1132
1133class _patch(object):
1134
1135 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001136 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001137
1138 def __init__(
1139 self, getter, attribute, new, spec, create,
1140 spec_set, autospec, new_callable, kwargs
1141 ):
1142 if new_callable is not None:
1143 if new is not DEFAULT:
1144 raise ValueError(
1145 "Cannot use 'new' and 'new_callable' together"
1146 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001147 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001148 raise ValueError(
1149 "Cannot use 'autospec' and 'new_callable' together"
1150 )
1151
1152 self.getter = getter
1153 self.attribute = attribute
1154 self.new = new
1155 self.new_callable = new_callable
1156 self.spec = spec
1157 self.create = create
1158 self.has_local = False
1159 self.spec_set = spec_set
1160 self.autospec = autospec
1161 self.kwargs = kwargs
1162 self.additional_patchers = []
1163
1164
1165 def copy(self):
1166 patcher = _patch(
1167 self.getter, self.attribute, self.new, self.spec,
1168 self.create, self.spec_set,
1169 self.autospec, self.new_callable, self.kwargs
1170 )
1171 patcher.attribute_name = self.attribute_name
1172 patcher.additional_patchers = [
1173 p.copy() for p in self.additional_patchers
1174 ]
1175 return patcher
1176
1177
1178 def __call__(self, func):
1179 if isinstance(func, type):
1180 return self.decorate_class(func)
1181 return self.decorate_callable(func)
1182
1183
1184 def decorate_class(self, klass):
1185 for attr in dir(klass):
1186 if not attr.startswith(patch.TEST_PREFIX):
1187 continue
1188
1189 attr_value = getattr(klass, attr)
1190 if not hasattr(attr_value, "__call__"):
1191 continue
1192
1193 patcher = self.copy()
1194 setattr(klass, attr, patcher(attr_value))
1195 return klass
1196
1197
1198 def decorate_callable(self, func):
1199 if hasattr(func, 'patchings'):
1200 func.patchings.append(self)
1201 return func
1202
1203 @wraps(func)
1204 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001205 extra_args = []
1206 entered_patchers = []
1207
Michael Foord50a8c0e2012-03-25 18:57:58 +01001208 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001209 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001210 for patching in patched.patchings:
1211 arg = patching.__enter__()
1212 entered_patchers.append(patching)
1213 if patching.attribute_name is not None:
1214 keywargs.update(arg)
1215 elif patching.new is DEFAULT:
1216 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001217
Michael Foordd7c65e22012-03-14 14:56:54 -07001218 args += tuple(extra_args)
1219 return func(*args, **keywargs)
1220 except:
1221 if (patching not in entered_patchers and
1222 _is_started(patching)):
1223 # the patcher may have been started, but an exception
1224 # raised whilst entering one of its additional_patchers
1225 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001226 # Pass the exception to __exit__
1227 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001228 # re-raise the exception
1229 raise
Michael Foord345266a2012-03-14 12:24:34 -07001230 finally:
1231 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001232 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001233
1234 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001235 return patched
1236
1237
1238 def get_original(self):
1239 target = self.getter()
1240 name = self.attribute
1241
1242 original = DEFAULT
1243 local = False
1244
1245 try:
1246 original = target.__dict__[name]
1247 except (AttributeError, KeyError):
1248 original = getattr(target, name, DEFAULT)
1249 else:
1250 local = True
1251
Michael Foordfddcfa22014-04-14 16:25:20 -04001252 if name in _builtins and isinstance(target, ModuleType):
1253 self.create = True
1254
Michael Foord345266a2012-03-14 12:24:34 -07001255 if not self.create and original is DEFAULT:
1256 raise AttributeError(
1257 "%s does not have the attribute %r" % (target, name)
1258 )
1259 return original, local
1260
1261
1262 def __enter__(self):
1263 """Perform the patch."""
1264 new, spec, spec_set = self.new, self.spec, self.spec_set
1265 autospec, kwargs = self.autospec, self.kwargs
1266 new_callable = self.new_callable
1267 self.target = self.getter()
1268
Michael Foord50a8c0e2012-03-25 18:57:58 +01001269 # normalise False to None
1270 if spec is False:
1271 spec = None
1272 if spec_set is False:
1273 spec_set = None
1274 if autospec is False:
1275 autospec = None
1276
1277 if spec is not None and autospec is not None:
1278 raise TypeError("Can't specify spec and autospec")
1279 if ((spec is not None or autospec is not None) and
1280 spec_set not in (True, None)):
1281 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1282
Michael Foord345266a2012-03-14 12:24:34 -07001283 original, local = self.get_original()
1284
Michael Foord50a8c0e2012-03-25 18:57:58 +01001285 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001286 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001287 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001288 # set spec to the object we are replacing
1289 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001290 if spec_set is True:
1291 spec_set = original
1292 spec = None
1293 elif spec is not None:
1294 if spec_set is True:
1295 spec_set = spec
1296 spec = None
1297 elif spec_set is True:
1298 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001299
Michael Foord50a8c0e2012-03-25 18:57:58 +01001300 if spec is not None or spec_set is not None:
1301 if original is DEFAULT:
1302 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001303 if isinstance(original, type):
1304 # If we're patching out a class and there is a spec
1305 inherit = True
1306
1307 Klass = MagicMock
1308 _kwargs = {}
1309 if new_callable is not None:
1310 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001311 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001312 this_spec = spec
1313 if spec_set is not None:
1314 this_spec = spec_set
1315 if _is_list(this_spec):
1316 not_callable = '__call__' not in this_spec
1317 else:
1318 not_callable = not callable(this_spec)
1319 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001320 Klass = NonCallableMagicMock
1321
1322 if spec is not None:
1323 _kwargs['spec'] = spec
1324 if spec_set is not None:
1325 _kwargs['spec_set'] = spec_set
1326
1327 # add a name to mocks
1328 if (isinstance(Klass, type) and
1329 issubclass(Klass, NonCallableMock) and self.attribute):
1330 _kwargs['name'] = self.attribute
1331
1332 _kwargs.update(kwargs)
1333 new = Klass(**_kwargs)
1334
1335 if inherit and _is_instance_mock(new):
1336 # we can only tell if the instance should be callable if the
1337 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001338 this_spec = spec
1339 if spec_set is not None:
1340 this_spec = spec_set
1341 if (not _is_list(this_spec) and not
1342 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001343 Klass = NonCallableMagicMock
1344
1345 _kwargs.pop('name')
1346 new.return_value = Klass(_new_parent=new, _new_name='()',
1347 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001348 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001349 # spec is ignored, new *must* be default, spec_set is treated
1350 # as a boolean. Should we check spec is not None and that spec_set
1351 # is a bool?
1352 if new is not DEFAULT:
1353 raise TypeError(
1354 "autospec creates the mock for you. Can't specify "
1355 "autospec and new."
1356 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001357 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001358 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001359 spec_set = bool(spec_set)
1360 if autospec is True:
1361 autospec = original
1362
1363 new = create_autospec(autospec, spec_set=spec_set,
1364 _name=self.attribute, **kwargs)
1365 elif kwargs:
1366 # can't set keyword args when we aren't creating the mock
1367 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1368 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1369
1370 new_attr = new
1371
1372 self.temp_original = original
1373 self.is_local = local
1374 setattr(self.target, self.attribute, new_attr)
1375 if self.attribute_name is not None:
1376 extra_args = {}
1377 if self.new is DEFAULT:
1378 extra_args[self.attribute_name] = new
1379 for patching in self.additional_patchers:
1380 arg = patching.__enter__()
1381 if patching.new is DEFAULT:
1382 extra_args.update(arg)
1383 return extra_args
1384
1385 return new
1386
1387
Michael Foord50a8c0e2012-03-25 18:57:58 +01001388 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001389 """Undo the patch."""
1390 if not _is_started(self):
1391 raise RuntimeError('stop called on unstarted patcher')
1392
1393 if self.is_local and self.temp_original is not DEFAULT:
1394 setattr(self.target, self.attribute, self.temp_original)
1395 else:
1396 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001397 if not self.create and (not hasattr(self.target, self.attribute) or
1398 self.attribute in ('__doc__', '__module__',
1399 '__defaults__', '__annotations__',
1400 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001401 # needed for proxy objects like django settings
1402 setattr(self.target, self.attribute, self.temp_original)
1403
1404 del self.temp_original
1405 del self.is_local
1406 del self.target
1407 for patcher in reversed(self.additional_patchers):
1408 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001409 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001410
Michael Foordf7c41582012-06-10 20:36:32 +01001411
1412 def start(self):
1413 """Activate a patch, returning any created mock."""
1414 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001415 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001416 return result
1417
1418
1419 def stop(self):
1420 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001421 try:
1422 self._active_patches.remove(self)
1423 except ValueError:
1424 # If the patch hasn't been started this will fail
1425 pass
1426
Michael Foordf7c41582012-06-10 20:36:32 +01001427 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001428
1429
1430
1431def _get_target(target):
1432 try:
1433 target, attribute = target.rsplit('.', 1)
1434 except (TypeError, ValueError):
1435 raise TypeError("Need a valid target to patch. You supplied: %r" %
1436 (target,))
1437 getter = lambda: _importer(target)
1438 return getter, attribute
1439
1440
1441def _patch_object(
1442 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001443 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001444 new_callable=None, **kwargs
1445 ):
1446 """
Michael Foord345266a2012-03-14 12:24:34 -07001447 patch the named member (`attribute`) on an object (`target`) with a mock
1448 object.
1449
1450 `patch.object` can be used as a decorator, class decorator or a context
1451 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1452 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1453 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1454 the mock object it creates.
1455
1456 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1457 for choosing which methods to wrap.
1458 """
1459 getter = lambda: target
1460 return _patch(
1461 getter, attribute, new, spec, create,
1462 spec_set, autospec, new_callable, kwargs
1463 )
1464
1465
Michael Foord50a8c0e2012-03-25 18:57:58 +01001466def _patch_multiple(target, spec=None, create=False, spec_set=None,
1467 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001468 """Perform multiple patches in a single call. It takes the object to be
1469 patched (either as an object or a string to fetch the object by importing)
1470 and keyword arguments for the patches::
1471
1472 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1473 ...
1474
1475 Use `DEFAULT` as the value if you want `patch.multiple` to create
1476 mocks for you. In this case the created mocks are passed into a decorated
1477 function by keyword, and a dictionary is returned when `patch.multiple` is
1478 used as a context manager.
1479
1480 `patch.multiple` can be used as a decorator, class decorator or a context
1481 manager. The arguments `spec`, `spec_set`, `create`,
1482 `autospec` and `new_callable` have the same meaning as for `patch`. These
1483 arguments will be applied to *all* patches done by `patch.multiple`.
1484
1485 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1486 for choosing which methods to wrap.
1487 """
1488 if type(target) is str:
1489 getter = lambda: _importer(target)
1490 else:
1491 getter = lambda: target
1492
1493 if not kwargs:
1494 raise ValueError(
1495 'Must supply at least one keyword argument with patch.multiple'
1496 )
1497 # need to wrap in a list for python 3, where items is a view
1498 items = list(kwargs.items())
1499 attribute, new = items[0]
1500 patcher = _patch(
1501 getter, attribute, new, spec, create, spec_set,
1502 autospec, new_callable, {}
1503 )
1504 patcher.attribute_name = attribute
1505 for attribute, new in items[1:]:
1506 this_patcher = _patch(
1507 getter, attribute, new, spec, create, spec_set,
1508 autospec, new_callable, {}
1509 )
1510 this_patcher.attribute_name = attribute
1511 patcher.additional_patchers.append(this_patcher)
1512 return patcher
1513
1514
1515def patch(
1516 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001517 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001518 ):
1519 """
1520 `patch` acts as a function decorator, class decorator or a context
1521 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001522 is patched with a `new` object. When the function/with statement exits
1523 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001524
Michael Foord54b3db82012-03-28 15:08:08 +01001525 If `new` is omitted, then the target is replaced with a
1526 `MagicMock`. If `patch` is used as a decorator and `new` is
1527 omitted, the created mock is passed in as an extra argument to the
1528 decorated function. If `patch` is used as a context manager the created
1529 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001530
Michael Foord54b3db82012-03-28 15:08:08 +01001531 `target` should be a string in the form `'package.module.ClassName'`. The
1532 `target` is imported and the specified object replaced with the `new`
1533 object, so the `target` must be importable from the environment you are
1534 calling `patch` from. The target is imported when the decorated function
1535 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001536
1537 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1538 if patch is creating one for you.
1539
1540 In addition you can pass `spec=True` or `spec_set=True`, which causes
1541 patch to pass in the object being mocked as the spec/spec_set object.
1542
1543 `new_callable` allows you to specify a different class, or callable object,
1544 that will be called to create the `new` object. By default `MagicMock` is
1545 used.
1546
1547 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001548 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001549 All attributes of the mock will also have the spec of the corresponding
1550 attribute of the object being replaced. Methods and functions being
1551 mocked will have their arguments checked and will raise a `TypeError` if
1552 they are called with the wrong signature. For mocks replacing a class,
1553 their return value (the 'instance') will have the same spec as the class.
1554
1555 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1556 arbitrary object as the spec instead of the one being replaced.
1557
1558 By default `patch` will fail to replace attributes that don't exist. If
1559 you pass in `create=True`, and the attribute doesn't exist, patch will
1560 create the attribute for you when the patched function is called, and
1561 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001562 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001563 default because it can be dangerous. With it switched on you can write
1564 passing tests against APIs that don't actually exist!
1565
1566 Patch can be used as a `TestCase` class decorator. It works by
1567 decorating each test method in the class. This reduces the boilerplate
1568 code when your test methods share a common patchings set. `patch` finds
1569 tests by looking for method names that start with `patch.TEST_PREFIX`.
1570 By default this is `test`, which matches the way `unittest` finds tests.
1571 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1572
1573 Patch can be used as a context manager, with the with statement. Here the
1574 patching applies to the indented block after the with statement. If you
1575 use "as" then the patched object will be bound to the name after the
1576 "as"; very useful if `patch` is creating a mock object for you.
1577
1578 `patch` takes arbitrary keyword arguments. These will be passed to
1579 the `Mock` (or `new_callable`) on construction.
1580
1581 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1582 available for alternate use-cases.
1583 """
1584 getter, attribute = _get_target(target)
1585 return _patch(
1586 getter, attribute, new, spec, create,
1587 spec_set, autospec, new_callable, kwargs
1588 )
1589
1590
1591class _patch_dict(object):
1592 """
1593 Patch a dictionary, or dictionary like object, and restore the dictionary
1594 to its original state after the test.
1595
1596 `in_dict` can be a dictionary or a mapping like container. If it is a
1597 mapping then it must at least support getting, setting and deleting items
1598 plus iterating over keys.
1599
1600 `in_dict` can also be a string specifying the name of the dictionary, which
1601 will then be fetched by importing it.
1602
1603 `values` can be a dictionary of values to set in the dictionary. `values`
1604 can also be an iterable of `(key, value)` pairs.
1605
1606 If `clear` is True then the dictionary will be cleared before the new
1607 values are set.
1608
1609 `patch.dict` can also be called with arbitrary keyword arguments to set
1610 values in the dictionary::
1611
1612 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1613 ...
1614
1615 `patch.dict` can be used as a context manager, decorator or class
1616 decorator. When used as a class decorator `patch.dict` honours
1617 `patch.TEST_PREFIX` for choosing which methods to wrap.
1618 """
1619
1620 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1621 if isinstance(in_dict, str):
1622 in_dict = _importer(in_dict)
1623 self.in_dict = in_dict
1624 # support any argument supported by dict(...) constructor
1625 self.values = dict(values)
1626 self.values.update(kwargs)
1627 self.clear = clear
1628 self._original = None
1629
1630
1631 def __call__(self, f):
1632 if isinstance(f, type):
1633 return self.decorate_class(f)
1634 @wraps(f)
1635 def _inner(*args, **kw):
1636 self._patch_dict()
1637 try:
1638 return f(*args, **kw)
1639 finally:
1640 self._unpatch_dict()
1641
1642 return _inner
1643
1644
1645 def decorate_class(self, klass):
1646 for attr in dir(klass):
1647 attr_value = getattr(klass, attr)
1648 if (attr.startswith(patch.TEST_PREFIX) and
1649 hasattr(attr_value, "__call__")):
1650 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1651 decorated = decorator(attr_value)
1652 setattr(klass, attr, decorated)
1653 return klass
1654
1655
1656 def __enter__(self):
1657 """Patch the dict."""
1658 self._patch_dict()
1659
1660
1661 def _patch_dict(self):
1662 values = self.values
1663 in_dict = self.in_dict
1664 clear = self.clear
1665
1666 try:
1667 original = in_dict.copy()
1668 except AttributeError:
1669 # dict like object with no copy method
1670 # must support iteration over keys
1671 original = {}
1672 for key in in_dict:
1673 original[key] = in_dict[key]
1674 self._original = original
1675
1676 if clear:
1677 _clear_dict(in_dict)
1678
1679 try:
1680 in_dict.update(values)
1681 except AttributeError:
1682 # dict like object with no update method
1683 for key in values:
1684 in_dict[key] = values[key]
1685
1686
1687 def _unpatch_dict(self):
1688 in_dict = self.in_dict
1689 original = self._original
1690
1691 _clear_dict(in_dict)
1692
1693 try:
1694 in_dict.update(original)
1695 except AttributeError:
1696 for key in original:
1697 in_dict[key] = original[key]
1698
1699
1700 def __exit__(self, *args):
1701 """Unpatch the dict."""
1702 self._unpatch_dict()
1703 return False
1704
1705 start = __enter__
1706 stop = __exit__
1707
1708
1709def _clear_dict(in_dict):
1710 try:
1711 in_dict.clear()
1712 except AttributeError:
1713 keys = list(in_dict)
1714 for key in keys:
1715 del in_dict[key]
1716
1717
Michael Foordf7c41582012-06-10 20:36:32 +01001718def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001719 """Stop all active patches. LIFO to unroll nested patches."""
1720 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001721 patch.stop()
1722
1723
Michael Foord345266a2012-03-14 12:24:34 -07001724patch.object = _patch_object
1725patch.dict = _patch_dict
1726patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001727patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001728patch.TEST_PREFIX = 'test'
1729
1730magic_methods = (
1731 "lt le gt ge eq ne "
1732 "getitem setitem delitem "
1733 "len contains iter "
1734 "hash str sizeof "
1735 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001736 # we added divmod and rdivmod here instead of numerics
1737 # because there is no idivmod
1738 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001739 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001740 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001741 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001742 "fspath "
Michael Foord345266a2012-03-14 12:24:34 -07001743)
1744
Michael Foordd2623d72014-04-14 11:23:48 -04001745numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001746 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001747)
Michael Foord345266a2012-03-14 12:24:34 -07001748inplace = ' '.join('i%s' % n for n in numerics.split())
1749right = ' '.join('r%s' % n for n in numerics.split())
1750
1751# not including __prepare__, __instancecheck__, __subclasscheck__
1752# (as they are metaclass methods)
1753# __del__ is not supported at all as it causes problems if it exists
1754
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001755_non_defaults = {
1756 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1757 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1758 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1759 '__repr__', '__dir__', '__subclasses__', '__format__',
Serhiy Storchaka5943ea72016-06-19 18:30:43 +03001760 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001761}
Michael Foord345266a2012-03-14 12:24:34 -07001762
1763
1764def _get_method(name, func):
1765 "Turns a callable object (like a mock) into a real function"
1766 def method(self, *args, **kw):
1767 return func(self, *args, **kw)
1768 method.__name__ = name
1769 return method
1770
1771
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001772_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001773 '__%s__' % method for method in
1774 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001775}
Michael Foord345266a2012-03-14 12:24:34 -07001776
1777_all_magics = _magics | _non_defaults
1778
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001779_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001780 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001781 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001782 '__instancecheck__', '__subclasscheck__',
1783 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001784}
Michael Foord345266a2012-03-14 12:24:34 -07001785
1786_calculate_return_value = {
1787 '__hash__': lambda self: object.__hash__(self),
1788 '__str__': lambda self: object.__str__(self),
1789 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001790 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001791}
1792
1793_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001794 '__lt__': NotImplemented,
1795 '__gt__': NotImplemented,
1796 '__le__': NotImplemented,
1797 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001798 '__int__': 1,
1799 '__contains__': False,
1800 '__len__': 0,
1801 '__exit__': False,
1802 '__complex__': 1j,
1803 '__float__': 1.0,
1804 '__bool__': True,
1805 '__index__': 1,
1806}
1807
1808
1809def _get_eq(self):
1810 def __eq__(other):
1811 ret_val = self.__eq__._mock_return_value
1812 if ret_val is not DEFAULT:
1813 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001814 if self is other:
1815 return True
1816 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001817 return __eq__
1818
1819def _get_ne(self):
1820 def __ne__(other):
1821 if self.__ne__._mock_return_value is not DEFAULT:
1822 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001823 if self is other:
1824 return False
1825 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001826 return __ne__
1827
1828def _get_iter(self):
1829 def __iter__():
1830 ret_val = self.__iter__._mock_return_value
1831 if ret_val is DEFAULT:
1832 return iter([])
1833 # if ret_val was already an iterator, then calling iter on it should
1834 # return the iterator unchanged
1835 return iter(ret_val)
1836 return __iter__
1837
1838_side_effect_methods = {
1839 '__eq__': _get_eq,
1840 '__ne__': _get_ne,
1841 '__iter__': _get_iter,
1842}
1843
1844
1845
1846def _set_return_value(mock, method, name):
1847 fixed = _return_values.get(name, DEFAULT)
1848 if fixed is not DEFAULT:
1849 method.return_value = fixed
1850 return
1851
1852 return_calulator = _calculate_return_value.get(name)
1853 if return_calulator is not None:
1854 try:
1855 return_value = return_calulator(mock)
1856 except AttributeError:
1857 # XXXX why do we return AttributeError here?
1858 # set it as a side_effect instead?
1859 return_value = AttributeError(name)
1860 method.return_value = return_value
1861 return
1862
1863 side_effector = _side_effect_methods.get(name)
1864 if side_effector is not None:
1865 method.side_effect = side_effector(mock)
1866
1867
1868
1869class MagicMixin(object):
1870 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001871 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001872 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001873 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001874
1875
1876 def _mock_set_magics(self):
1877 these_magics = _magics
1878
Łukasz Langaa468db92015-04-13 23:12:42 -07001879 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001880 these_magics = _magics.intersection(self._mock_methods)
1881
1882 remove_magics = set()
1883 remove_magics = _magics - these_magics
1884
1885 for entry in remove_magics:
1886 if entry in type(self).__dict__:
1887 # remove unneeded magic methods
1888 delattr(self, entry)
1889
1890 # don't overwrite existing attributes if called a second time
1891 these_magics = these_magics - set(type(self).__dict__)
1892
1893 _type = type(self)
1894 for entry in these_magics:
1895 setattr(_type, entry, MagicProxy(entry, self))
1896
1897
1898
1899class NonCallableMagicMock(MagicMixin, NonCallableMock):
1900 """A version of `MagicMock` that isn't callable."""
1901 def mock_add_spec(self, spec, spec_set=False):
1902 """Add a spec to a mock. `spec` can either be an object or a
1903 list of strings. Only attributes on the `spec` can be fetched as
1904 attributes from the mock.
1905
1906 If `spec_set` is True then only attributes on the spec can be set."""
1907 self._mock_add_spec(spec, spec_set)
1908 self._mock_set_magics()
1909
1910
1911
1912class MagicMock(MagicMixin, Mock):
1913 """
1914 MagicMock is a subclass of Mock with default implementations
1915 of most of the magic methods. You can use MagicMock without having to
1916 configure the magic methods yourself.
1917
1918 If you use the `spec` or `spec_set` arguments then *only* magic
1919 methods that exist in the spec will be created.
1920
1921 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1922 """
1923 def mock_add_spec(self, spec, spec_set=False):
1924 """Add a spec to a mock. `spec` can either be an object or a
1925 list of strings. Only attributes on the `spec` can be fetched as
1926 attributes from the mock.
1927
1928 If `spec_set` is True then only attributes on the spec can be set."""
1929 self._mock_add_spec(spec, spec_set)
1930 self._mock_set_magics()
1931
1932
1933
1934class MagicProxy(object):
1935 def __init__(self, name, parent):
1936 self.name = name
1937 self.parent = parent
1938
1939 def __call__(self, *args, **kwargs):
1940 m = self.create_mock()
1941 return m(*args, **kwargs)
1942
1943 def create_mock(self):
1944 entry = self.name
1945 parent = self.parent
1946 m = parent._get_child_mock(name=entry, _new_name=entry,
1947 _new_parent=parent)
1948 setattr(parent, entry, m)
1949 _set_return_value(parent, m, entry)
1950 return m
1951
1952 def __get__(self, obj, _type=None):
1953 return self.create_mock()
1954
1955
1956
1957class _ANY(object):
1958 "A helper object that compares equal to everything."
1959
1960 def __eq__(self, other):
1961 return True
1962
1963 def __ne__(self, other):
1964 return False
1965
1966 def __repr__(self):
1967 return '<ANY>'
1968
1969ANY = _ANY()
1970
1971
1972
1973def _format_call_signature(name, args, kwargs):
1974 message = '%s(%%s)' % name
1975 formatted_args = ''
1976 args_string = ', '.join([repr(arg) for arg in args])
1977 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301978 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001979 ])
1980 if args_string:
1981 formatted_args = args_string
1982 if kwargs_string:
1983 if formatted_args:
1984 formatted_args += ', '
1985 formatted_args += kwargs_string
1986
1987 return message % formatted_args
1988
1989
1990
1991class _Call(tuple):
1992 """
1993 A tuple for holding the results of a call to a mock, either in the form
1994 `(args, kwargs)` or `(name, args, kwargs)`.
1995
1996 If args or kwargs are empty then a call tuple will compare equal to
1997 a tuple without those values. This makes comparisons less verbose::
1998
1999 _Call(('name', (), {})) == ('name',)
2000 _Call(('name', (1,), {})) == ('name', (1,))
2001 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2002
2003 The `_Call` object provides a useful shortcut for comparing with call::
2004
2005 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2006 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2007
2008 If the _Call has no name then it will match any name.
2009 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002010 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002011 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002012 args = ()
2013 kwargs = {}
2014 _len = len(value)
2015 if _len == 3:
2016 name, args, kwargs = value
2017 elif _len == 2:
2018 first, second = value
2019 if isinstance(first, str):
2020 name = first
2021 if isinstance(second, tuple):
2022 args = second
2023 else:
2024 kwargs = second
2025 else:
2026 args, kwargs = first, second
2027 elif _len == 1:
2028 value, = value
2029 if isinstance(value, str):
2030 name = value
2031 elif isinstance(value, tuple):
2032 args = value
2033 else:
2034 kwargs = value
2035
2036 if two:
2037 return tuple.__new__(cls, (args, kwargs))
2038
2039 return tuple.__new__(cls, (name, args, kwargs))
2040
2041
2042 def __init__(self, value=(), name=None, parent=None, two=False,
2043 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002044 self._mock_name = name
2045 self._mock_parent = parent
2046 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002047
2048
2049 def __eq__(self, other):
2050 if other is ANY:
2051 return True
2052 try:
2053 len_other = len(other)
2054 except TypeError:
2055 return False
2056
2057 self_name = ''
2058 if len(self) == 2:
2059 self_args, self_kwargs = self
2060 else:
2061 self_name, self_args, self_kwargs = self
2062
Andrew Dunaie63e6172018-12-04 11:08:45 +02002063 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2064 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002065 return False
2066
Michael Foord345266a2012-03-14 12:24:34 -07002067 other_name = ''
2068 if len_other == 0:
2069 other_args, other_kwargs = (), {}
2070 elif len_other == 3:
2071 other_name, other_args, other_kwargs = other
2072 elif len_other == 1:
2073 value, = other
2074 if isinstance(value, tuple):
2075 other_args = value
2076 other_kwargs = {}
2077 elif isinstance(value, str):
2078 other_name = value
2079 other_args, other_kwargs = (), {}
2080 else:
2081 other_args = ()
2082 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002083 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002084 # could be (name, args) or (name, kwargs) or (args, kwargs)
2085 first, second = other
2086 if isinstance(first, str):
2087 other_name = first
2088 if isinstance(second, tuple):
2089 other_args, other_kwargs = second, {}
2090 else:
2091 other_args, other_kwargs = (), second
2092 else:
2093 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002094 else:
2095 return False
Michael Foord345266a2012-03-14 12:24:34 -07002096
2097 if self_name and other_name != self_name:
2098 return False
2099
2100 # this order is important for ANY to work!
2101 return (other_args, other_kwargs) == (self_args, self_kwargs)
2102
2103
Berker Peksagce913872016-03-28 00:30:02 +03002104 __ne__ = object.__ne__
2105
2106
Michael Foord345266a2012-03-14 12:24:34 -07002107 def __call__(self, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002108 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002109 return _Call(('', args, kwargs), name='()')
2110
Andrew Dunaie63e6172018-12-04 11:08:45 +02002111 name = self._mock_name + '()'
2112 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002113
2114
2115 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002116 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002117 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002118 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002119 return _Call(name=name, parent=self, from_kall=False)
2120
2121
Kushal Dasa37b9582014-09-16 18:33:37 +05302122 def count(self, *args, **kwargs):
2123 return self.__getattr__('count')(*args, **kwargs)
2124
2125 def index(self, *args, **kwargs):
2126 return self.__getattr__('index')(*args, **kwargs)
2127
Michael Foord345266a2012-03-14 12:24:34 -07002128 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002129 if not self._mock_from_kall:
2130 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002131 if name.startswith('()'):
2132 name = 'call%s' % name
2133 return name
2134
2135 if len(self) == 2:
2136 name = 'call'
2137 args, kwargs = self
2138 else:
2139 name, args, kwargs = self
2140 if not name:
2141 name = 'call'
2142 elif not name.startswith('()'):
2143 name = 'call.%s' % name
2144 else:
2145 name = 'call%s' % name
2146 return _format_call_signature(name, args, kwargs)
2147
2148
2149 def call_list(self):
2150 """For a call object that represents multiple calls, `call_list`
2151 returns a list of all the intermediate calls as well as the
2152 final call."""
2153 vals = []
2154 thing = self
2155 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002156 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002157 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002158 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002159 return _CallList(reversed(vals))
2160
2161
2162call = _Call(from_kall=False)
2163
2164
2165
2166def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2167 _name=None, **kwargs):
2168 """Create a mock object using another object as a spec. Attributes on the
2169 mock will use the corresponding attribute on the `spec` object as their
2170 spec.
2171
2172 Functions or methods being mocked will have their arguments checked
2173 to check that they are called with the correct signature.
2174
2175 If `spec_set` is True then attempting to set attributes that don't exist
2176 on the spec object will raise an `AttributeError`.
2177
2178 If a class is used as a spec then the return value of the mock (the
2179 instance of the class) will have the same spec. You can use a class as the
2180 spec for an instance object by passing `instance=True`. The returned mock
2181 will only be callable if instances of the mock are callable.
2182
2183 `create_autospec` also takes arbitrary keyword arguments that are passed to
2184 the constructor of the created mock."""
2185 if _is_list(spec):
2186 # can't pass a list instance to the mock constructor as it will be
2187 # interpreted as a list of strings
2188 spec = type(spec)
2189
2190 is_type = isinstance(spec, type)
2191
2192 _kwargs = {'spec': spec}
2193 if spec_set:
2194 _kwargs = {'spec_set': spec}
2195 elif spec is None:
2196 # None we mock with a normal mock without a spec
2197 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002198 if _kwargs and instance:
2199 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002200
2201 _kwargs.update(kwargs)
2202
2203 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002204 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002205 # descriptors don't have a spec
2206 # because we don't know what type they return
2207 _kwargs = {}
2208 elif not _callable(spec):
2209 Klass = NonCallableMagicMock
2210 elif is_type and instance and not _instance_callable(spec):
2211 Klass = NonCallableMagicMock
2212
Kushal Das484f8a82014-04-16 01:05:50 +05302213 _name = _kwargs.pop('name', _name)
2214
Michael Foord345266a2012-03-14 12:24:34 -07002215 _new_name = _name
2216 if _parent is None:
2217 # for a top level object no _new_name should be set
2218 _new_name = ''
2219
2220 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2221 name=_name, **_kwargs)
2222
2223 if isinstance(spec, FunctionTypes):
2224 # should only happen at the top level because we don't
2225 # recurse for functions
2226 mock = _set_signature(mock, spec)
2227 else:
2228 _check_signature(spec, mock, is_type, instance)
2229
2230 if _parent is not None and not instance:
2231 _parent._mock_children[_name] = mock
2232
2233 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002234 mock.return_value = create_autospec(spec, spec_set, instance=True,
2235 _name='()', _parent=mock)
2236
2237 for entry in dir(spec):
2238 if _is_magic(entry):
2239 # MagicMock already does the useful magic methods for us
2240 continue
2241
Michael Foord345266a2012-03-14 12:24:34 -07002242 # XXXX do we need a better way of getting attributes without
2243 # triggering code execution (?) Probably not - we need the actual
2244 # object to mock it so we would rather trigger a property than mock
2245 # the property descriptor. Likewise we want to mock out dynamically
2246 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002247 # XXXX what about attributes that raise exceptions other than
2248 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002249 # we could be resilient against it, or catch and propagate the
2250 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002251 try:
2252 original = getattr(spec, entry)
2253 except AttributeError:
2254 continue
Michael Foord345266a2012-03-14 12:24:34 -07002255
2256 kwargs = {'spec': original}
2257 if spec_set:
2258 kwargs = {'spec_set': original}
2259
2260 if not isinstance(original, FunctionTypes):
2261 new = _SpecState(original, spec_set, mock, entry, instance)
2262 mock._mock_children[entry] = new
2263 else:
2264 parent = mock
2265 if isinstance(spec, FunctionTypes):
2266 parent = mock.mock
2267
Michael Foord345266a2012-03-14 12:24:34 -07002268 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002269 kwargs['_eat_self'] = skipfirst
2270 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2271 _new_parent=parent,
2272 **kwargs)
2273 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002274 _check_signature(original, new, skipfirst=skipfirst)
2275
2276 # so functions created with _set_signature become instance attributes,
2277 # *plus* their underlying mock exists in _mock_children of the parent
2278 # mock. Adding to _mock_children may be unnecessary where we are also
2279 # setting as an instance attribute?
2280 if isinstance(new, FunctionTypes):
2281 setattr(mock, entry, new)
2282
2283 return mock
2284
2285
2286def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002287 """
2288 Return whether we should skip the first argument on spec's `entry`
2289 attribute.
2290 """
Michael Foord345266a2012-03-14 12:24:34 -07002291 if not isinstance(spec, type):
2292 if entry in getattr(spec, '__dict__', {}):
2293 # instance attribute - shouldn't skip
2294 return False
Michael Foord345266a2012-03-14 12:24:34 -07002295 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002296
2297 for klass in spec.__mro__:
2298 result = klass.__dict__.get(entry, DEFAULT)
2299 if result is DEFAULT:
2300 continue
2301 if isinstance(result, (staticmethod, classmethod)):
2302 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002303 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2304 # Normal method => skip if looked up on type
2305 # (if looked up on instance, self is already skipped)
2306 return is_type
2307 else:
2308 return False
Michael Foord345266a2012-03-14 12:24:34 -07002309
2310 # shouldn't get here unless function is a dynamically provided attribute
2311 # XXXX untested behaviour
2312 return is_type
2313
2314
2315def _get_class(obj):
2316 try:
2317 return obj.__class__
2318 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002319 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002320 return type(obj)
2321
2322
2323class _SpecState(object):
2324
2325 def __init__(self, spec, spec_set=False, parent=None,
2326 name=None, ids=None, instance=False):
2327 self.spec = spec
2328 self.ids = ids
2329 self.spec_set = spec_set
2330 self.parent = parent
2331 self.instance = instance
2332 self.name = name
2333
2334
2335FunctionTypes = (
2336 # python function
2337 type(create_autospec),
2338 # instance method
2339 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002340)
2341
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002342MethodWrapperTypes = (
2343 type(ANY.__eq__.__get__),
2344)
2345
Michael Foord345266a2012-03-14 12:24:34 -07002346
Michael Foorda74561a2012-03-25 19:03:13 +01002347file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002348
Michael Foord04cbe0c2013-03-19 17:22:51 -07002349def _iterate_read_data(read_data):
2350 # Helper for mock_open:
2351 # Retrieve lines from read_data via a generator so that separate calls to
2352 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002353 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2354 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002355
Berker Peksag86b34da2015-08-06 13:15:51 +03002356 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002357 # If the last line ended in a newline, the list comprehension will have an
2358 # extra entry that's just a newline. Remove this.
2359 data_as_list = data_as_list[:-1]
2360 else:
2361 # If there wasn't an extra newline by itself, then the file being
2362 # emulated doesn't have a newline to end the last line remove the
2363 # newline that our naive format() added
2364 data_as_list[-1] = data_as_list[-1][:-1]
2365
2366 for line in data_as_list:
2367 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002368
Robert Collins5329aaa2015-07-17 20:08:45 +12002369
Michael Foord0dccf652012-03-25 19:11:50 +01002370def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002371 """
2372 A helper function to create a mock to replace the use of `open`. It works
2373 for `open` called directly or used as a context manager.
2374
2375 The `mock` argument is the mock object to configure. If `None` (the
2376 default) then a `MagicMock` will be created for you, with the API limited
2377 to methods or attributes available on standard file handles.
2378
Michael Foord04cbe0c2013-03-19 17:22:51 -07002379 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2380 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002381 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002382 def _readlines_side_effect(*args, **kwargs):
2383 if handle.readlines.return_value is not None:
2384 return handle.readlines.return_value
2385 return list(_state[0])
2386
2387 def _read_side_effect(*args, **kwargs):
2388 if handle.read.return_value is not None:
2389 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002390 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002391
2392 def _readline_side_effect():
Tony Flury20870232018-09-12 23:21:16 +01002393 yield from _iter_side_effect()
2394 while True:
2395 yield type(read_data)()
2396
2397 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002398 if handle.readline.return_value is not None:
2399 while True:
2400 yield handle.readline.return_value
2401 for line in _state[0]:
2402 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002403
Michael Foorda74561a2012-03-25 19:03:13 +01002404 global file_spec
2405 if file_spec is None:
2406 import _io
2407 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2408
Michael Foord345266a2012-03-14 12:24:34 -07002409 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002410 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002411
Robert Collinsca647ef2015-07-24 03:48:20 +12002412 handle = MagicMock(spec=file_spec)
2413 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002414
Robert Collinsca647ef2015-07-24 03:48:20 +12002415 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002416
Robert Collinsca647ef2015-07-24 03:48:20 +12002417 handle.write.return_value = None
2418 handle.read.return_value = None
2419 handle.readline.return_value = None
2420 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002421
Robert Collinsca647ef2015-07-24 03:48:20 +12002422 handle.read.side_effect = _read_side_effect
2423 _state[1] = _readline_side_effect()
2424 handle.readline.side_effect = _state[1]
2425 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002426 handle.__iter__.side_effect = _iter_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002427
Robert Collinsca647ef2015-07-24 03:48:20 +12002428 def reset_data(*args, **kwargs):
2429 _state[0] = _iterate_read_data(read_data)
2430 if handle.readline.side_effect == _state[1]:
2431 # Only reset the side effect if the user hasn't overridden it.
2432 _state[1] = _readline_side_effect()
2433 handle.readline.side_effect = _state[1]
2434 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002435
Robert Collinsca647ef2015-07-24 03:48:20 +12002436 mock.side_effect = reset_data
2437 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002438 return mock
2439
2440
2441class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002442 """
2443 A mock intended to be used as a property, or other descriptor, on a class.
2444 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2445 a return value when it is fetched.
2446
2447 Fetching a `PropertyMock` instance from an object calls the mock, with
2448 no args. Setting it calls the mock with the value being set.
2449 """
Michael Foordc2870622012-04-13 16:57:22 +01002450 def _get_child_mock(self, **kwargs):
2451 return MagicMock(**kwargs)
2452
Michael Foord345266a2012-03-14 12:24:34 -07002453 def __get__(self, obj, obj_type):
2454 return self()
2455 def __set__(self, obj, val):
2456 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002457
2458
2459def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002460 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002461
2462 Given an input Mock, seals it to ensure no further mocks will be generated
2463 when accessing an attribute that was not already defined.
2464
Mario Corchero96200eb2018-10-19 22:57:37 +01002465 The operation recursively seals the mock passed in, meaning that
2466 the mock itself, any mocks generated by accessing one of its attributes,
2467 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002468 """
2469 mock._mock_sealed = True
2470 for attr in dir(mock):
2471 try:
2472 m = getattr(mock, attr)
2473 except AttributeError:
2474 continue
2475 if not isinstance(m, NonCallableMock):
2476 continue
2477 if m._mock_new_parent is mock:
2478 seal(m)