blob: 8f46050462bd941dd1b1c4fde520ea3f7bb0587f [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001# mock.py
2# Test tools for mocking and patching.
Michael Foordc17adf42012-03-14 13:30:29 -07003# Maintained by Michael Foord
4# Backport for other versions of Python available from
Ned Deily9d6d06e2018-06-11 00:45:50 -04005# https://pypi.org/project/mock
Michael Foord345266a2012-03-14 12:24:34 -07006
7__all__ = (
8 'Mock',
9 'MagicMock',
10 'patch',
11 'sentinel',
12 'DEFAULT',
13 'ANY',
14 'call',
15 'create_autospec',
16 'FILTER_DIR',
17 'NonCallableMock',
18 'NonCallableMagicMock',
19 'mock_open',
20 'PropertyMock',
Mario Corchero552be9d2017-10-17 12:35:11 +010021 'seal',
Michael Foord345266a2012-03-14 12:24:34 -070022)
23
24
25__version__ = '1.0'
26
27
28import inspect
29import pprint
30import sys
Michael Foordfddcfa22014-04-14 16:25:20 -040031import builtins
32from types import ModuleType
Petter Strandmark47d94242018-10-28 21:37:10 +010033from unittest.util import safe_repr
Antoine Pitrou5c64df72013-02-03 00:23:58 +010034from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070035
36
Michael Foordfddcfa22014-04-14 16:25:20 -040037_builtins = {name for name in dir(builtins) if not name.startswith('_')}
38
Michael Foord345266a2012-03-14 12:24:34 -070039BaseExceptions = (BaseException,)
40if 'java' in sys.platform:
41 # jython
42 import java
43 BaseExceptions = (BaseException, java.lang.Throwable)
44
45
46FILTER_DIR = True
47
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100048# Workaround for issue #12370
49# Without this, the __class__ properties wouldn't be set correctly
50_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070051
52def _is_instance_mock(obj):
53 # can't use isinstance on Mock objects because they override __class__
54 # The base class for all mocks is NonCallableMock
55 return issubclass(type(obj), NonCallableMock)
56
57
58def _is_exception(obj):
59 return (
60 isinstance(obj, BaseExceptions) or
61 isinstance(obj, type) and issubclass(obj, BaseExceptions)
62 )
63
64
Antoine Pitrou5c64df72013-02-03 00:23:58 +010065def _get_signature_object(func, as_instance, eat_self):
66 """
67 Given an arbitrary, possibly callable object, try to create a suitable
68 signature object.
69 Return a (reduced func, signature) tuple, or None.
70 """
71 if isinstance(func, type) and not as_instance:
72 # If it's a type and should be modelled as a type, use __init__.
Michael Foord345266a2012-03-14 12:24:34 -070073 try:
74 func = func.__init__
75 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010076 return None
77 # Skip the `self` argument in __init__
78 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070079 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010080 # If we really want to model an instance of the passed type,
81 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070082 try:
83 func = func.__call__
84 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010085 return None
86 if eat_self:
87 sig_func = partial(func, None)
88 else:
89 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -070090 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010091 return func, inspect.signature(sig_func)
92 except ValueError:
93 # Certain callable types are not supported by inspect.signature()
94 return None
Michael Foord345266a2012-03-14 12:24:34 -070095
96
97def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010098 sig = _get_signature_object(func, instance, skipfirst)
99 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700100 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100101 func, sig = sig
102 def checksig(_mock_self, *args, **kwargs):
103 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700104 _copy_func_details(func, checksig)
105 type(mock)._mock_check_sig = checksig
Xtreakf7fa62e2018-12-12 13:24:54 +0530106 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700107
108
109def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700110 # we explicitly don't copy func.__dict__ into this copy as it would
111 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300112 for attribute in (
113 '__name__', '__doc__', '__text_signature__',
114 '__module__', '__defaults__', '__kwdefaults__',
115 ):
116 try:
117 setattr(funcopy, attribute, getattr(func, attribute))
118 except AttributeError:
119 pass
Michael Foord345266a2012-03-14 12:24:34 -0700120
121
122def _callable(obj):
123 if isinstance(obj, type):
124 return True
125 if getattr(obj, '__call__', None) is not None:
126 return True
127 return False
128
129
130def _is_list(obj):
131 # checks for list or tuples
132 # XXXX badly named!
133 return type(obj) in (list, tuple)
134
135
136def _instance_callable(obj):
137 """Given an object, return True if the object is callable.
138 For classes, return True if instances would be callable."""
139 if not isinstance(obj, type):
140 # already an instance
141 return getattr(obj, '__call__', None) is not None
142
Michael Foorda74b3aa2012-03-14 14:40:22 -0700143 # *could* be broken by a class overriding __mro__ or __dict__ via
144 # a metaclass
145 for base in (obj,) + obj.__mro__:
146 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700147 return True
148 return False
149
150
151def _set_signature(mock, original, instance=False):
152 # creates a function with signature (*args, **kwargs) that delegates to a
153 # mock. It still does signature checking by calling a lambda with the same
154 # signature as the original.
155 if not _callable(original):
156 return
157
158 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100159 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700160 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700161 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100162 func, sig = result
163 def checksig(*args, **kwargs):
164 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700165 _copy_func_details(func, checksig)
166
167 name = original.__name__
168 if not name.isidentifier():
169 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100170 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700171 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100172 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700173 return mock(*args, **kwargs)""" % name
174 exec (src, context)
175 funcopy = context[name]
Xtreakf7fa62e2018-12-12 13:24:54 +0530176 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700177 return funcopy
178
179
Xtreakf7fa62e2018-12-12 13:24:54 +0530180def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700181 funcopy.mock = mock
182
183 # can't use isinstance with mocks
184 if not _is_instance_mock(mock):
185 return
186
187 def assert_called_with(*args, **kwargs):
188 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700189 def assert_called(*args, **kwargs):
190 return mock.assert_called(*args, **kwargs)
191 def assert_not_called(*args, **kwargs):
192 return mock.assert_not_called(*args, **kwargs)
193 def assert_called_once(*args, **kwargs):
194 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700195 def assert_called_once_with(*args, **kwargs):
196 return mock.assert_called_once_with(*args, **kwargs)
197 def assert_has_calls(*args, **kwargs):
198 return mock.assert_has_calls(*args, **kwargs)
199 def assert_any_call(*args, **kwargs):
200 return mock.assert_any_call(*args, **kwargs)
201 def reset_mock():
202 funcopy.method_calls = _CallList()
203 funcopy.mock_calls = _CallList()
204 mock.reset_mock()
205 ret = funcopy.return_value
206 if _is_instance_mock(ret) and not ret is mock:
207 ret.reset_mock()
208
209 funcopy.called = False
210 funcopy.call_count = 0
211 funcopy.call_args = None
212 funcopy.call_args_list = _CallList()
213 funcopy.method_calls = _CallList()
214 funcopy.mock_calls = _CallList()
215
216 funcopy.return_value = mock.return_value
217 funcopy.side_effect = mock.side_effect
218 funcopy._mock_children = mock._mock_children
219
220 funcopy.assert_called_with = assert_called_with
221 funcopy.assert_called_once_with = assert_called_once_with
222 funcopy.assert_has_calls = assert_has_calls
223 funcopy.assert_any_call = assert_any_call
224 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700225 funcopy.assert_called = assert_called
226 funcopy.assert_not_called = assert_not_called
227 funcopy.assert_called_once = assert_called_once
Xtreakf7fa62e2018-12-12 13:24:54 +0530228 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700229
230 mock._mock_delegate = funcopy
231
232
233def _is_magic(name):
234 return '__%s__' % name[2:-2] == name
235
236
237class _SentinelObject(object):
238 "A unique, named, sentinel object."
239 def __init__(self, name):
240 self.name = name
241
242 def __repr__(self):
243 return 'sentinel.%s' % self.name
244
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200245 def __reduce__(self):
246 return 'sentinel.%s' % self.name
247
Michael Foord345266a2012-03-14 12:24:34 -0700248
249class _Sentinel(object):
250 """Access attributes to return a named object, usable as a sentinel."""
251 def __init__(self):
252 self._sentinels = {}
253
254 def __getattr__(self, name):
255 if name == '__bases__':
256 # Without this help(unittest.mock) raises an exception
257 raise AttributeError
258 return self._sentinels.setdefault(name, _SentinelObject(name))
259
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200260 def __reduce__(self):
261 return 'sentinel'
262
Michael Foord345266a2012-03-14 12:24:34 -0700263
264sentinel = _Sentinel()
265
266DEFAULT = sentinel.DEFAULT
267_missing = sentinel.MISSING
268_deleted = sentinel.DELETED
269
270
Michael Foord345266a2012-03-14 12:24:34 -0700271def _copy(value):
272 if type(value) in (dict, list, tuple, set):
273 return type(value)(value)
274 return value
275
276
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200277_allowed_names = {
278 'return_value', '_mock_return_value', 'side_effect',
279 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
280 '_mock_name', '_mock_new_name'
281}
Michael Foord345266a2012-03-14 12:24:34 -0700282
283
284def _delegating_property(name):
285 _allowed_names.add(name)
286 _the_name = '_mock_' + name
287 def _get(self, name=name, _the_name=_the_name):
288 sig = self._mock_delegate
289 if sig is None:
290 return getattr(self, _the_name)
291 return getattr(sig, name)
292 def _set(self, value, name=name, _the_name=_the_name):
293 sig = self._mock_delegate
294 if sig is None:
295 self.__dict__[_the_name] = value
296 else:
297 setattr(sig, name, value)
298
299 return property(_get, _set)
300
301
302
303class _CallList(list):
304
305 def __contains__(self, value):
306 if not isinstance(value, list):
307 return list.__contains__(self, value)
308 len_value = len(value)
309 len_self = len(self)
310 if len_value > len_self:
311 return False
312
313 for i in range(0, len_self - len_value + 1):
314 sub_list = self[i:i+len_value]
315 if sub_list == value:
316 return True
317 return False
318
319 def __repr__(self):
320 return pprint.pformat(list(self))
321
322
323def _check_and_set_parent(parent, value, name, new_name):
324 if not _is_instance_mock(value):
325 return False
326 if ((value._mock_name or value._mock_new_name) or
327 (value._mock_parent is not None) or
328 (value._mock_new_parent is not None)):
329 return False
330
331 _parent = parent
332 while _parent is not None:
333 # setting a mock (value) as a child or return value of itself
334 # should not modify the mock
335 if _parent is value:
336 return False
337 _parent = _parent._mock_new_parent
338
339 if new_name:
340 value._mock_new_parent = parent
341 value._mock_new_name = new_name
342 if name:
343 value._mock_parent = parent
344 value._mock_name = name
345 return True
346
Michael Foord01bafdc2014-04-14 16:09:42 -0400347# Internal class to identify if we wrapped an iterator object or not.
348class _MockIter(object):
349 def __init__(self, obj):
350 self.obj = iter(obj)
351 def __iter__(self):
352 return self
353 def __next__(self):
354 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700355
356class Base(object):
357 _mock_return_value = DEFAULT
358 _mock_side_effect = None
359 def __init__(self, *args, **kwargs):
360 pass
361
362
363
364class NonCallableMock(Base):
365 """A non-callable version of `Mock`"""
366
367 def __new__(cls, *args, **kw):
368 # every instance has its own class
369 # so we can create magic methods on the
370 # class without stomping on other mocks
371 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
372 instance = object.__new__(new)
373 return instance
374
375
376 def __init__(
377 self, spec=None, wraps=None, name=None, spec_set=None,
378 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530379 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700380 ):
381 if _new_parent is None:
382 _new_parent = parent
383
384 __dict__ = self.__dict__
385 __dict__['_mock_parent'] = parent
386 __dict__['_mock_name'] = name
387 __dict__['_mock_new_name'] = _new_name
388 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100389 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700390
391 if spec_set is not None:
392 spec = spec_set
393 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100394 if _eat_self is None:
395 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700396
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100397 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700398
399 __dict__['_mock_children'] = {}
400 __dict__['_mock_wraps'] = wraps
401 __dict__['_mock_delegate'] = None
402
403 __dict__['_mock_called'] = False
404 __dict__['_mock_call_args'] = None
405 __dict__['_mock_call_count'] = 0
406 __dict__['_mock_call_args_list'] = _CallList()
407 __dict__['_mock_mock_calls'] = _CallList()
408
409 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530410 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700411
412 if kwargs:
413 self.configure_mock(**kwargs)
414
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000415 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700416 spec, wraps, name, spec_set, parent,
417 _spec_state
418 )
419
420
421 def attach_mock(self, mock, attribute):
422 """
423 Attach a mock as an attribute of this one, replacing its name and
424 parent. Calls to the attached mock will be recorded in the
425 `method_calls` and `mock_calls` attributes of this one."""
426 mock._mock_parent = None
427 mock._mock_new_parent = None
428 mock._mock_name = ''
429 mock._mock_new_name = None
430
431 setattr(self, attribute, mock)
432
433
434 def mock_add_spec(self, spec, spec_set=False):
435 """Add a spec to a mock. `spec` can either be an object or a
436 list of strings. Only attributes on the `spec` can be fetched as
437 attributes from the mock.
438
439 If `spec_set` is True then only attributes on the spec can be set."""
440 self._mock_add_spec(spec, spec_set)
441
442
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100443 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
444 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700445 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100446 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700447
448 if spec is not None and not _is_list(spec):
449 if isinstance(spec, type):
450 _spec_class = spec
451 else:
452 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100453 res = _get_signature_object(spec,
454 _spec_as_instance, _eat_self)
455 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700456
457 spec = dir(spec)
458
459 __dict__ = self.__dict__
460 __dict__['_spec_class'] = _spec_class
461 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100462 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700463 __dict__['_mock_methods'] = spec
464
465
466 def __get_return_value(self):
467 ret = self._mock_return_value
468 if self._mock_delegate is not None:
469 ret = self._mock_delegate.return_value
470
471 if ret is DEFAULT:
472 ret = self._get_child_mock(
473 _new_parent=self, _new_name='()'
474 )
475 self.return_value = ret
476 return ret
477
478
479 def __set_return_value(self, value):
480 if self._mock_delegate is not None:
481 self._mock_delegate.return_value = value
482 else:
483 self._mock_return_value = value
484 _check_and_set_parent(self, value, None, '()')
485
486 __return_value_doc = "The value to be returned when the mock is called."
487 return_value = property(__get_return_value, __set_return_value,
488 __return_value_doc)
489
490
491 @property
492 def __class__(self):
493 if self._spec_class is None:
494 return type(self)
495 return self._spec_class
496
497 called = _delegating_property('called')
498 call_count = _delegating_property('call_count')
499 call_args = _delegating_property('call_args')
500 call_args_list = _delegating_property('call_args_list')
501 mock_calls = _delegating_property('mock_calls')
502
503
504 def __get_side_effect(self):
505 delegated = self._mock_delegate
506 if delegated is None:
507 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400508 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200509 if (sf is not None and not callable(sf)
510 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400511 sf = _MockIter(sf)
512 delegated.side_effect = sf
513 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700514
515 def __set_side_effect(self, value):
516 value = _try_iter(value)
517 delegated = self._mock_delegate
518 if delegated is None:
519 self._mock_side_effect = value
520 else:
521 delegated.side_effect = value
522
523 side_effect = property(__get_side_effect, __set_side_effect)
524
525
Kushal Das9cd39a12016-06-02 10:20:16 -0700526 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700527 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200528 if visited is None:
529 visited = []
530 if id(self) in visited:
531 return
532 visited.append(id(self))
533
Michael Foord345266a2012-03-14 12:24:34 -0700534 self.called = False
535 self.call_args = None
536 self.call_count = 0
537 self.mock_calls = _CallList()
538 self.call_args_list = _CallList()
539 self.method_calls = _CallList()
540
Kushal Das9cd39a12016-06-02 10:20:16 -0700541 if return_value:
542 self._mock_return_value = DEFAULT
543 if side_effect:
544 self._mock_side_effect = None
545
Michael Foord345266a2012-03-14 12:24:34 -0700546 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530547 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100548 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200549 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700550
551 ret = self._mock_return_value
552 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200553 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700554
555
556 def configure_mock(self, **kwargs):
557 """Set attributes on the mock through keyword arguments.
558
559 Attributes plus return values and side effects can be set on child
560 mocks using standard dot notation and unpacking a dictionary in the
561 method call:
562
563 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
564 >>> mock.configure_mock(**attrs)"""
565 for arg, val in sorted(kwargs.items(),
566 # we sort on the number of dots so that
567 # attributes are set before we set attributes on
568 # attributes
569 key=lambda entry: entry[0].count('.')):
570 args = arg.split('.')
571 final = args.pop()
572 obj = self
573 for entry in args:
574 obj = getattr(obj, entry)
575 setattr(obj, final, val)
576
577
578 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530579 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700580 raise AttributeError(name)
581 elif self._mock_methods is not None:
582 if name not in self._mock_methods or name in _all_magics:
583 raise AttributeError("Mock object has no attribute %r" % name)
584 elif _is_magic(name):
585 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530586 if not self._mock_unsafe:
587 if name.startswith(('assert', 'assret')):
588 raise AttributeError(name)
Michael Foord345266a2012-03-14 12:24:34 -0700589
590 result = self._mock_children.get(name)
591 if result is _deleted:
592 raise AttributeError(name)
593 elif result is None:
594 wraps = None
595 if self._mock_wraps is not None:
596 # XXXX should we get the attribute without triggering code
597 # execution?
598 wraps = getattr(self._mock_wraps, name)
599
600 result = self._get_child_mock(
601 parent=self, name=name, wraps=wraps, _new_name=name,
602 _new_parent=self
603 )
604 self._mock_children[name] = result
605
606 elif isinstance(result, _SpecState):
607 result = create_autospec(
608 result.spec, result.spec_set, result.instance,
609 result.parent, result.name
610 )
611 self._mock_children[name] = result
612
613 return result
614
615
Mario Corchero552be9d2017-10-17 12:35:11 +0100616 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700617 _name_list = [self._mock_new_name]
618 _parent = self._mock_new_parent
619 last = self
620
621 dot = '.'
622 if _name_list == ['()']:
623 dot = ''
624 seen = set()
625 while _parent is not None:
626 last = _parent
627
628 _name_list.append(_parent._mock_new_name + dot)
629 dot = '.'
630 if _parent._mock_new_name == '()':
631 dot = ''
632
633 _parent = _parent._mock_new_parent
634
635 # use ids here so as not to call __hash__ on the mocks
636 if id(_parent) in seen:
637 break
638 seen.add(id(_parent))
639
640 _name_list = list(reversed(_name_list))
641 _first = last._mock_name or 'mock'
642 if len(_name_list) > 1:
643 if _name_list[1] not in ('()', '().'):
644 _first += '.'
645 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100646 return ''.join(_name_list)
647
648 def __repr__(self):
649 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700650
651 name_string = ''
652 if name not in ('mock', 'mock.'):
653 name_string = ' name=%r' % name
654
655 spec_string = ''
656 if self._spec_class is not None:
657 spec_string = ' spec=%r'
658 if self._spec_set:
659 spec_string = ' spec_set=%r'
660 spec_string = spec_string % self._spec_class.__name__
661 return "<%s%s%s id='%s'>" % (
662 type(self).__name__,
663 name_string,
664 spec_string,
665 id(self)
666 )
667
668
669 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700670 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100671 if not FILTER_DIR:
672 return object.__dir__(self)
673
Michael Foord345266a2012-03-14 12:24:34 -0700674 extras = self._mock_methods or []
675 from_type = dir(type(self))
676 from_dict = list(self.__dict__)
677
Michael Foord313f85f2012-03-25 18:16:07 +0100678 from_type = [e for e in from_type if not e.startswith('_')]
679 from_dict = [e for e in from_dict if not e.startswith('_') or
680 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700681 return sorted(set(extras + from_type + from_dict +
682 list(self._mock_children)))
683
684
685 def __setattr__(self, name, value):
686 if name in _allowed_names:
687 # property setters go through here
688 return object.__setattr__(self, name, value)
689 elif (self._spec_set and self._mock_methods is not None and
690 name not in self._mock_methods and
691 name not in self.__dict__):
692 raise AttributeError("Mock object has no attribute '%s'" % name)
693 elif name in _unsupported_magics:
694 msg = 'Attempting to set unsupported magic method %r.' % name
695 raise AttributeError(msg)
696 elif name in _all_magics:
697 if self._mock_methods is not None and name not in self._mock_methods:
698 raise AttributeError("Mock object has no attribute '%s'" % name)
699
700 if not _is_instance_mock(value):
701 setattr(type(self), name, _get_method(name, value))
702 original = value
703 value = lambda *args, **kw: original(self, *args, **kw)
704 else:
705 # only set _new_name and not name so that mock_calls is tracked
706 # but not method calls
707 _check_and_set_parent(self, value, None, name)
708 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100709 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700710 elif name == '__class__':
711 self._spec_class = value
712 return
713 else:
714 if _check_and_set_parent(self, value, name, name):
715 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100716
717 if self._mock_sealed and not hasattr(self, name):
718 mock_name = f'{self._extract_mock_name()}.{name}'
719 raise AttributeError(f'Cannot set {mock_name}')
720
Michael Foord345266a2012-03-14 12:24:34 -0700721 return object.__setattr__(self, name, value)
722
723
724 def __delattr__(self, name):
725 if name in _all_magics and name in type(self).__dict__:
726 delattr(type(self), name)
727 if name not in self.__dict__:
728 # for magic methods that are still MagicProxy objects and
729 # not set on the instance itself
730 return
731
Michael Foord345266a2012-03-14 12:24:34 -0700732 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000733 if name in self.__dict__:
734 super().__delattr__(name)
735 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700736 raise AttributeError(name)
737 if obj is not _missing:
738 del self._mock_children[name]
739 self._mock_children[name] = _deleted
740
741
Michael Foord345266a2012-03-14 12:24:34 -0700742 def _format_mock_call_signature(self, args, kwargs):
743 name = self._mock_name or 'mock'
744 return _format_call_signature(name, args, kwargs)
745
746
747 def _format_mock_failure_message(self, args, kwargs):
Susan Su2bdd5852019-02-13 18:22:29 -0800748 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700749 expected_string = self._format_mock_call_signature(args, kwargs)
750 call_args = self.call_args
751 if len(call_args) == 3:
752 call_args = call_args[1:]
753 actual_string = self._format_mock_call_signature(*call_args)
754 return message % (expected_string, actual_string)
755
756
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100757 def _call_matcher(self, _call):
758 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000759 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100760 comparison key suitable for matching with other calls.
761 This is a best effort method which relies on the spec's signature,
762 if available, or falls back on the arguments themselves.
763 """
764 sig = self._spec_signature
765 if sig is not None:
766 if len(_call) == 2:
767 name = ''
768 args, kwargs = _call
769 else:
770 name, args, kwargs = _call
771 try:
772 return name, sig.bind(*args, **kwargs)
773 except TypeError as e:
774 return e.with_traceback(None)
775 else:
776 return _call
777
Kushal Das68290f42014-04-17 01:54:07 +0530778 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530779 """assert that the mock was never called.
780 """
781 self = _mock_self
782 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100783 msg = ("Expected '%s' to not have been called. Called %s times.%s"
784 % (self._mock_name or 'mock',
785 self.call_count,
786 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530787 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100788
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100789 def assert_called(_mock_self):
790 """assert that the mock was called at least once
791 """
792 self = _mock_self
793 if self.call_count == 0:
794 msg = ("Expected '%s' to have been called." %
795 self._mock_name or 'mock')
796 raise AssertionError(msg)
797
798 def assert_called_once(_mock_self):
799 """assert that the mock was called only once.
800 """
801 self = _mock_self
802 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100803 msg = ("Expected '%s' to have been called once. Called %s times.%s"
804 % (self._mock_name or 'mock',
805 self.call_count,
806 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100807 raise AssertionError(msg)
808
Michael Foord345266a2012-03-14 12:24:34 -0700809 def assert_called_with(_mock_self, *args, **kwargs):
810 """assert that the mock was called with the specified arguments.
811
812 Raises an AssertionError if the args and keyword args passed in are
813 different to the last call to the mock."""
814 self = _mock_self
815 if self.call_args is None:
816 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800817 actual = 'not called.'
818 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
819 % (expected, actual))
820 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700821
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100822 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700823 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100824 return msg
825 expected = self._call_matcher((args, kwargs))
826 actual = self._call_matcher(self.call_args)
827 if expected != actual:
828 cause = expected if isinstance(expected, Exception) else None
829 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700830
831
832 def assert_called_once_with(_mock_self, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100833 """assert that the mock was called exactly once and that that call was
834 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700835 self = _mock_self
836 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100837 msg = ("Expected '%s' to be called once. Called %s times.%s"
838 % (self._mock_name or 'mock',
839 self.call_count,
840 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700841 raise AssertionError(msg)
842 return self.assert_called_with(*args, **kwargs)
843
844
845 def assert_has_calls(self, calls, any_order=False):
846 """assert the mock has been called with the specified calls.
847 The `mock_calls` list is checked for the calls.
848
849 If `any_order` is False (the default) then the calls must be
850 sequential. There can be extra calls before or after the
851 specified calls.
852
853 If `any_order` is True then the calls can be in any order, but
854 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100855 expected = [self._call_matcher(c) for c in calls]
856 cause = expected if isinstance(expected, Exception) else None
857 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700858 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100859 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700860 raise AssertionError(
Petter Strandmark47d94242018-10-28 21:37:10 +0100861 'Calls not found.\nExpected: %r%s'
862 % (_CallList(calls), self._calls_repr(prefix="Actual"))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100863 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700864 return
865
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100866 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700867
868 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100869 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700870 try:
871 all_calls.remove(kall)
872 except ValueError:
873 not_found.append(kall)
874 if not_found:
875 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400876 '%r does not contain all of %r in its call list, '
877 'found %r instead' % (self._mock_name or 'mock',
878 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100879 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700880
881
882 def assert_any_call(self, *args, **kwargs):
883 """assert the mock has been called with the specified arguments.
884
885 The assert passes if the mock has *ever* been called, unlike
886 `assert_called_with` and `assert_called_once_with` that only pass if
887 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100888 expected = self._call_matcher((args, kwargs))
889 actual = [self._call_matcher(c) for c in self.call_args_list]
890 if expected not in actual:
891 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700892 expected_string = self._format_mock_call_signature(args, kwargs)
893 raise AssertionError(
894 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100895 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700896
897
898 def _get_child_mock(self, **kw):
899 """Create the child mocks for attributes and return value.
900 By default child mocks will be the same type as the parent.
901 Subclasses of Mock may want to override this to customize the way
902 child mocks are made.
903
904 For non-callable mocks the callable variant will be used (rather than
905 any custom subclass)."""
906 _type = type(self)
907 if not issubclass(_type, CallableMixin):
908 if issubclass(_type, NonCallableMagicMock):
909 klass = MagicMock
910 elif issubclass(_type, NonCallableMock) :
911 klass = Mock
912 else:
913 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +0100914
915 if self._mock_sealed:
916 attribute = "." + kw["name"] if "name" in kw else "()"
917 mock_name = self._extract_mock_name() + attribute
918 raise AttributeError(mock_name)
919
Michael Foord345266a2012-03-14 12:24:34 -0700920 return klass(**kw)
921
922
Petter Strandmark47d94242018-10-28 21:37:10 +0100923 def _calls_repr(self, prefix="Calls"):
924 """Renders self.mock_calls as a string.
925
926 Example: "\nCalls: [call(1), call(2)]."
927
928 If self.mock_calls is empty, an empty string is returned. The
929 output will be truncated if very long.
930 """
931 if not self.mock_calls:
932 return ""
933 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
934
935
Michael Foord345266a2012-03-14 12:24:34 -0700936
937def _try_iter(obj):
938 if obj is None:
939 return obj
940 if _is_exception(obj):
941 return obj
942 if _callable(obj):
943 return obj
944 try:
945 return iter(obj)
946 except TypeError:
947 # XXXX backwards compatibility
948 # but this will blow up on first call - so maybe we should fail early?
949 return obj
950
951
952
953class CallableMixin(Base):
954
955 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
956 wraps=None, name=None, spec_set=None, parent=None,
957 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
958 self.__dict__['_mock_return_value'] = return_value
959
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000960 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700961 spec, wraps, name, spec_set, parent,
962 _spec_state, _new_name, _new_parent, **kwargs
963 )
964
965 self.side_effect = side_effect
966
967
968 def _mock_check_sig(self, *args, **kwargs):
969 # stub method that can be replaced with one with a specific signature
970 pass
971
972
973 def __call__(_mock_self, *args, **kwargs):
974 # can't use self in-case a function / method we are mocking uses self
975 # in the signature
976 _mock_self._mock_check_sig(*args, **kwargs)
977 return _mock_self._mock_call(*args, **kwargs)
978
979
980 def _mock_call(_mock_self, *args, **kwargs):
981 self = _mock_self
982 self.called = True
983 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100984
Chris Withers8ca0fa92018-12-03 21:31:37 +0000985 # handle call_args
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100986 _call = _Call((args, kwargs), two=True)
987 self.call_args = _call
988 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700989
990 seen = set()
Chris Withers8ca0fa92018-12-03 21:31:37 +0000991
992 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700993 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +0000994 method_call_name = self._mock_name
995
996 # initial stuff for mock_calls:
997 mock_call_name = self._mock_new_name
998 is_a_call = mock_call_name == '()'
999 self.mock_calls.append(_Call(('', args, kwargs)))
1000
1001 # follow up the chain of mocks:
1002 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001003 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001004
Chris Withers8ca0fa92018-12-03 21:31:37 +00001005 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001006 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001007 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001008 do_method_calls = _new_parent._mock_parent is not None
1009 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001010 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001011
Chris Withers8ca0fa92018-12-03 21:31:37 +00001012 # handle mock_calls:
1013 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001014 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001015
1016 if _new_parent._mock_new_name:
1017 if is_a_call:
1018 dot = ''
1019 else:
1020 dot = '.'
1021 is_a_call = _new_parent._mock_new_name == '()'
1022 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1023
1024 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001025 _new_parent = _new_parent._mock_new_parent
1026
Chris Withers8ca0fa92018-12-03 21:31:37 +00001027 # check we're not in an infinite loop:
1028 # ( use ids here so as not to call __hash__ on the mocks)
Michael Foord345266a2012-03-14 12:24:34 -07001029 _new_parent_id = id(_new_parent)
1030 if _new_parent_id in seen:
1031 break
1032 seen.add(_new_parent_id)
1033
Michael Foord345266a2012-03-14 12:24:34 -07001034 effect = self.side_effect
1035 if effect is not None:
1036 if _is_exception(effect):
1037 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001038 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001039 result = next(effect)
1040 if _is_exception(result):
1041 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001042 else:
1043 result = effect(*args, **kwargs)
1044
1045 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001046 return result
Michael Foord345266a2012-03-14 12:24:34 -07001047
Mario Corcherof05df0a2018-12-08 11:25:02 +00001048 if self._mock_return_value is not DEFAULT:
1049 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001050
Mario Corcherof05df0a2018-12-08 11:25:02 +00001051 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001052 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001053
1054 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001055
1056
1057
1058class Mock(CallableMixin, NonCallableMock):
1059 """
1060 Create a new `Mock` object. `Mock` takes several optional arguments
1061 that specify the behaviour of the Mock object:
1062
1063 * `spec`: This can be either a list of strings or an existing object (a
1064 class or instance) that acts as the specification for the mock object. If
1065 you pass in an object then a list of strings is formed by calling dir on
1066 the object (excluding unsupported magic attributes and methods). Accessing
1067 any attribute not in this list will raise an `AttributeError`.
1068
1069 If `spec` is an object (rather than a list of strings) then
1070 `mock.__class__` returns the class of the spec object. This allows mocks
1071 to pass `isinstance` tests.
1072
1073 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1074 or get an attribute on the mock that isn't on the object passed as
1075 `spec_set` will raise an `AttributeError`.
1076
1077 * `side_effect`: A function to be called whenever the Mock is called. See
1078 the `side_effect` attribute. Useful for raising exceptions or
1079 dynamically changing return values. The function is called with the same
1080 arguments as the mock, and unless it returns `DEFAULT`, the return
1081 value of this function is used as the return value.
1082
Michael Foord2cd48732012-04-21 15:52:11 +01001083 If `side_effect` is an iterable then each call to the mock will return
1084 the next value from the iterable. If any of the members of the iterable
1085 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001086
Michael Foord345266a2012-03-14 12:24:34 -07001087 * `return_value`: The value returned when the mock is called. By default
1088 this is a new Mock (created on first access). See the
1089 `return_value` attribute.
1090
Michael Foord0682a0c2012-04-13 20:51:20 +01001091 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1092 calling the Mock will pass the call through to the wrapped object
1093 (returning the real result). Attribute access on the mock will return a
1094 Mock object that wraps the corresponding attribute of the wrapped object
1095 (so attempting to access an attribute that doesn't exist will raise an
1096 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001097
1098 If the mock has an explicit `return_value` set then calls are not passed
1099 to the wrapped object and the `return_value` is returned instead.
1100
1101 * `name`: If the mock has a name then it will be used in the repr of the
1102 mock. This can be useful for debugging. The name is propagated to child
1103 mocks.
1104
1105 Mocks can also be called with arbitrary keyword arguments. These will be
1106 used to set attributes on the mock after it is created.
1107 """
1108
1109
1110
1111def _dot_lookup(thing, comp, import_path):
1112 try:
1113 return getattr(thing, comp)
1114 except AttributeError:
1115 __import__(import_path)
1116 return getattr(thing, comp)
1117
1118
1119def _importer(target):
1120 components = target.split('.')
1121 import_path = components.pop(0)
1122 thing = __import__(import_path)
1123
1124 for comp in components:
1125 import_path += ".%s" % comp
1126 thing = _dot_lookup(thing, comp, import_path)
1127 return thing
1128
1129
1130def _is_started(patcher):
1131 # XXXX horrible
1132 return hasattr(patcher, 'is_local')
1133
1134
1135class _patch(object):
1136
1137 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001138 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001139
1140 def __init__(
1141 self, getter, attribute, new, spec, create,
1142 spec_set, autospec, new_callable, kwargs
1143 ):
1144 if new_callable is not None:
1145 if new is not DEFAULT:
1146 raise ValueError(
1147 "Cannot use 'new' and 'new_callable' together"
1148 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001149 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001150 raise ValueError(
1151 "Cannot use 'autospec' and 'new_callable' together"
1152 )
1153
1154 self.getter = getter
1155 self.attribute = attribute
1156 self.new = new
1157 self.new_callable = new_callable
1158 self.spec = spec
1159 self.create = create
1160 self.has_local = False
1161 self.spec_set = spec_set
1162 self.autospec = autospec
1163 self.kwargs = kwargs
1164 self.additional_patchers = []
1165
1166
1167 def copy(self):
1168 patcher = _patch(
1169 self.getter, self.attribute, self.new, self.spec,
1170 self.create, self.spec_set,
1171 self.autospec, self.new_callable, self.kwargs
1172 )
1173 patcher.attribute_name = self.attribute_name
1174 patcher.additional_patchers = [
1175 p.copy() for p in self.additional_patchers
1176 ]
1177 return patcher
1178
1179
1180 def __call__(self, func):
1181 if isinstance(func, type):
1182 return self.decorate_class(func)
1183 return self.decorate_callable(func)
1184
1185
1186 def decorate_class(self, klass):
1187 for attr in dir(klass):
1188 if not attr.startswith(patch.TEST_PREFIX):
1189 continue
1190
1191 attr_value = getattr(klass, attr)
1192 if not hasattr(attr_value, "__call__"):
1193 continue
1194
1195 patcher = self.copy()
1196 setattr(klass, attr, patcher(attr_value))
1197 return klass
1198
1199
1200 def decorate_callable(self, func):
1201 if hasattr(func, 'patchings'):
1202 func.patchings.append(self)
1203 return func
1204
1205 @wraps(func)
1206 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001207 extra_args = []
1208 entered_patchers = []
1209
Michael Foord50a8c0e2012-03-25 18:57:58 +01001210 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001211 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001212 for patching in patched.patchings:
1213 arg = patching.__enter__()
1214 entered_patchers.append(patching)
1215 if patching.attribute_name is not None:
1216 keywargs.update(arg)
1217 elif patching.new is DEFAULT:
1218 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001219
Michael Foordd7c65e22012-03-14 14:56:54 -07001220 args += tuple(extra_args)
1221 return func(*args, **keywargs)
1222 except:
1223 if (patching not in entered_patchers and
1224 _is_started(patching)):
1225 # the patcher may have been started, but an exception
1226 # raised whilst entering one of its additional_patchers
1227 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001228 # Pass the exception to __exit__
1229 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001230 # re-raise the exception
1231 raise
Michael Foord345266a2012-03-14 12:24:34 -07001232 finally:
1233 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001234 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001235
1236 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001237 return patched
1238
1239
1240 def get_original(self):
1241 target = self.getter()
1242 name = self.attribute
1243
1244 original = DEFAULT
1245 local = False
1246
1247 try:
1248 original = target.__dict__[name]
1249 except (AttributeError, KeyError):
1250 original = getattr(target, name, DEFAULT)
1251 else:
1252 local = True
1253
Michael Foordfddcfa22014-04-14 16:25:20 -04001254 if name in _builtins and isinstance(target, ModuleType):
1255 self.create = True
1256
Michael Foord345266a2012-03-14 12:24:34 -07001257 if not self.create and original is DEFAULT:
1258 raise AttributeError(
1259 "%s does not have the attribute %r" % (target, name)
1260 )
1261 return original, local
1262
1263
1264 def __enter__(self):
1265 """Perform the patch."""
1266 new, spec, spec_set = self.new, self.spec, self.spec_set
1267 autospec, kwargs = self.autospec, self.kwargs
1268 new_callable = self.new_callable
1269 self.target = self.getter()
1270
Michael Foord50a8c0e2012-03-25 18:57:58 +01001271 # normalise False to None
1272 if spec is False:
1273 spec = None
1274 if spec_set is False:
1275 spec_set = None
1276 if autospec is False:
1277 autospec = None
1278
1279 if spec is not None and autospec is not None:
1280 raise TypeError("Can't specify spec and autospec")
1281 if ((spec is not None or autospec is not None) and
1282 spec_set not in (True, None)):
1283 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1284
Michael Foord345266a2012-03-14 12:24:34 -07001285 original, local = self.get_original()
1286
Michael Foord50a8c0e2012-03-25 18:57:58 +01001287 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001288 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001289 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001290 # set spec to the object we are replacing
1291 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001292 if spec_set is True:
1293 spec_set = original
1294 spec = None
1295 elif spec is not None:
1296 if spec_set is True:
1297 spec_set = spec
1298 spec = None
1299 elif spec_set is True:
1300 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001301
Michael Foord50a8c0e2012-03-25 18:57:58 +01001302 if spec is not None or spec_set is not None:
1303 if original is DEFAULT:
1304 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001305 if isinstance(original, type):
1306 # If we're patching out a class and there is a spec
1307 inherit = True
1308
1309 Klass = MagicMock
1310 _kwargs = {}
1311 if new_callable is not None:
1312 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001313 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001314 this_spec = spec
1315 if spec_set is not None:
1316 this_spec = spec_set
1317 if _is_list(this_spec):
1318 not_callable = '__call__' not in this_spec
1319 else:
1320 not_callable = not callable(this_spec)
1321 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001322 Klass = NonCallableMagicMock
1323
1324 if spec is not None:
1325 _kwargs['spec'] = spec
1326 if spec_set is not None:
1327 _kwargs['spec_set'] = spec_set
1328
1329 # add a name to mocks
1330 if (isinstance(Klass, type) and
1331 issubclass(Klass, NonCallableMock) and self.attribute):
1332 _kwargs['name'] = self.attribute
1333
1334 _kwargs.update(kwargs)
1335 new = Klass(**_kwargs)
1336
1337 if inherit and _is_instance_mock(new):
1338 # we can only tell if the instance should be callable if the
1339 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001340 this_spec = spec
1341 if spec_set is not None:
1342 this_spec = spec_set
1343 if (not _is_list(this_spec) and not
1344 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001345 Klass = NonCallableMagicMock
1346
1347 _kwargs.pop('name')
1348 new.return_value = Klass(_new_parent=new, _new_name='()',
1349 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001350 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001351 # spec is ignored, new *must* be default, spec_set is treated
1352 # as a boolean. Should we check spec is not None and that spec_set
1353 # is a bool?
1354 if new is not DEFAULT:
1355 raise TypeError(
1356 "autospec creates the mock for you. Can't specify "
1357 "autospec and new."
1358 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001359 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001360 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001361 spec_set = bool(spec_set)
1362 if autospec is True:
1363 autospec = original
1364
1365 new = create_autospec(autospec, spec_set=spec_set,
1366 _name=self.attribute, **kwargs)
1367 elif kwargs:
1368 # can't set keyword args when we aren't creating the mock
1369 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1370 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1371
1372 new_attr = new
1373
1374 self.temp_original = original
1375 self.is_local = local
1376 setattr(self.target, self.attribute, new_attr)
1377 if self.attribute_name is not None:
1378 extra_args = {}
1379 if self.new is DEFAULT:
1380 extra_args[self.attribute_name] = new
1381 for patching in self.additional_patchers:
1382 arg = patching.__enter__()
1383 if patching.new is DEFAULT:
1384 extra_args.update(arg)
1385 return extra_args
1386
1387 return new
1388
1389
Michael Foord50a8c0e2012-03-25 18:57:58 +01001390 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001391 """Undo the patch."""
1392 if not _is_started(self):
1393 raise RuntimeError('stop called on unstarted patcher')
1394
1395 if self.is_local and self.temp_original is not DEFAULT:
1396 setattr(self.target, self.attribute, self.temp_original)
1397 else:
1398 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001399 if not self.create and (not hasattr(self.target, self.attribute) or
1400 self.attribute in ('__doc__', '__module__',
1401 '__defaults__', '__annotations__',
1402 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001403 # needed for proxy objects like django settings
1404 setattr(self.target, self.attribute, self.temp_original)
1405
1406 del self.temp_original
1407 del self.is_local
1408 del self.target
1409 for patcher in reversed(self.additional_patchers):
1410 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001411 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001412
Michael Foordf7c41582012-06-10 20:36:32 +01001413
1414 def start(self):
1415 """Activate a patch, returning any created mock."""
1416 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001417 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001418 return result
1419
1420
1421 def stop(self):
1422 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001423 try:
1424 self._active_patches.remove(self)
1425 except ValueError:
1426 # If the patch hasn't been started this will fail
1427 pass
1428
Michael Foordf7c41582012-06-10 20:36:32 +01001429 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001430
1431
1432
1433def _get_target(target):
1434 try:
1435 target, attribute = target.rsplit('.', 1)
1436 except (TypeError, ValueError):
1437 raise TypeError("Need a valid target to patch. You supplied: %r" %
1438 (target,))
1439 getter = lambda: _importer(target)
1440 return getter, attribute
1441
1442
1443def _patch_object(
1444 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001445 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001446 new_callable=None, **kwargs
1447 ):
1448 """
Michael Foord345266a2012-03-14 12:24:34 -07001449 patch the named member (`attribute`) on an object (`target`) with a mock
1450 object.
1451
1452 `patch.object` can be used as a decorator, class decorator or a context
1453 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1454 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1455 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1456 the mock object it creates.
1457
1458 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1459 for choosing which methods to wrap.
1460 """
1461 getter = lambda: target
1462 return _patch(
1463 getter, attribute, new, spec, create,
1464 spec_set, autospec, new_callable, kwargs
1465 )
1466
1467
Michael Foord50a8c0e2012-03-25 18:57:58 +01001468def _patch_multiple(target, spec=None, create=False, spec_set=None,
1469 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001470 """Perform multiple patches in a single call. It takes the object to be
1471 patched (either as an object or a string to fetch the object by importing)
1472 and keyword arguments for the patches::
1473
1474 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1475 ...
1476
1477 Use `DEFAULT` as the value if you want `patch.multiple` to create
1478 mocks for you. In this case the created mocks are passed into a decorated
1479 function by keyword, and a dictionary is returned when `patch.multiple` is
1480 used as a context manager.
1481
1482 `patch.multiple` can be used as a decorator, class decorator or a context
1483 manager. The arguments `spec`, `spec_set`, `create`,
1484 `autospec` and `new_callable` have the same meaning as for `patch`. These
1485 arguments will be applied to *all* patches done by `patch.multiple`.
1486
1487 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1488 for choosing which methods to wrap.
1489 """
1490 if type(target) is str:
1491 getter = lambda: _importer(target)
1492 else:
1493 getter = lambda: target
1494
1495 if not kwargs:
1496 raise ValueError(
1497 'Must supply at least one keyword argument with patch.multiple'
1498 )
1499 # need to wrap in a list for python 3, where items is a view
1500 items = list(kwargs.items())
1501 attribute, new = items[0]
1502 patcher = _patch(
1503 getter, attribute, new, spec, create, spec_set,
1504 autospec, new_callable, {}
1505 )
1506 patcher.attribute_name = attribute
1507 for attribute, new in items[1:]:
1508 this_patcher = _patch(
1509 getter, attribute, new, spec, create, spec_set,
1510 autospec, new_callable, {}
1511 )
1512 this_patcher.attribute_name = attribute
1513 patcher.additional_patchers.append(this_patcher)
1514 return patcher
1515
1516
1517def patch(
1518 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001519 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001520 ):
1521 """
1522 `patch` acts as a function decorator, class decorator or a context
1523 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001524 is patched with a `new` object. When the function/with statement exits
1525 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001526
Michael Foord54b3db82012-03-28 15:08:08 +01001527 If `new` is omitted, then the target is replaced with a
1528 `MagicMock`. If `patch` is used as a decorator and `new` is
1529 omitted, the created mock is passed in as an extra argument to the
1530 decorated function. If `patch` is used as a context manager the created
1531 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001532
Michael Foord54b3db82012-03-28 15:08:08 +01001533 `target` should be a string in the form `'package.module.ClassName'`. The
1534 `target` is imported and the specified object replaced with the `new`
1535 object, so the `target` must be importable from the environment you are
1536 calling `patch` from. The target is imported when the decorated function
1537 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001538
1539 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1540 if patch is creating one for you.
1541
1542 In addition you can pass `spec=True` or `spec_set=True`, which causes
1543 patch to pass in the object being mocked as the spec/spec_set object.
1544
1545 `new_callable` allows you to specify a different class, or callable object,
1546 that will be called to create the `new` object. By default `MagicMock` is
1547 used.
1548
1549 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001550 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001551 All attributes of the mock will also have the spec of the corresponding
1552 attribute of the object being replaced. Methods and functions being
1553 mocked will have their arguments checked and will raise a `TypeError` if
1554 they are called with the wrong signature. For mocks replacing a class,
1555 their return value (the 'instance') will have the same spec as the class.
1556
1557 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1558 arbitrary object as the spec instead of the one being replaced.
1559
1560 By default `patch` will fail to replace attributes that don't exist. If
1561 you pass in `create=True`, and the attribute doesn't exist, patch will
1562 create the attribute for you when the patched function is called, and
1563 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001564 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001565 default because it can be dangerous. With it switched on you can write
1566 passing tests against APIs that don't actually exist!
1567
1568 Patch can be used as a `TestCase` class decorator. It works by
1569 decorating each test method in the class. This reduces the boilerplate
1570 code when your test methods share a common patchings set. `patch` finds
1571 tests by looking for method names that start with `patch.TEST_PREFIX`.
1572 By default this is `test`, which matches the way `unittest` finds tests.
1573 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1574
1575 Patch can be used as a context manager, with the with statement. Here the
1576 patching applies to the indented block after the with statement. If you
1577 use "as" then the patched object will be bound to the name after the
1578 "as"; very useful if `patch` is creating a mock object for you.
1579
1580 `patch` takes arbitrary keyword arguments. These will be passed to
1581 the `Mock` (or `new_callable`) on construction.
1582
1583 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1584 available for alternate use-cases.
1585 """
1586 getter, attribute = _get_target(target)
1587 return _patch(
1588 getter, attribute, new, spec, create,
1589 spec_set, autospec, new_callable, kwargs
1590 )
1591
1592
1593class _patch_dict(object):
1594 """
1595 Patch a dictionary, or dictionary like object, and restore the dictionary
1596 to its original state after the test.
1597
1598 `in_dict` can be a dictionary or a mapping like container. If it is a
1599 mapping then it must at least support getting, setting and deleting items
1600 plus iterating over keys.
1601
1602 `in_dict` can also be a string specifying the name of the dictionary, which
1603 will then be fetched by importing it.
1604
1605 `values` can be a dictionary of values to set in the dictionary. `values`
1606 can also be an iterable of `(key, value)` pairs.
1607
1608 If `clear` is True then the dictionary will be cleared before the new
1609 values are set.
1610
1611 `patch.dict` can also be called with arbitrary keyword arguments to set
1612 values in the dictionary::
1613
1614 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1615 ...
1616
1617 `patch.dict` can be used as a context manager, decorator or class
1618 decorator. When used as a class decorator `patch.dict` honours
1619 `patch.TEST_PREFIX` for choosing which methods to wrap.
1620 """
1621
1622 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1623 if isinstance(in_dict, str):
1624 in_dict = _importer(in_dict)
1625 self.in_dict = in_dict
1626 # support any argument supported by dict(...) constructor
1627 self.values = dict(values)
1628 self.values.update(kwargs)
1629 self.clear = clear
1630 self._original = None
1631
1632
1633 def __call__(self, f):
1634 if isinstance(f, type):
1635 return self.decorate_class(f)
1636 @wraps(f)
1637 def _inner(*args, **kw):
1638 self._patch_dict()
1639 try:
1640 return f(*args, **kw)
1641 finally:
1642 self._unpatch_dict()
1643
1644 return _inner
1645
1646
1647 def decorate_class(self, klass):
1648 for attr in dir(klass):
1649 attr_value = getattr(klass, attr)
1650 if (attr.startswith(patch.TEST_PREFIX) and
1651 hasattr(attr_value, "__call__")):
1652 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1653 decorated = decorator(attr_value)
1654 setattr(klass, attr, decorated)
1655 return klass
1656
1657
1658 def __enter__(self):
1659 """Patch the dict."""
1660 self._patch_dict()
1661
1662
1663 def _patch_dict(self):
1664 values = self.values
1665 in_dict = self.in_dict
1666 clear = self.clear
1667
1668 try:
1669 original = in_dict.copy()
1670 except AttributeError:
1671 # dict like object with no copy method
1672 # must support iteration over keys
1673 original = {}
1674 for key in in_dict:
1675 original[key] = in_dict[key]
1676 self._original = original
1677
1678 if clear:
1679 _clear_dict(in_dict)
1680
1681 try:
1682 in_dict.update(values)
1683 except AttributeError:
1684 # dict like object with no update method
1685 for key in values:
1686 in_dict[key] = values[key]
1687
1688
1689 def _unpatch_dict(self):
1690 in_dict = self.in_dict
1691 original = self._original
1692
1693 _clear_dict(in_dict)
1694
1695 try:
1696 in_dict.update(original)
1697 except AttributeError:
1698 for key in original:
1699 in_dict[key] = original[key]
1700
1701
1702 def __exit__(self, *args):
1703 """Unpatch the dict."""
1704 self._unpatch_dict()
1705 return False
1706
1707 start = __enter__
1708 stop = __exit__
1709
1710
1711def _clear_dict(in_dict):
1712 try:
1713 in_dict.clear()
1714 except AttributeError:
1715 keys = list(in_dict)
1716 for key in keys:
1717 del in_dict[key]
1718
1719
Michael Foordf7c41582012-06-10 20:36:32 +01001720def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001721 """Stop all active patches. LIFO to unroll nested patches."""
1722 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001723 patch.stop()
1724
1725
Michael Foord345266a2012-03-14 12:24:34 -07001726patch.object = _patch_object
1727patch.dict = _patch_dict
1728patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001729patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001730patch.TEST_PREFIX = 'test'
1731
1732magic_methods = (
1733 "lt le gt ge eq ne "
1734 "getitem setitem delitem "
1735 "len contains iter "
1736 "hash str sizeof "
1737 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001738 # we added divmod and rdivmod here instead of numerics
1739 # because there is no idivmod
1740 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001741 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001742 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001743 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001744 "fspath "
Michael Foord345266a2012-03-14 12:24:34 -07001745)
1746
Michael Foordd2623d72014-04-14 11:23:48 -04001747numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001748 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001749)
Michael Foord345266a2012-03-14 12:24:34 -07001750inplace = ' '.join('i%s' % n for n in numerics.split())
1751right = ' '.join('r%s' % n for n in numerics.split())
1752
1753# not including __prepare__, __instancecheck__, __subclasscheck__
1754# (as they are metaclass methods)
1755# __del__ is not supported at all as it causes problems if it exists
1756
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001757_non_defaults = {
1758 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1759 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1760 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1761 '__repr__', '__dir__', '__subclasses__', '__format__',
Serhiy Storchaka5943ea72016-06-19 18:30:43 +03001762 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001763}
Michael Foord345266a2012-03-14 12:24:34 -07001764
1765
1766def _get_method(name, func):
1767 "Turns a callable object (like a mock) into a real function"
1768 def method(self, *args, **kw):
1769 return func(self, *args, **kw)
1770 method.__name__ = name
1771 return method
1772
1773
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001774_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001775 '__%s__' % method for method in
1776 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001777}
Michael Foord345266a2012-03-14 12:24:34 -07001778
1779_all_magics = _magics | _non_defaults
1780
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001781_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001782 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001783 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001784 '__instancecheck__', '__subclasscheck__',
1785 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001786}
Michael Foord345266a2012-03-14 12:24:34 -07001787
1788_calculate_return_value = {
1789 '__hash__': lambda self: object.__hash__(self),
1790 '__str__': lambda self: object.__str__(self),
1791 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001792 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001793}
1794
1795_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001796 '__lt__': NotImplemented,
1797 '__gt__': NotImplemented,
1798 '__le__': NotImplemented,
1799 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001800 '__int__': 1,
1801 '__contains__': False,
1802 '__len__': 0,
1803 '__exit__': False,
1804 '__complex__': 1j,
1805 '__float__': 1.0,
1806 '__bool__': True,
1807 '__index__': 1,
1808}
1809
1810
1811def _get_eq(self):
1812 def __eq__(other):
1813 ret_val = self.__eq__._mock_return_value
1814 if ret_val is not DEFAULT:
1815 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001816 if self is other:
1817 return True
1818 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001819 return __eq__
1820
1821def _get_ne(self):
1822 def __ne__(other):
1823 if self.__ne__._mock_return_value is not DEFAULT:
1824 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001825 if self is other:
1826 return False
1827 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001828 return __ne__
1829
1830def _get_iter(self):
1831 def __iter__():
1832 ret_val = self.__iter__._mock_return_value
1833 if ret_val is DEFAULT:
1834 return iter([])
1835 # if ret_val was already an iterator, then calling iter on it should
1836 # return the iterator unchanged
1837 return iter(ret_val)
1838 return __iter__
1839
1840_side_effect_methods = {
1841 '__eq__': _get_eq,
1842 '__ne__': _get_ne,
1843 '__iter__': _get_iter,
1844}
1845
1846
1847
1848def _set_return_value(mock, method, name):
1849 fixed = _return_values.get(name, DEFAULT)
1850 if fixed is not DEFAULT:
1851 method.return_value = fixed
1852 return
1853
1854 return_calulator = _calculate_return_value.get(name)
1855 if return_calulator is not None:
1856 try:
1857 return_value = return_calulator(mock)
1858 except AttributeError:
1859 # XXXX why do we return AttributeError here?
1860 # set it as a side_effect instead?
1861 return_value = AttributeError(name)
1862 method.return_value = return_value
1863 return
1864
1865 side_effector = _side_effect_methods.get(name)
1866 if side_effector is not None:
1867 method.side_effect = side_effector(mock)
1868
1869
1870
1871class MagicMixin(object):
1872 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001873 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001874 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001875 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001876
1877
1878 def _mock_set_magics(self):
1879 these_magics = _magics
1880
Łukasz Langaa468db92015-04-13 23:12:42 -07001881 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001882 these_magics = _magics.intersection(self._mock_methods)
1883
1884 remove_magics = set()
1885 remove_magics = _magics - these_magics
1886
1887 for entry in remove_magics:
1888 if entry in type(self).__dict__:
1889 # remove unneeded magic methods
1890 delattr(self, entry)
1891
1892 # don't overwrite existing attributes if called a second time
1893 these_magics = these_magics - set(type(self).__dict__)
1894
1895 _type = type(self)
1896 for entry in these_magics:
1897 setattr(_type, entry, MagicProxy(entry, self))
1898
1899
1900
1901class NonCallableMagicMock(MagicMixin, NonCallableMock):
1902 """A version of `MagicMock` that isn't callable."""
1903 def mock_add_spec(self, spec, spec_set=False):
1904 """Add a spec to a mock. `spec` can either be an object or a
1905 list of strings. Only attributes on the `spec` can be fetched as
1906 attributes from the mock.
1907
1908 If `spec_set` is True then only attributes on the spec can be set."""
1909 self._mock_add_spec(spec, spec_set)
1910 self._mock_set_magics()
1911
1912
1913
1914class MagicMock(MagicMixin, Mock):
1915 """
1916 MagicMock is a subclass of Mock with default implementations
1917 of most of the magic methods. You can use MagicMock without having to
1918 configure the magic methods yourself.
1919
1920 If you use the `spec` or `spec_set` arguments then *only* magic
1921 methods that exist in the spec will be created.
1922
1923 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1924 """
1925 def mock_add_spec(self, spec, spec_set=False):
1926 """Add a spec to a mock. `spec` can either be an object or a
1927 list of strings. Only attributes on the `spec` can be fetched as
1928 attributes from the mock.
1929
1930 If `spec_set` is True then only attributes on the spec can be set."""
1931 self._mock_add_spec(spec, spec_set)
1932 self._mock_set_magics()
1933
1934
1935
1936class MagicProxy(object):
1937 def __init__(self, name, parent):
1938 self.name = name
1939 self.parent = parent
1940
1941 def __call__(self, *args, **kwargs):
1942 m = self.create_mock()
1943 return m(*args, **kwargs)
1944
1945 def create_mock(self):
1946 entry = self.name
1947 parent = self.parent
1948 m = parent._get_child_mock(name=entry, _new_name=entry,
1949 _new_parent=parent)
1950 setattr(parent, entry, m)
1951 _set_return_value(parent, m, entry)
1952 return m
1953
1954 def __get__(self, obj, _type=None):
1955 return self.create_mock()
1956
1957
1958
1959class _ANY(object):
1960 "A helper object that compares equal to everything."
1961
1962 def __eq__(self, other):
1963 return True
1964
1965 def __ne__(self, other):
1966 return False
1967
1968 def __repr__(self):
1969 return '<ANY>'
1970
1971ANY = _ANY()
1972
1973
1974
1975def _format_call_signature(name, args, kwargs):
1976 message = '%s(%%s)' % name
1977 formatted_args = ''
1978 args_string = ', '.join([repr(arg) for arg in args])
1979 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301980 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001981 ])
1982 if args_string:
1983 formatted_args = args_string
1984 if kwargs_string:
1985 if formatted_args:
1986 formatted_args += ', '
1987 formatted_args += kwargs_string
1988
1989 return message % formatted_args
1990
1991
1992
1993class _Call(tuple):
1994 """
1995 A tuple for holding the results of a call to a mock, either in the form
1996 `(args, kwargs)` or `(name, args, kwargs)`.
1997
1998 If args or kwargs are empty then a call tuple will compare equal to
1999 a tuple without those values. This makes comparisons less verbose::
2000
2001 _Call(('name', (), {})) == ('name',)
2002 _Call(('name', (1,), {})) == ('name', (1,))
2003 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2004
2005 The `_Call` object provides a useful shortcut for comparing with call::
2006
2007 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2008 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2009
2010 If the _Call has no name then it will match any name.
2011 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002012 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002013 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002014 args = ()
2015 kwargs = {}
2016 _len = len(value)
2017 if _len == 3:
2018 name, args, kwargs = value
2019 elif _len == 2:
2020 first, second = value
2021 if isinstance(first, str):
2022 name = first
2023 if isinstance(second, tuple):
2024 args = second
2025 else:
2026 kwargs = second
2027 else:
2028 args, kwargs = first, second
2029 elif _len == 1:
2030 value, = value
2031 if isinstance(value, str):
2032 name = value
2033 elif isinstance(value, tuple):
2034 args = value
2035 else:
2036 kwargs = value
2037
2038 if two:
2039 return tuple.__new__(cls, (args, kwargs))
2040
2041 return tuple.__new__(cls, (name, args, kwargs))
2042
2043
2044 def __init__(self, value=(), name=None, parent=None, two=False,
2045 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002046 self._mock_name = name
2047 self._mock_parent = parent
2048 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002049
2050
2051 def __eq__(self, other):
2052 if other is ANY:
2053 return True
2054 try:
2055 len_other = len(other)
2056 except TypeError:
2057 return False
2058
2059 self_name = ''
2060 if len(self) == 2:
2061 self_args, self_kwargs = self
2062 else:
2063 self_name, self_args, self_kwargs = self
2064
Andrew Dunaie63e6172018-12-04 11:08:45 +02002065 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2066 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002067 return False
2068
Michael Foord345266a2012-03-14 12:24:34 -07002069 other_name = ''
2070 if len_other == 0:
2071 other_args, other_kwargs = (), {}
2072 elif len_other == 3:
2073 other_name, other_args, other_kwargs = other
2074 elif len_other == 1:
2075 value, = other
2076 if isinstance(value, tuple):
2077 other_args = value
2078 other_kwargs = {}
2079 elif isinstance(value, str):
2080 other_name = value
2081 other_args, other_kwargs = (), {}
2082 else:
2083 other_args = ()
2084 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002085 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002086 # could be (name, args) or (name, kwargs) or (args, kwargs)
2087 first, second = other
2088 if isinstance(first, str):
2089 other_name = first
2090 if isinstance(second, tuple):
2091 other_args, other_kwargs = second, {}
2092 else:
2093 other_args, other_kwargs = (), second
2094 else:
2095 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002096 else:
2097 return False
Michael Foord345266a2012-03-14 12:24:34 -07002098
2099 if self_name and other_name != self_name:
2100 return False
2101
2102 # this order is important for ANY to work!
2103 return (other_args, other_kwargs) == (self_args, self_kwargs)
2104
2105
Berker Peksagce913872016-03-28 00:30:02 +03002106 __ne__ = object.__ne__
2107
2108
Michael Foord345266a2012-03-14 12:24:34 -07002109 def __call__(self, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002110 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002111 return _Call(('', args, kwargs), name='()')
2112
Andrew Dunaie63e6172018-12-04 11:08:45 +02002113 name = self._mock_name + '()'
2114 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002115
2116
2117 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002118 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002119 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002120 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002121 return _Call(name=name, parent=self, from_kall=False)
2122
2123
Kushal Dasa37b9582014-09-16 18:33:37 +05302124 def count(self, *args, **kwargs):
2125 return self.__getattr__('count')(*args, **kwargs)
2126
2127 def index(self, *args, **kwargs):
2128 return self.__getattr__('index')(*args, **kwargs)
2129
Michael Foord345266a2012-03-14 12:24:34 -07002130 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002131 if not self._mock_from_kall:
2132 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002133 if name.startswith('()'):
2134 name = 'call%s' % name
2135 return name
2136
2137 if len(self) == 2:
2138 name = 'call'
2139 args, kwargs = self
2140 else:
2141 name, args, kwargs = self
2142 if not name:
2143 name = 'call'
2144 elif not name.startswith('()'):
2145 name = 'call.%s' % name
2146 else:
2147 name = 'call%s' % name
2148 return _format_call_signature(name, args, kwargs)
2149
2150
2151 def call_list(self):
2152 """For a call object that represents multiple calls, `call_list`
2153 returns a list of all the intermediate calls as well as the
2154 final call."""
2155 vals = []
2156 thing = self
2157 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002158 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002159 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002160 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002161 return _CallList(reversed(vals))
2162
2163
2164call = _Call(from_kall=False)
2165
2166
2167
2168def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2169 _name=None, **kwargs):
2170 """Create a mock object using another object as a spec. Attributes on the
2171 mock will use the corresponding attribute on the `spec` object as their
2172 spec.
2173
2174 Functions or methods being mocked will have their arguments checked
2175 to check that they are called with the correct signature.
2176
2177 If `spec_set` is True then attempting to set attributes that don't exist
2178 on the spec object will raise an `AttributeError`.
2179
2180 If a class is used as a spec then the return value of the mock (the
2181 instance of the class) will have the same spec. You can use a class as the
2182 spec for an instance object by passing `instance=True`. The returned mock
2183 will only be callable if instances of the mock are callable.
2184
2185 `create_autospec` also takes arbitrary keyword arguments that are passed to
2186 the constructor of the created mock."""
2187 if _is_list(spec):
2188 # can't pass a list instance to the mock constructor as it will be
2189 # interpreted as a list of strings
2190 spec = type(spec)
2191
2192 is_type = isinstance(spec, type)
2193
2194 _kwargs = {'spec': spec}
2195 if spec_set:
2196 _kwargs = {'spec_set': spec}
2197 elif spec is None:
2198 # None we mock with a normal mock without a spec
2199 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002200 if _kwargs and instance:
2201 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002202
2203 _kwargs.update(kwargs)
2204
2205 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002206 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002207 # descriptors don't have a spec
2208 # because we don't know what type they return
2209 _kwargs = {}
2210 elif not _callable(spec):
2211 Klass = NonCallableMagicMock
2212 elif is_type and instance and not _instance_callable(spec):
2213 Klass = NonCallableMagicMock
2214
Kushal Das484f8a82014-04-16 01:05:50 +05302215 _name = _kwargs.pop('name', _name)
2216
Michael Foord345266a2012-03-14 12:24:34 -07002217 _new_name = _name
2218 if _parent is None:
2219 # for a top level object no _new_name should be set
2220 _new_name = ''
2221
2222 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2223 name=_name, **_kwargs)
2224
2225 if isinstance(spec, FunctionTypes):
2226 # should only happen at the top level because we don't
2227 # recurse for functions
2228 mock = _set_signature(mock, spec)
2229 else:
2230 _check_signature(spec, mock, is_type, instance)
2231
2232 if _parent is not None and not instance:
2233 _parent._mock_children[_name] = mock
2234
2235 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002236 mock.return_value = create_autospec(spec, spec_set, instance=True,
2237 _name='()', _parent=mock)
2238
2239 for entry in dir(spec):
2240 if _is_magic(entry):
2241 # MagicMock already does the useful magic methods for us
2242 continue
2243
Michael Foord345266a2012-03-14 12:24:34 -07002244 # XXXX do we need a better way of getting attributes without
2245 # triggering code execution (?) Probably not - we need the actual
2246 # object to mock it so we would rather trigger a property than mock
2247 # the property descriptor. Likewise we want to mock out dynamically
2248 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002249 # XXXX what about attributes that raise exceptions other than
2250 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002251 # we could be resilient against it, or catch and propagate the
2252 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002253 try:
2254 original = getattr(spec, entry)
2255 except AttributeError:
2256 continue
Michael Foord345266a2012-03-14 12:24:34 -07002257
2258 kwargs = {'spec': original}
2259 if spec_set:
2260 kwargs = {'spec_set': original}
2261
2262 if not isinstance(original, FunctionTypes):
2263 new = _SpecState(original, spec_set, mock, entry, instance)
2264 mock._mock_children[entry] = new
2265 else:
2266 parent = mock
2267 if isinstance(spec, FunctionTypes):
2268 parent = mock.mock
2269
Michael Foord345266a2012-03-14 12:24:34 -07002270 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002271 kwargs['_eat_self'] = skipfirst
2272 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2273 _new_parent=parent,
2274 **kwargs)
2275 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002276 _check_signature(original, new, skipfirst=skipfirst)
2277
2278 # so functions created with _set_signature become instance attributes,
2279 # *plus* their underlying mock exists in _mock_children of the parent
2280 # mock. Adding to _mock_children may be unnecessary where we are also
2281 # setting as an instance attribute?
2282 if isinstance(new, FunctionTypes):
2283 setattr(mock, entry, new)
2284
2285 return mock
2286
2287
2288def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002289 """
2290 Return whether we should skip the first argument on spec's `entry`
2291 attribute.
2292 """
Michael Foord345266a2012-03-14 12:24:34 -07002293 if not isinstance(spec, type):
2294 if entry in getattr(spec, '__dict__', {}):
2295 # instance attribute - shouldn't skip
2296 return False
Michael Foord345266a2012-03-14 12:24:34 -07002297 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002298
2299 for klass in spec.__mro__:
2300 result = klass.__dict__.get(entry, DEFAULT)
2301 if result is DEFAULT:
2302 continue
2303 if isinstance(result, (staticmethod, classmethod)):
2304 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002305 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2306 # Normal method => skip if looked up on type
2307 # (if looked up on instance, self is already skipped)
2308 return is_type
2309 else:
2310 return False
Michael Foord345266a2012-03-14 12:24:34 -07002311
2312 # shouldn't get here unless function is a dynamically provided attribute
2313 # XXXX untested behaviour
2314 return is_type
2315
2316
2317def _get_class(obj):
2318 try:
2319 return obj.__class__
2320 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002321 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002322 return type(obj)
2323
2324
2325class _SpecState(object):
2326
2327 def __init__(self, spec, spec_set=False, parent=None,
2328 name=None, ids=None, instance=False):
2329 self.spec = spec
2330 self.ids = ids
2331 self.spec_set = spec_set
2332 self.parent = parent
2333 self.instance = instance
2334 self.name = name
2335
2336
2337FunctionTypes = (
2338 # python function
2339 type(create_autospec),
2340 # instance method
2341 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002342)
2343
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002344MethodWrapperTypes = (
2345 type(ANY.__eq__.__get__),
2346)
2347
Michael Foord345266a2012-03-14 12:24:34 -07002348
Michael Foorda74561a2012-03-25 19:03:13 +01002349file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002350
Michael Foord04cbe0c2013-03-19 17:22:51 -07002351def _iterate_read_data(read_data):
2352 # Helper for mock_open:
2353 # Retrieve lines from read_data via a generator so that separate calls to
2354 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002355 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2356 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002357
Berker Peksag86b34da2015-08-06 13:15:51 +03002358 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002359 # If the last line ended in a newline, the list comprehension will have an
2360 # extra entry that's just a newline. Remove this.
2361 data_as_list = data_as_list[:-1]
2362 else:
2363 # If there wasn't an extra newline by itself, then the file being
2364 # emulated doesn't have a newline to end the last line remove the
2365 # newline that our naive format() added
2366 data_as_list[-1] = data_as_list[-1][:-1]
2367
2368 for line in data_as_list:
2369 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002370
Robert Collins5329aaa2015-07-17 20:08:45 +12002371
Michael Foord0dccf652012-03-25 19:11:50 +01002372def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002373 """
2374 A helper function to create a mock to replace the use of `open`. It works
2375 for `open` called directly or used as a context manager.
2376
2377 The `mock` argument is the mock object to configure. If `None` (the
2378 default) then a `MagicMock` will be created for you, with the API limited
2379 to methods or attributes available on standard file handles.
2380
Xtreak71f82a22018-12-20 21:30:21 +05302381 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002382 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002383 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002384 def _readlines_side_effect(*args, **kwargs):
2385 if handle.readlines.return_value is not None:
2386 return handle.readlines.return_value
2387 return list(_state[0])
2388
2389 def _read_side_effect(*args, **kwargs):
2390 if handle.read.return_value is not None:
2391 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002392 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002393
2394 def _readline_side_effect():
Tony Flury20870232018-09-12 23:21:16 +01002395 yield from _iter_side_effect()
2396 while True:
2397 yield type(read_data)()
2398
2399 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002400 if handle.readline.return_value is not None:
2401 while True:
2402 yield handle.readline.return_value
2403 for line in _state[0]:
2404 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002405
Michael Foorda74561a2012-03-25 19:03:13 +01002406 global file_spec
2407 if file_spec is None:
2408 import _io
2409 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2410
Michael Foord345266a2012-03-14 12:24:34 -07002411 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002412 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002413
Robert Collinsca647ef2015-07-24 03:48:20 +12002414 handle = MagicMock(spec=file_spec)
2415 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002416
Robert Collinsca647ef2015-07-24 03:48:20 +12002417 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002418
Robert Collinsca647ef2015-07-24 03:48:20 +12002419 handle.write.return_value = None
2420 handle.read.return_value = None
2421 handle.readline.return_value = None
2422 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002423
Robert Collinsca647ef2015-07-24 03:48:20 +12002424 handle.read.side_effect = _read_side_effect
2425 _state[1] = _readline_side_effect()
2426 handle.readline.side_effect = _state[1]
2427 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002428 handle.__iter__.side_effect = _iter_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002429
Robert Collinsca647ef2015-07-24 03:48:20 +12002430 def reset_data(*args, **kwargs):
2431 _state[0] = _iterate_read_data(read_data)
2432 if handle.readline.side_effect == _state[1]:
2433 # Only reset the side effect if the user hasn't overridden it.
2434 _state[1] = _readline_side_effect()
2435 handle.readline.side_effect = _state[1]
2436 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002437
Robert Collinsca647ef2015-07-24 03:48:20 +12002438 mock.side_effect = reset_data
2439 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002440 return mock
2441
2442
2443class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002444 """
2445 A mock intended to be used as a property, or other descriptor, on a class.
2446 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2447 a return value when it is fetched.
2448
2449 Fetching a `PropertyMock` instance from an object calls the mock, with
2450 no args. Setting it calls the mock with the value being set.
2451 """
Michael Foordc2870622012-04-13 16:57:22 +01002452 def _get_child_mock(self, **kwargs):
2453 return MagicMock(**kwargs)
2454
Michael Foord345266a2012-03-14 12:24:34 -07002455 def __get__(self, obj, obj_type):
2456 return self()
2457 def __set__(self, obj, val):
2458 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002459
2460
2461def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002462 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002463
2464 Given an input Mock, seals it to ensure no further mocks will be generated
2465 when accessing an attribute that was not already defined.
2466
Mario Corchero96200eb2018-10-19 22:57:37 +01002467 The operation recursively seals the mock passed in, meaning that
2468 the mock itself, any mocks generated by accessing one of its attributes,
2469 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002470 """
2471 mock._mock_sealed = True
2472 for attr in dir(mock):
2473 try:
2474 m = getattr(mock, attr)
2475 except AttributeError:
2476 continue
2477 if not isinstance(m, NonCallableMock):
2478 continue
2479 if m._mock_new_parent is mock:
2480 seal(m)