blob: 2ccf0d82ce23bd25e712d7eb90bb91a60b3a62ff [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):
Xtreak9c3f2842019-02-26 03:16:34 +0530324 # function passed to create_autospec will have mock
325 # attribute attached to which parent must be set
326 if isinstance(value, FunctionTypes):
327 try:
328 value = value.mock
329 except AttributeError:
330 pass
331
Michael Foord345266a2012-03-14 12:24:34 -0700332 if not _is_instance_mock(value):
333 return False
334 if ((value._mock_name or value._mock_new_name) or
335 (value._mock_parent is not None) or
336 (value._mock_new_parent is not None)):
337 return False
338
339 _parent = parent
340 while _parent is not None:
341 # setting a mock (value) as a child or return value of itself
342 # should not modify the mock
343 if _parent is value:
344 return False
345 _parent = _parent._mock_new_parent
346
347 if new_name:
348 value._mock_new_parent = parent
349 value._mock_new_name = new_name
350 if name:
351 value._mock_parent = parent
352 value._mock_name = name
353 return True
354
Michael Foord01bafdc2014-04-14 16:09:42 -0400355# Internal class to identify if we wrapped an iterator object or not.
356class _MockIter(object):
357 def __init__(self, obj):
358 self.obj = iter(obj)
359 def __iter__(self):
360 return self
361 def __next__(self):
362 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700363
364class Base(object):
365 _mock_return_value = DEFAULT
366 _mock_side_effect = None
367 def __init__(self, *args, **kwargs):
368 pass
369
370
371
372class NonCallableMock(Base):
373 """A non-callable version of `Mock`"""
374
375 def __new__(cls, *args, **kw):
376 # every instance has its own class
377 # so we can create magic methods on the
378 # class without stomping on other mocks
379 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
380 instance = object.__new__(new)
381 return instance
382
383
384 def __init__(
385 self, spec=None, wraps=None, name=None, spec_set=None,
386 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530387 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700388 ):
389 if _new_parent is None:
390 _new_parent = parent
391
392 __dict__ = self.__dict__
393 __dict__['_mock_parent'] = parent
394 __dict__['_mock_name'] = name
395 __dict__['_mock_new_name'] = _new_name
396 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100397 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700398
399 if spec_set is not None:
400 spec = spec_set
401 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100402 if _eat_self is None:
403 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700404
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100405 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700406
407 __dict__['_mock_children'] = {}
408 __dict__['_mock_wraps'] = wraps
409 __dict__['_mock_delegate'] = None
410
411 __dict__['_mock_called'] = False
412 __dict__['_mock_call_args'] = None
413 __dict__['_mock_call_count'] = 0
414 __dict__['_mock_call_args_list'] = _CallList()
415 __dict__['_mock_mock_calls'] = _CallList()
416
417 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530418 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700419
420 if kwargs:
421 self.configure_mock(**kwargs)
422
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000423 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700424 spec, wraps, name, spec_set, parent,
425 _spec_state
426 )
427
428
429 def attach_mock(self, mock, attribute):
430 """
431 Attach a mock as an attribute of this one, replacing its name and
432 parent. Calls to the attached mock will be recorded in the
433 `method_calls` and `mock_calls` attributes of this one."""
434 mock._mock_parent = None
435 mock._mock_new_parent = None
436 mock._mock_name = ''
437 mock._mock_new_name = None
438
439 setattr(self, attribute, mock)
440
441
442 def mock_add_spec(self, spec, spec_set=False):
443 """Add a spec to a mock. `spec` can either be an object or a
444 list of strings. Only attributes on the `spec` can be fetched as
445 attributes from the mock.
446
447 If `spec_set` is True then only attributes on the spec can be set."""
448 self._mock_add_spec(spec, spec_set)
449
450
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100451 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
452 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700453 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100454 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700455
456 if spec is not None and not _is_list(spec):
457 if isinstance(spec, type):
458 _spec_class = spec
459 else:
460 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100461 res = _get_signature_object(spec,
462 _spec_as_instance, _eat_self)
463 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700464
465 spec = dir(spec)
466
467 __dict__ = self.__dict__
468 __dict__['_spec_class'] = _spec_class
469 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100470 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700471 __dict__['_mock_methods'] = spec
472
473
474 def __get_return_value(self):
475 ret = self._mock_return_value
476 if self._mock_delegate is not None:
477 ret = self._mock_delegate.return_value
478
479 if ret is DEFAULT:
480 ret = self._get_child_mock(
481 _new_parent=self, _new_name='()'
482 )
483 self.return_value = ret
484 return ret
485
486
487 def __set_return_value(self, value):
488 if self._mock_delegate is not None:
489 self._mock_delegate.return_value = value
490 else:
491 self._mock_return_value = value
492 _check_and_set_parent(self, value, None, '()')
493
494 __return_value_doc = "The value to be returned when the mock is called."
495 return_value = property(__get_return_value, __set_return_value,
496 __return_value_doc)
497
498
499 @property
500 def __class__(self):
501 if self._spec_class is None:
502 return type(self)
503 return self._spec_class
504
505 called = _delegating_property('called')
506 call_count = _delegating_property('call_count')
507 call_args = _delegating_property('call_args')
508 call_args_list = _delegating_property('call_args_list')
509 mock_calls = _delegating_property('mock_calls')
510
511
512 def __get_side_effect(self):
513 delegated = self._mock_delegate
514 if delegated is None:
515 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400516 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200517 if (sf is not None and not callable(sf)
518 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400519 sf = _MockIter(sf)
520 delegated.side_effect = sf
521 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700522
523 def __set_side_effect(self, value):
524 value = _try_iter(value)
525 delegated = self._mock_delegate
526 if delegated is None:
527 self._mock_side_effect = value
528 else:
529 delegated.side_effect = value
530
531 side_effect = property(__get_side_effect, __set_side_effect)
532
533
Kushal Das9cd39a12016-06-02 10:20:16 -0700534 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700535 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200536 if visited is None:
537 visited = []
538 if id(self) in visited:
539 return
540 visited.append(id(self))
541
Michael Foord345266a2012-03-14 12:24:34 -0700542 self.called = False
543 self.call_args = None
544 self.call_count = 0
545 self.mock_calls = _CallList()
546 self.call_args_list = _CallList()
547 self.method_calls = _CallList()
548
Kushal Das9cd39a12016-06-02 10:20:16 -0700549 if return_value:
550 self._mock_return_value = DEFAULT
551 if side_effect:
552 self._mock_side_effect = None
553
Michael Foord345266a2012-03-14 12:24:34 -0700554 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530555 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100556 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200557 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700558
559 ret = self._mock_return_value
560 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200561 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700562
563
564 def configure_mock(self, **kwargs):
565 """Set attributes on the mock through keyword arguments.
566
567 Attributes plus return values and side effects can be set on child
568 mocks using standard dot notation and unpacking a dictionary in the
569 method call:
570
571 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
572 >>> mock.configure_mock(**attrs)"""
573 for arg, val in sorted(kwargs.items(),
574 # we sort on the number of dots so that
575 # attributes are set before we set attributes on
576 # attributes
577 key=lambda entry: entry[0].count('.')):
578 args = arg.split('.')
579 final = args.pop()
580 obj = self
581 for entry in args:
582 obj = getattr(obj, entry)
583 setattr(obj, final, val)
584
585
586 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530587 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700588 raise AttributeError(name)
589 elif self._mock_methods is not None:
590 if name not in self._mock_methods or name in _all_magics:
591 raise AttributeError("Mock object has no attribute %r" % name)
592 elif _is_magic(name):
593 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530594 if not self._mock_unsafe:
595 if name.startswith(('assert', 'assret')):
596 raise AttributeError(name)
Michael Foord345266a2012-03-14 12:24:34 -0700597
598 result = self._mock_children.get(name)
599 if result is _deleted:
600 raise AttributeError(name)
601 elif result is None:
602 wraps = None
603 if self._mock_wraps is not None:
604 # XXXX should we get the attribute without triggering code
605 # execution?
606 wraps = getattr(self._mock_wraps, name)
607
608 result = self._get_child_mock(
609 parent=self, name=name, wraps=wraps, _new_name=name,
610 _new_parent=self
611 )
612 self._mock_children[name] = result
613
614 elif isinstance(result, _SpecState):
615 result = create_autospec(
616 result.spec, result.spec_set, result.instance,
617 result.parent, result.name
618 )
619 self._mock_children[name] = result
620
621 return result
622
623
Mario Corchero552be9d2017-10-17 12:35:11 +0100624 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700625 _name_list = [self._mock_new_name]
626 _parent = self._mock_new_parent
627 last = self
628
629 dot = '.'
630 if _name_list == ['()']:
631 dot = ''
632 seen = set()
633 while _parent is not None:
634 last = _parent
635
636 _name_list.append(_parent._mock_new_name + dot)
637 dot = '.'
638 if _parent._mock_new_name == '()':
639 dot = ''
640
641 _parent = _parent._mock_new_parent
642
643 # use ids here so as not to call __hash__ on the mocks
644 if id(_parent) in seen:
645 break
646 seen.add(id(_parent))
647
648 _name_list = list(reversed(_name_list))
649 _first = last._mock_name or 'mock'
650 if len(_name_list) > 1:
651 if _name_list[1] not in ('()', '().'):
652 _first += '.'
653 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100654 return ''.join(_name_list)
655
656 def __repr__(self):
657 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700658
659 name_string = ''
660 if name not in ('mock', 'mock.'):
661 name_string = ' name=%r' % name
662
663 spec_string = ''
664 if self._spec_class is not None:
665 spec_string = ' spec=%r'
666 if self._spec_set:
667 spec_string = ' spec_set=%r'
668 spec_string = spec_string % self._spec_class.__name__
669 return "<%s%s%s id='%s'>" % (
670 type(self).__name__,
671 name_string,
672 spec_string,
673 id(self)
674 )
675
676
677 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700678 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100679 if not FILTER_DIR:
680 return object.__dir__(self)
681
Michael Foord345266a2012-03-14 12:24:34 -0700682 extras = self._mock_methods or []
683 from_type = dir(type(self))
684 from_dict = list(self.__dict__)
685
Michael Foord313f85f2012-03-25 18:16:07 +0100686 from_type = [e for e in from_type if not e.startswith('_')]
687 from_dict = [e for e in from_dict if not e.startswith('_') or
688 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700689 return sorted(set(extras + from_type + from_dict +
690 list(self._mock_children)))
691
692
693 def __setattr__(self, name, value):
694 if name in _allowed_names:
695 # property setters go through here
696 return object.__setattr__(self, name, value)
697 elif (self._spec_set and self._mock_methods is not None and
698 name not in self._mock_methods and
699 name not in self.__dict__):
700 raise AttributeError("Mock object has no attribute '%s'" % name)
701 elif name in _unsupported_magics:
702 msg = 'Attempting to set unsupported magic method %r.' % name
703 raise AttributeError(msg)
704 elif name in _all_magics:
705 if self._mock_methods is not None and name not in self._mock_methods:
706 raise AttributeError("Mock object has no attribute '%s'" % name)
707
708 if not _is_instance_mock(value):
709 setattr(type(self), name, _get_method(name, value))
710 original = value
711 value = lambda *args, **kw: original(self, *args, **kw)
712 else:
713 # only set _new_name and not name so that mock_calls is tracked
714 # but not method calls
715 _check_and_set_parent(self, value, None, name)
716 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100717 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700718 elif name == '__class__':
719 self._spec_class = value
720 return
721 else:
722 if _check_and_set_parent(self, value, name, name):
723 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100724
725 if self._mock_sealed and not hasattr(self, name):
726 mock_name = f'{self._extract_mock_name()}.{name}'
727 raise AttributeError(f'Cannot set {mock_name}')
728
Michael Foord345266a2012-03-14 12:24:34 -0700729 return object.__setattr__(self, name, value)
730
731
732 def __delattr__(self, name):
733 if name in _all_magics and name in type(self).__dict__:
734 delattr(type(self), name)
735 if name not in self.__dict__:
736 # for magic methods that are still MagicProxy objects and
737 # not set on the instance itself
738 return
739
Michael Foord345266a2012-03-14 12:24:34 -0700740 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000741 if name in self.__dict__:
742 super().__delattr__(name)
743 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700744 raise AttributeError(name)
745 if obj is not _missing:
746 del self._mock_children[name]
747 self._mock_children[name] = _deleted
748
749
Michael Foord345266a2012-03-14 12:24:34 -0700750 def _format_mock_call_signature(self, args, kwargs):
751 name = self._mock_name or 'mock'
752 return _format_call_signature(name, args, kwargs)
753
754
755 def _format_mock_failure_message(self, args, kwargs):
Susan Su2bdd5852019-02-13 18:22:29 -0800756 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700757 expected_string = self._format_mock_call_signature(args, kwargs)
758 call_args = self.call_args
759 if len(call_args) == 3:
760 call_args = call_args[1:]
761 actual_string = self._format_mock_call_signature(*call_args)
762 return message % (expected_string, actual_string)
763
764
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100765 def _call_matcher(self, _call):
766 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000767 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100768 comparison key suitable for matching with other calls.
769 This is a best effort method which relies on the spec's signature,
770 if available, or falls back on the arguments themselves.
771 """
772 sig = self._spec_signature
773 if sig is not None:
774 if len(_call) == 2:
775 name = ''
776 args, kwargs = _call
777 else:
778 name, args, kwargs = _call
779 try:
780 return name, sig.bind(*args, **kwargs)
781 except TypeError as e:
782 return e.with_traceback(None)
783 else:
784 return _call
785
Kushal Das68290f42014-04-17 01:54:07 +0530786 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530787 """assert that the mock was never called.
788 """
789 self = _mock_self
790 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100791 msg = ("Expected '%s' to not have been called. Called %s times.%s"
792 % (self._mock_name or 'mock',
793 self.call_count,
794 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530795 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100796
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100797 def assert_called(_mock_self):
798 """assert that the mock was called at least once
799 """
800 self = _mock_self
801 if self.call_count == 0:
802 msg = ("Expected '%s' to have been called." %
803 self._mock_name or 'mock')
804 raise AssertionError(msg)
805
806 def assert_called_once(_mock_self):
807 """assert that the mock was called only once.
808 """
809 self = _mock_self
810 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100811 msg = ("Expected '%s' to have been called once. Called %s times.%s"
812 % (self._mock_name or 'mock',
813 self.call_count,
814 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100815 raise AssertionError(msg)
816
Michael Foord345266a2012-03-14 12:24:34 -0700817 def assert_called_with(_mock_self, *args, **kwargs):
818 """assert that the mock was called with the specified arguments.
819
820 Raises an AssertionError if the args and keyword args passed in are
821 different to the last call to the mock."""
822 self = _mock_self
823 if self.call_args is None:
824 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800825 actual = 'not called.'
826 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
827 % (expected, actual))
828 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700829
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100830 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700831 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100832 return msg
833 expected = self._call_matcher((args, kwargs))
834 actual = self._call_matcher(self.call_args)
835 if expected != actual:
836 cause = expected if isinstance(expected, Exception) else None
837 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700838
839
840 def assert_called_once_with(_mock_self, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100841 """assert that the mock was called exactly once and that that call was
842 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700843 self = _mock_self
844 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100845 msg = ("Expected '%s' to be called once. Called %s times.%s"
846 % (self._mock_name or 'mock',
847 self.call_count,
848 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700849 raise AssertionError(msg)
850 return self.assert_called_with(*args, **kwargs)
851
852
853 def assert_has_calls(self, calls, any_order=False):
854 """assert the mock has been called with the specified calls.
855 The `mock_calls` list is checked for the calls.
856
857 If `any_order` is False (the default) then the calls must be
858 sequential. There can be extra calls before or after the
859 specified calls.
860
861 If `any_order` is True then the calls can be in any order, but
862 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100863 expected = [self._call_matcher(c) for c in calls]
864 cause = expected if isinstance(expected, Exception) else None
865 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700866 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100867 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700868 raise AssertionError(
Petter Strandmark47d94242018-10-28 21:37:10 +0100869 'Calls not found.\nExpected: %r%s'
870 % (_CallList(calls), self._calls_repr(prefix="Actual"))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100871 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700872 return
873
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100874 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700875
876 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100877 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700878 try:
879 all_calls.remove(kall)
880 except ValueError:
881 not_found.append(kall)
882 if not_found:
883 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400884 '%r does not contain all of %r in its call list, '
885 'found %r instead' % (self._mock_name or 'mock',
886 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100887 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700888
889
890 def assert_any_call(self, *args, **kwargs):
891 """assert the mock has been called with the specified arguments.
892
893 The assert passes if the mock has *ever* been called, unlike
894 `assert_called_with` and `assert_called_once_with` that only pass if
895 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100896 expected = self._call_matcher((args, kwargs))
897 actual = [self._call_matcher(c) for c in self.call_args_list]
898 if expected not in actual:
899 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700900 expected_string = self._format_mock_call_signature(args, kwargs)
901 raise AssertionError(
902 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100903 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700904
905
906 def _get_child_mock(self, **kw):
907 """Create the child mocks for attributes and return value.
908 By default child mocks will be the same type as the parent.
909 Subclasses of Mock may want to override this to customize the way
910 child mocks are made.
911
912 For non-callable mocks the callable variant will be used (rather than
913 any custom subclass)."""
914 _type = type(self)
915 if not issubclass(_type, CallableMixin):
916 if issubclass(_type, NonCallableMagicMock):
917 klass = MagicMock
918 elif issubclass(_type, NonCallableMock) :
919 klass = Mock
920 else:
921 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +0100922
923 if self._mock_sealed:
924 attribute = "." + kw["name"] if "name" in kw else "()"
925 mock_name = self._extract_mock_name() + attribute
926 raise AttributeError(mock_name)
927
Michael Foord345266a2012-03-14 12:24:34 -0700928 return klass(**kw)
929
930
Petter Strandmark47d94242018-10-28 21:37:10 +0100931 def _calls_repr(self, prefix="Calls"):
932 """Renders self.mock_calls as a string.
933
934 Example: "\nCalls: [call(1), call(2)]."
935
936 If self.mock_calls is empty, an empty string is returned. The
937 output will be truncated if very long.
938 """
939 if not self.mock_calls:
940 return ""
941 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
942
943
Michael Foord345266a2012-03-14 12:24:34 -0700944
945def _try_iter(obj):
946 if obj is None:
947 return obj
948 if _is_exception(obj):
949 return obj
950 if _callable(obj):
951 return obj
952 try:
953 return iter(obj)
954 except TypeError:
955 # XXXX backwards compatibility
956 # but this will blow up on first call - so maybe we should fail early?
957 return obj
958
959
960
961class CallableMixin(Base):
962
963 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
964 wraps=None, name=None, spec_set=None, parent=None,
965 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
966 self.__dict__['_mock_return_value'] = return_value
967
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000968 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700969 spec, wraps, name, spec_set, parent,
970 _spec_state, _new_name, _new_parent, **kwargs
971 )
972
973 self.side_effect = side_effect
974
975
976 def _mock_check_sig(self, *args, **kwargs):
977 # stub method that can be replaced with one with a specific signature
978 pass
979
980
981 def __call__(_mock_self, *args, **kwargs):
982 # can't use self in-case a function / method we are mocking uses self
983 # in the signature
984 _mock_self._mock_check_sig(*args, **kwargs)
985 return _mock_self._mock_call(*args, **kwargs)
986
987
988 def _mock_call(_mock_self, *args, **kwargs):
989 self = _mock_self
990 self.called = True
991 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100992
Chris Withers8ca0fa92018-12-03 21:31:37 +0000993 # handle call_args
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100994 _call = _Call((args, kwargs), two=True)
995 self.call_args = _call
996 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700997
998 seen = set()
Chris Withers8ca0fa92018-12-03 21:31:37 +0000999
1000 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001001 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001002 method_call_name = self._mock_name
1003
1004 # initial stuff for mock_calls:
1005 mock_call_name = self._mock_new_name
1006 is_a_call = mock_call_name == '()'
1007 self.mock_calls.append(_Call(('', args, kwargs)))
1008
1009 # follow up the chain of mocks:
1010 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001011 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001012
Chris Withers8ca0fa92018-12-03 21:31:37 +00001013 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001014 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001015 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001016 do_method_calls = _new_parent._mock_parent is not None
1017 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001018 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001019
Chris Withers8ca0fa92018-12-03 21:31:37 +00001020 # handle mock_calls:
1021 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001022 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001023
1024 if _new_parent._mock_new_name:
1025 if is_a_call:
1026 dot = ''
1027 else:
1028 dot = '.'
1029 is_a_call = _new_parent._mock_new_name == '()'
1030 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1031
1032 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001033 _new_parent = _new_parent._mock_new_parent
1034
Chris Withers8ca0fa92018-12-03 21:31:37 +00001035 # check we're not in an infinite loop:
1036 # ( use ids here so as not to call __hash__ on the mocks)
Michael Foord345266a2012-03-14 12:24:34 -07001037 _new_parent_id = id(_new_parent)
1038 if _new_parent_id in seen:
1039 break
1040 seen.add(_new_parent_id)
1041
Michael Foord345266a2012-03-14 12:24:34 -07001042 effect = self.side_effect
1043 if effect is not None:
1044 if _is_exception(effect):
1045 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001046 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001047 result = next(effect)
1048 if _is_exception(result):
1049 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001050 else:
1051 result = effect(*args, **kwargs)
1052
1053 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001054 return result
Michael Foord345266a2012-03-14 12:24:34 -07001055
Mario Corcherof05df0a2018-12-08 11:25:02 +00001056 if self._mock_return_value is not DEFAULT:
1057 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001058
Mario Corcherof05df0a2018-12-08 11:25:02 +00001059 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001060 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001061
1062 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001063
1064
1065
1066class Mock(CallableMixin, NonCallableMock):
1067 """
1068 Create a new `Mock` object. `Mock` takes several optional arguments
1069 that specify the behaviour of the Mock object:
1070
1071 * `spec`: This can be either a list of strings or an existing object (a
1072 class or instance) that acts as the specification for the mock object. If
1073 you pass in an object then a list of strings is formed by calling dir on
1074 the object (excluding unsupported magic attributes and methods). Accessing
1075 any attribute not in this list will raise an `AttributeError`.
1076
1077 If `spec` is an object (rather than a list of strings) then
1078 `mock.__class__` returns the class of the spec object. This allows mocks
1079 to pass `isinstance` tests.
1080
1081 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1082 or get an attribute on the mock that isn't on the object passed as
1083 `spec_set` will raise an `AttributeError`.
1084
1085 * `side_effect`: A function to be called whenever the Mock is called. See
1086 the `side_effect` attribute. Useful for raising exceptions or
1087 dynamically changing return values. The function is called with the same
1088 arguments as the mock, and unless it returns `DEFAULT`, the return
1089 value of this function is used as the return value.
1090
Michael Foord2cd48732012-04-21 15:52:11 +01001091 If `side_effect` is an iterable then each call to the mock will return
1092 the next value from the iterable. If any of the members of the iterable
1093 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001094
Michael Foord345266a2012-03-14 12:24:34 -07001095 * `return_value`: The value returned when the mock is called. By default
1096 this is a new Mock (created on first access). See the
1097 `return_value` attribute.
1098
Michael Foord0682a0c2012-04-13 20:51:20 +01001099 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1100 calling the Mock will pass the call through to the wrapped object
1101 (returning the real result). Attribute access on the mock will return a
1102 Mock object that wraps the corresponding attribute of the wrapped object
1103 (so attempting to access an attribute that doesn't exist will raise an
1104 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001105
1106 If the mock has an explicit `return_value` set then calls are not passed
1107 to the wrapped object and the `return_value` is returned instead.
1108
1109 * `name`: If the mock has a name then it will be used in the repr of the
1110 mock. This can be useful for debugging. The name is propagated to child
1111 mocks.
1112
1113 Mocks can also be called with arbitrary keyword arguments. These will be
1114 used to set attributes on the mock after it is created.
1115 """
1116
1117
1118
1119def _dot_lookup(thing, comp, import_path):
1120 try:
1121 return getattr(thing, comp)
1122 except AttributeError:
1123 __import__(import_path)
1124 return getattr(thing, comp)
1125
1126
1127def _importer(target):
1128 components = target.split('.')
1129 import_path = components.pop(0)
1130 thing = __import__(import_path)
1131
1132 for comp in components:
1133 import_path += ".%s" % comp
1134 thing = _dot_lookup(thing, comp, import_path)
1135 return thing
1136
1137
1138def _is_started(patcher):
1139 # XXXX horrible
1140 return hasattr(patcher, 'is_local')
1141
1142
1143class _patch(object):
1144
1145 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001146 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001147
1148 def __init__(
1149 self, getter, attribute, new, spec, create,
1150 spec_set, autospec, new_callable, kwargs
1151 ):
1152 if new_callable is not None:
1153 if new is not DEFAULT:
1154 raise ValueError(
1155 "Cannot use 'new' and 'new_callable' together"
1156 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001157 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001158 raise ValueError(
1159 "Cannot use 'autospec' and 'new_callable' together"
1160 )
1161
1162 self.getter = getter
1163 self.attribute = attribute
1164 self.new = new
1165 self.new_callable = new_callable
1166 self.spec = spec
1167 self.create = create
1168 self.has_local = False
1169 self.spec_set = spec_set
1170 self.autospec = autospec
1171 self.kwargs = kwargs
1172 self.additional_patchers = []
1173
1174
1175 def copy(self):
1176 patcher = _patch(
1177 self.getter, self.attribute, self.new, self.spec,
1178 self.create, self.spec_set,
1179 self.autospec, self.new_callable, self.kwargs
1180 )
1181 patcher.attribute_name = self.attribute_name
1182 patcher.additional_patchers = [
1183 p.copy() for p in self.additional_patchers
1184 ]
1185 return patcher
1186
1187
1188 def __call__(self, func):
1189 if isinstance(func, type):
1190 return self.decorate_class(func)
1191 return self.decorate_callable(func)
1192
1193
1194 def decorate_class(self, klass):
1195 for attr in dir(klass):
1196 if not attr.startswith(patch.TEST_PREFIX):
1197 continue
1198
1199 attr_value = getattr(klass, attr)
1200 if not hasattr(attr_value, "__call__"):
1201 continue
1202
1203 patcher = self.copy()
1204 setattr(klass, attr, patcher(attr_value))
1205 return klass
1206
1207
1208 def decorate_callable(self, func):
1209 if hasattr(func, 'patchings'):
1210 func.patchings.append(self)
1211 return func
1212
1213 @wraps(func)
1214 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001215 extra_args = []
1216 entered_patchers = []
1217
Michael Foord50a8c0e2012-03-25 18:57:58 +01001218 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001219 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001220 for patching in patched.patchings:
1221 arg = patching.__enter__()
1222 entered_patchers.append(patching)
1223 if patching.attribute_name is not None:
1224 keywargs.update(arg)
1225 elif patching.new is DEFAULT:
1226 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001227
Michael Foordd7c65e22012-03-14 14:56:54 -07001228 args += tuple(extra_args)
1229 return func(*args, **keywargs)
1230 except:
1231 if (patching not in entered_patchers and
1232 _is_started(patching)):
1233 # the patcher may have been started, but an exception
1234 # raised whilst entering one of its additional_patchers
1235 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001236 # Pass the exception to __exit__
1237 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001238 # re-raise the exception
1239 raise
Michael Foord345266a2012-03-14 12:24:34 -07001240 finally:
1241 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001242 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001243
1244 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001245 return patched
1246
1247
1248 def get_original(self):
1249 target = self.getter()
1250 name = self.attribute
1251
1252 original = DEFAULT
1253 local = False
1254
1255 try:
1256 original = target.__dict__[name]
1257 except (AttributeError, KeyError):
1258 original = getattr(target, name, DEFAULT)
1259 else:
1260 local = True
1261
Michael Foordfddcfa22014-04-14 16:25:20 -04001262 if name in _builtins and isinstance(target, ModuleType):
1263 self.create = True
1264
Michael Foord345266a2012-03-14 12:24:34 -07001265 if not self.create and original is DEFAULT:
1266 raise AttributeError(
1267 "%s does not have the attribute %r" % (target, name)
1268 )
1269 return original, local
1270
1271
1272 def __enter__(self):
1273 """Perform the patch."""
1274 new, spec, spec_set = self.new, self.spec, self.spec_set
1275 autospec, kwargs = self.autospec, self.kwargs
1276 new_callable = self.new_callable
1277 self.target = self.getter()
1278
Michael Foord50a8c0e2012-03-25 18:57:58 +01001279 # normalise False to None
1280 if spec is False:
1281 spec = None
1282 if spec_set is False:
1283 spec_set = None
1284 if autospec is False:
1285 autospec = None
1286
1287 if spec is not None and autospec is not None:
1288 raise TypeError("Can't specify spec and autospec")
1289 if ((spec is not None or autospec is not None) and
1290 spec_set not in (True, None)):
1291 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1292
Michael Foord345266a2012-03-14 12:24:34 -07001293 original, local = self.get_original()
1294
Michael Foord50a8c0e2012-03-25 18:57:58 +01001295 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001296 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001297 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001298 # set spec to the object we are replacing
1299 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001300 if spec_set is True:
1301 spec_set = original
1302 spec = None
1303 elif spec is not None:
1304 if spec_set is True:
1305 spec_set = spec
1306 spec = None
1307 elif spec_set is True:
1308 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001309
Michael Foord50a8c0e2012-03-25 18:57:58 +01001310 if spec is not None or spec_set is not None:
1311 if original is DEFAULT:
1312 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001313 if isinstance(original, type):
1314 # If we're patching out a class and there is a spec
1315 inherit = True
1316
1317 Klass = MagicMock
1318 _kwargs = {}
1319 if new_callable is not None:
1320 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001321 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001322 this_spec = spec
1323 if spec_set is not None:
1324 this_spec = spec_set
1325 if _is_list(this_spec):
1326 not_callable = '__call__' not in this_spec
1327 else:
1328 not_callable = not callable(this_spec)
1329 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001330 Klass = NonCallableMagicMock
1331
1332 if spec is not None:
1333 _kwargs['spec'] = spec
1334 if spec_set is not None:
1335 _kwargs['spec_set'] = spec_set
1336
1337 # add a name to mocks
1338 if (isinstance(Klass, type) and
1339 issubclass(Klass, NonCallableMock) and self.attribute):
1340 _kwargs['name'] = self.attribute
1341
1342 _kwargs.update(kwargs)
1343 new = Klass(**_kwargs)
1344
1345 if inherit and _is_instance_mock(new):
1346 # we can only tell if the instance should be callable if the
1347 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001348 this_spec = spec
1349 if spec_set is not None:
1350 this_spec = spec_set
1351 if (not _is_list(this_spec) and not
1352 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001353 Klass = NonCallableMagicMock
1354
1355 _kwargs.pop('name')
1356 new.return_value = Klass(_new_parent=new, _new_name='()',
1357 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001358 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001359 # spec is ignored, new *must* be default, spec_set is treated
1360 # as a boolean. Should we check spec is not None and that spec_set
1361 # is a bool?
1362 if new is not DEFAULT:
1363 raise TypeError(
1364 "autospec creates the mock for you. Can't specify "
1365 "autospec and new."
1366 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001367 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001368 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001369 spec_set = bool(spec_set)
1370 if autospec is True:
1371 autospec = original
1372
1373 new = create_autospec(autospec, spec_set=spec_set,
1374 _name=self.attribute, **kwargs)
1375 elif kwargs:
1376 # can't set keyword args when we aren't creating the mock
1377 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1378 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1379
1380 new_attr = new
1381
1382 self.temp_original = original
1383 self.is_local = local
1384 setattr(self.target, self.attribute, new_attr)
1385 if self.attribute_name is not None:
1386 extra_args = {}
1387 if self.new is DEFAULT:
1388 extra_args[self.attribute_name] = new
1389 for patching in self.additional_patchers:
1390 arg = patching.__enter__()
1391 if patching.new is DEFAULT:
1392 extra_args.update(arg)
1393 return extra_args
1394
1395 return new
1396
1397
Michael Foord50a8c0e2012-03-25 18:57:58 +01001398 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001399 """Undo the patch."""
1400 if not _is_started(self):
1401 raise RuntimeError('stop called on unstarted patcher')
1402
1403 if self.is_local and self.temp_original is not DEFAULT:
1404 setattr(self.target, self.attribute, self.temp_original)
1405 else:
1406 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001407 if not self.create and (not hasattr(self.target, self.attribute) or
1408 self.attribute in ('__doc__', '__module__',
1409 '__defaults__', '__annotations__',
1410 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001411 # needed for proxy objects like django settings
1412 setattr(self.target, self.attribute, self.temp_original)
1413
1414 del self.temp_original
1415 del self.is_local
1416 del self.target
1417 for patcher in reversed(self.additional_patchers):
1418 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001419 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001420
Michael Foordf7c41582012-06-10 20:36:32 +01001421
1422 def start(self):
1423 """Activate a patch, returning any created mock."""
1424 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001425 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001426 return result
1427
1428
1429 def stop(self):
1430 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001431 try:
1432 self._active_patches.remove(self)
1433 except ValueError:
1434 # If the patch hasn't been started this will fail
1435 pass
1436
Michael Foordf7c41582012-06-10 20:36:32 +01001437 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001438
1439
1440
1441def _get_target(target):
1442 try:
1443 target, attribute = target.rsplit('.', 1)
1444 except (TypeError, ValueError):
1445 raise TypeError("Need a valid target to patch. You supplied: %r" %
1446 (target,))
1447 getter = lambda: _importer(target)
1448 return getter, attribute
1449
1450
1451def _patch_object(
1452 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001453 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001454 new_callable=None, **kwargs
1455 ):
1456 """
Michael Foord345266a2012-03-14 12:24:34 -07001457 patch the named member (`attribute`) on an object (`target`) with a mock
1458 object.
1459
1460 `patch.object` can be used as a decorator, class decorator or a context
1461 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1462 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1463 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1464 the mock object it creates.
1465
1466 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1467 for choosing which methods to wrap.
1468 """
1469 getter = lambda: target
1470 return _patch(
1471 getter, attribute, new, spec, create,
1472 spec_set, autospec, new_callable, kwargs
1473 )
1474
1475
Michael Foord50a8c0e2012-03-25 18:57:58 +01001476def _patch_multiple(target, spec=None, create=False, spec_set=None,
1477 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001478 """Perform multiple patches in a single call. It takes the object to be
1479 patched (either as an object or a string to fetch the object by importing)
1480 and keyword arguments for the patches::
1481
1482 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1483 ...
1484
1485 Use `DEFAULT` as the value if you want `patch.multiple` to create
1486 mocks for you. In this case the created mocks are passed into a decorated
1487 function by keyword, and a dictionary is returned when `patch.multiple` is
1488 used as a context manager.
1489
1490 `patch.multiple` can be used as a decorator, class decorator or a context
1491 manager. The arguments `spec`, `spec_set`, `create`,
1492 `autospec` and `new_callable` have the same meaning as for `patch`. These
1493 arguments will be applied to *all* patches done by `patch.multiple`.
1494
1495 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1496 for choosing which methods to wrap.
1497 """
1498 if type(target) is str:
1499 getter = lambda: _importer(target)
1500 else:
1501 getter = lambda: target
1502
1503 if not kwargs:
1504 raise ValueError(
1505 'Must supply at least one keyword argument with patch.multiple'
1506 )
1507 # need to wrap in a list for python 3, where items is a view
1508 items = list(kwargs.items())
1509 attribute, new = items[0]
1510 patcher = _patch(
1511 getter, attribute, new, spec, create, spec_set,
1512 autospec, new_callable, {}
1513 )
1514 patcher.attribute_name = attribute
1515 for attribute, new in items[1:]:
1516 this_patcher = _patch(
1517 getter, attribute, new, spec, create, spec_set,
1518 autospec, new_callable, {}
1519 )
1520 this_patcher.attribute_name = attribute
1521 patcher.additional_patchers.append(this_patcher)
1522 return patcher
1523
1524
1525def patch(
1526 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001527 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001528 ):
1529 """
1530 `patch` acts as a function decorator, class decorator or a context
1531 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001532 is patched with a `new` object. When the function/with statement exits
1533 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001534
Michael Foord54b3db82012-03-28 15:08:08 +01001535 If `new` is omitted, then the target is replaced with a
1536 `MagicMock`. If `patch` is used as a decorator and `new` is
1537 omitted, the created mock is passed in as an extra argument to the
1538 decorated function. If `patch` is used as a context manager the created
1539 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001540
Michael Foord54b3db82012-03-28 15:08:08 +01001541 `target` should be a string in the form `'package.module.ClassName'`. The
1542 `target` is imported and the specified object replaced with the `new`
1543 object, so the `target` must be importable from the environment you are
1544 calling `patch` from. The target is imported when the decorated function
1545 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001546
1547 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1548 if patch is creating one for you.
1549
1550 In addition you can pass `spec=True` or `spec_set=True`, which causes
1551 patch to pass in the object being mocked as the spec/spec_set object.
1552
1553 `new_callable` allows you to specify a different class, or callable object,
1554 that will be called to create the `new` object. By default `MagicMock` is
1555 used.
1556
1557 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001558 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001559 All attributes of the mock will also have the spec of the corresponding
1560 attribute of the object being replaced. Methods and functions being
1561 mocked will have their arguments checked and will raise a `TypeError` if
1562 they are called with the wrong signature. For mocks replacing a class,
1563 their return value (the 'instance') will have the same spec as the class.
1564
1565 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1566 arbitrary object as the spec instead of the one being replaced.
1567
1568 By default `patch` will fail to replace attributes that don't exist. If
1569 you pass in `create=True`, and the attribute doesn't exist, patch will
1570 create the attribute for you when the patched function is called, and
1571 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001572 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001573 default because it can be dangerous. With it switched on you can write
1574 passing tests against APIs that don't actually exist!
1575
1576 Patch can be used as a `TestCase` class decorator. It works by
1577 decorating each test method in the class. This reduces the boilerplate
1578 code when your test methods share a common patchings set. `patch` finds
1579 tests by looking for method names that start with `patch.TEST_PREFIX`.
1580 By default this is `test`, which matches the way `unittest` finds tests.
1581 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1582
1583 Patch can be used as a context manager, with the with statement. Here the
1584 patching applies to the indented block after the with statement. If you
1585 use "as" then the patched object will be bound to the name after the
1586 "as"; very useful if `patch` is creating a mock object for you.
1587
1588 `patch` takes arbitrary keyword arguments. These will be passed to
1589 the `Mock` (or `new_callable`) on construction.
1590
1591 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1592 available for alternate use-cases.
1593 """
1594 getter, attribute = _get_target(target)
1595 return _patch(
1596 getter, attribute, new, spec, create,
1597 spec_set, autospec, new_callable, kwargs
1598 )
1599
1600
1601class _patch_dict(object):
1602 """
1603 Patch a dictionary, or dictionary like object, and restore the dictionary
1604 to its original state after the test.
1605
1606 `in_dict` can be a dictionary or a mapping like container. If it is a
1607 mapping then it must at least support getting, setting and deleting items
1608 plus iterating over keys.
1609
1610 `in_dict` can also be a string specifying the name of the dictionary, which
1611 will then be fetched by importing it.
1612
1613 `values` can be a dictionary of values to set in the dictionary. `values`
1614 can also be an iterable of `(key, value)` pairs.
1615
1616 If `clear` is True then the dictionary will be cleared before the new
1617 values are set.
1618
1619 `patch.dict` can also be called with arbitrary keyword arguments to set
1620 values in the dictionary::
1621
1622 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1623 ...
1624
1625 `patch.dict` can be used as a context manager, decorator or class
1626 decorator. When used as a class decorator `patch.dict` honours
1627 `patch.TEST_PREFIX` for choosing which methods to wrap.
1628 """
1629
1630 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001631 self.in_dict = in_dict
1632 # support any argument supported by dict(...) constructor
1633 self.values = dict(values)
1634 self.values.update(kwargs)
1635 self.clear = clear
1636 self._original = None
1637
1638
1639 def __call__(self, f):
1640 if isinstance(f, type):
1641 return self.decorate_class(f)
1642 @wraps(f)
1643 def _inner(*args, **kw):
1644 self._patch_dict()
1645 try:
1646 return f(*args, **kw)
1647 finally:
1648 self._unpatch_dict()
1649
1650 return _inner
1651
1652
1653 def decorate_class(self, klass):
1654 for attr in dir(klass):
1655 attr_value = getattr(klass, attr)
1656 if (attr.startswith(patch.TEST_PREFIX) and
1657 hasattr(attr_value, "__call__")):
1658 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1659 decorated = decorator(attr_value)
1660 setattr(klass, attr, decorated)
1661 return klass
1662
1663
1664 def __enter__(self):
1665 """Patch the dict."""
1666 self._patch_dict()
1667
1668
1669 def _patch_dict(self):
1670 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301671 if isinstance(self.in_dict, str):
1672 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001673 in_dict = self.in_dict
1674 clear = self.clear
1675
1676 try:
1677 original = in_dict.copy()
1678 except AttributeError:
1679 # dict like object with no copy method
1680 # must support iteration over keys
1681 original = {}
1682 for key in in_dict:
1683 original[key] = in_dict[key]
1684 self._original = original
1685
1686 if clear:
1687 _clear_dict(in_dict)
1688
1689 try:
1690 in_dict.update(values)
1691 except AttributeError:
1692 # dict like object with no update method
1693 for key in values:
1694 in_dict[key] = values[key]
1695
1696
1697 def _unpatch_dict(self):
1698 in_dict = self.in_dict
1699 original = self._original
1700
1701 _clear_dict(in_dict)
1702
1703 try:
1704 in_dict.update(original)
1705 except AttributeError:
1706 for key in original:
1707 in_dict[key] = original[key]
1708
1709
1710 def __exit__(self, *args):
1711 """Unpatch the dict."""
1712 self._unpatch_dict()
1713 return False
1714
1715 start = __enter__
1716 stop = __exit__
1717
1718
1719def _clear_dict(in_dict):
1720 try:
1721 in_dict.clear()
1722 except AttributeError:
1723 keys = list(in_dict)
1724 for key in keys:
1725 del in_dict[key]
1726
1727
Michael Foordf7c41582012-06-10 20:36:32 +01001728def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001729 """Stop all active patches. LIFO to unroll nested patches."""
1730 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001731 patch.stop()
1732
1733
Michael Foord345266a2012-03-14 12:24:34 -07001734patch.object = _patch_object
1735patch.dict = _patch_dict
1736patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001737patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001738patch.TEST_PREFIX = 'test'
1739
1740magic_methods = (
1741 "lt le gt ge eq ne "
1742 "getitem setitem delitem "
1743 "len contains iter "
1744 "hash str sizeof "
1745 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001746 # we added divmod and rdivmod here instead of numerics
1747 # because there is no idivmod
1748 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001749 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001750 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001751 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001752 "fspath "
Michael Foord345266a2012-03-14 12:24:34 -07001753)
1754
Michael Foordd2623d72014-04-14 11:23:48 -04001755numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001756 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001757)
Michael Foord345266a2012-03-14 12:24:34 -07001758inplace = ' '.join('i%s' % n for n in numerics.split())
1759right = ' '.join('r%s' % n for n in numerics.split())
1760
1761# not including __prepare__, __instancecheck__, __subclasscheck__
1762# (as they are metaclass methods)
1763# __del__ is not supported at all as it causes problems if it exists
1764
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001765_non_defaults = {
1766 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1767 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1768 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1769 '__repr__', '__dir__', '__subclasses__', '__format__',
Serhiy Storchaka5943ea72016-06-19 18:30:43 +03001770 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001771}
Michael Foord345266a2012-03-14 12:24:34 -07001772
1773
1774def _get_method(name, func):
1775 "Turns a callable object (like a mock) into a real function"
1776 def method(self, *args, **kw):
1777 return func(self, *args, **kw)
1778 method.__name__ = name
1779 return method
1780
1781
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001782_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001783 '__%s__' % method for method in
1784 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001785}
Michael Foord345266a2012-03-14 12:24:34 -07001786
1787_all_magics = _magics | _non_defaults
1788
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001789_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001790 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001791 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001792 '__instancecheck__', '__subclasscheck__',
1793 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001794}
Michael Foord345266a2012-03-14 12:24:34 -07001795
1796_calculate_return_value = {
1797 '__hash__': lambda self: object.__hash__(self),
1798 '__str__': lambda self: object.__str__(self),
1799 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001800 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001801}
1802
1803_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001804 '__lt__': NotImplemented,
1805 '__gt__': NotImplemented,
1806 '__le__': NotImplemented,
1807 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001808 '__int__': 1,
1809 '__contains__': False,
1810 '__len__': 0,
1811 '__exit__': False,
1812 '__complex__': 1j,
1813 '__float__': 1.0,
1814 '__bool__': True,
1815 '__index__': 1,
1816}
1817
1818
1819def _get_eq(self):
1820 def __eq__(other):
1821 ret_val = self.__eq__._mock_return_value
1822 if ret_val is not DEFAULT:
1823 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001824 if self is other:
1825 return True
1826 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001827 return __eq__
1828
1829def _get_ne(self):
1830 def __ne__(other):
1831 if self.__ne__._mock_return_value is not DEFAULT:
1832 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001833 if self is other:
1834 return False
1835 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001836 return __ne__
1837
1838def _get_iter(self):
1839 def __iter__():
1840 ret_val = self.__iter__._mock_return_value
1841 if ret_val is DEFAULT:
1842 return iter([])
1843 # if ret_val was already an iterator, then calling iter on it should
1844 # return the iterator unchanged
1845 return iter(ret_val)
1846 return __iter__
1847
1848_side_effect_methods = {
1849 '__eq__': _get_eq,
1850 '__ne__': _get_ne,
1851 '__iter__': _get_iter,
1852}
1853
1854
1855
1856def _set_return_value(mock, method, name):
1857 fixed = _return_values.get(name, DEFAULT)
1858 if fixed is not DEFAULT:
1859 method.return_value = fixed
1860 return
1861
1862 return_calulator = _calculate_return_value.get(name)
1863 if return_calulator is not None:
1864 try:
1865 return_value = return_calulator(mock)
1866 except AttributeError:
1867 # XXXX why do we return AttributeError here?
1868 # set it as a side_effect instead?
1869 return_value = AttributeError(name)
1870 method.return_value = return_value
1871 return
1872
1873 side_effector = _side_effect_methods.get(name)
1874 if side_effector is not None:
1875 method.side_effect = side_effector(mock)
1876
1877
1878
1879class MagicMixin(object):
1880 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001881 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001882 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001883 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001884
1885
1886 def _mock_set_magics(self):
1887 these_magics = _magics
1888
Łukasz Langaa468db92015-04-13 23:12:42 -07001889 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001890 these_magics = _magics.intersection(self._mock_methods)
1891
1892 remove_magics = set()
1893 remove_magics = _magics - these_magics
1894
1895 for entry in remove_magics:
1896 if entry in type(self).__dict__:
1897 # remove unneeded magic methods
1898 delattr(self, entry)
1899
1900 # don't overwrite existing attributes if called a second time
1901 these_magics = these_magics - set(type(self).__dict__)
1902
1903 _type = type(self)
1904 for entry in these_magics:
1905 setattr(_type, entry, MagicProxy(entry, self))
1906
1907
1908
1909class NonCallableMagicMock(MagicMixin, NonCallableMock):
1910 """A version of `MagicMock` that isn't callable."""
1911 def mock_add_spec(self, spec, spec_set=False):
1912 """Add a spec to a mock. `spec` can either be an object or a
1913 list of strings. Only attributes on the `spec` can be fetched as
1914 attributes from the mock.
1915
1916 If `spec_set` is True then only attributes on the spec can be set."""
1917 self._mock_add_spec(spec, spec_set)
1918 self._mock_set_magics()
1919
1920
1921
1922class MagicMock(MagicMixin, Mock):
1923 """
1924 MagicMock is a subclass of Mock with default implementations
1925 of most of the magic methods. You can use MagicMock without having to
1926 configure the magic methods yourself.
1927
1928 If you use the `spec` or `spec_set` arguments then *only* magic
1929 methods that exist in the spec will be created.
1930
1931 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1932 """
1933 def mock_add_spec(self, spec, spec_set=False):
1934 """Add a spec to a mock. `spec` can either be an object or a
1935 list of strings. Only attributes on the `spec` can be fetched as
1936 attributes from the mock.
1937
1938 If `spec_set` is True then only attributes on the spec can be set."""
1939 self._mock_add_spec(spec, spec_set)
1940 self._mock_set_magics()
1941
1942
1943
1944class MagicProxy(object):
1945 def __init__(self, name, parent):
1946 self.name = name
1947 self.parent = parent
1948
1949 def __call__(self, *args, **kwargs):
1950 m = self.create_mock()
1951 return m(*args, **kwargs)
1952
1953 def create_mock(self):
1954 entry = self.name
1955 parent = self.parent
1956 m = parent._get_child_mock(name=entry, _new_name=entry,
1957 _new_parent=parent)
1958 setattr(parent, entry, m)
1959 _set_return_value(parent, m, entry)
1960 return m
1961
1962 def __get__(self, obj, _type=None):
1963 return self.create_mock()
1964
1965
1966
1967class _ANY(object):
1968 "A helper object that compares equal to everything."
1969
1970 def __eq__(self, other):
1971 return True
1972
1973 def __ne__(self, other):
1974 return False
1975
1976 def __repr__(self):
1977 return '<ANY>'
1978
1979ANY = _ANY()
1980
1981
1982
1983def _format_call_signature(name, args, kwargs):
1984 message = '%s(%%s)' % name
1985 formatted_args = ''
1986 args_string = ', '.join([repr(arg) for arg in args])
1987 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301988 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001989 ])
1990 if args_string:
1991 formatted_args = args_string
1992 if kwargs_string:
1993 if formatted_args:
1994 formatted_args += ', '
1995 formatted_args += kwargs_string
1996
1997 return message % formatted_args
1998
1999
2000
2001class _Call(tuple):
2002 """
2003 A tuple for holding the results of a call to a mock, either in the form
2004 `(args, kwargs)` or `(name, args, kwargs)`.
2005
2006 If args or kwargs are empty then a call tuple will compare equal to
2007 a tuple without those values. This makes comparisons less verbose::
2008
2009 _Call(('name', (), {})) == ('name',)
2010 _Call(('name', (1,), {})) == ('name', (1,))
2011 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2012
2013 The `_Call` object provides a useful shortcut for comparing with call::
2014
2015 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2016 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2017
2018 If the _Call has no name then it will match any name.
2019 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002020 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002021 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002022 args = ()
2023 kwargs = {}
2024 _len = len(value)
2025 if _len == 3:
2026 name, args, kwargs = value
2027 elif _len == 2:
2028 first, second = value
2029 if isinstance(first, str):
2030 name = first
2031 if isinstance(second, tuple):
2032 args = second
2033 else:
2034 kwargs = second
2035 else:
2036 args, kwargs = first, second
2037 elif _len == 1:
2038 value, = value
2039 if isinstance(value, str):
2040 name = value
2041 elif isinstance(value, tuple):
2042 args = value
2043 else:
2044 kwargs = value
2045
2046 if two:
2047 return tuple.__new__(cls, (args, kwargs))
2048
2049 return tuple.__new__(cls, (name, args, kwargs))
2050
2051
2052 def __init__(self, value=(), name=None, parent=None, two=False,
2053 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002054 self._mock_name = name
2055 self._mock_parent = parent
2056 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002057
2058
2059 def __eq__(self, other):
2060 if other is ANY:
2061 return True
2062 try:
2063 len_other = len(other)
2064 except TypeError:
2065 return False
2066
2067 self_name = ''
2068 if len(self) == 2:
2069 self_args, self_kwargs = self
2070 else:
2071 self_name, self_args, self_kwargs = self
2072
Andrew Dunaie63e6172018-12-04 11:08:45 +02002073 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2074 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002075 return False
2076
Michael Foord345266a2012-03-14 12:24:34 -07002077 other_name = ''
2078 if len_other == 0:
2079 other_args, other_kwargs = (), {}
2080 elif len_other == 3:
2081 other_name, other_args, other_kwargs = other
2082 elif len_other == 1:
2083 value, = other
2084 if isinstance(value, tuple):
2085 other_args = value
2086 other_kwargs = {}
2087 elif isinstance(value, str):
2088 other_name = value
2089 other_args, other_kwargs = (), {}
2090 else:
2091 other_args = ()
2092 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002093 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002094 # could be (name, args) or (name, kwargs) or (args, kwargs)
2095 first, second = other
2096 if isinstance(first, str):
2097 other_name = first
2098 if isinstance(second, tuple):
2099 other_args, other_kwargs = second, {}
2100 else:
2101 other_args, other_kwargs = (), second
2102 else:
2103 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002104 else:
2105 return False
Michael Foord345266a2012-03-14 12:24:34 -07002106
2107 if self_name and other_name != self_name:
2108 return False
2109
2110 # this order is important for ANY to work!
2111 return (other_args, other_kwargs) == (self_args, self_kwargs)
2112
2113
Berker Peksagce913872016-03-28 00:30:02 +03002114 __ne__ = object.__ne__
2115
2116
Michael Foord345266a2012-03-14 12:24:34 -07002117 def __call__(self, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002118 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002119 return _Call(('', args, kwargs), name='()')
2120
Andrew Dunaie63e6172018-12-04 11:08:45 +02002121 name = self._mock_name + '()'
2122 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002123
2124
2125 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002126 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002127 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002128 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002129 return _Call(name=name, parent=self, from_kall=False)
2130
2131
Kushal Dasa37b9582014-09-16 18:33:37 +05302132 def count(self, *args, **kwargs):
2133 return self.__getattr__('count')(*args, **kwargs)
2134
2135 def index(self, *args, **kwargs):
2136 return self.__getattr__('index')(*args, **kwargs)
2137
Michael Foord345266a2012-03-14 12:24:34 -07002138 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002139 if not self._mock_from_kall:
2140 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002141 if name.startswith('()'):
2142 name = 'call%s' % name
2143 return name
2144
2145 if len(self) == 2:
2146 name = 'call'
2147 args, kwargs = self
2148 else:
2149 name, args, kwargs = self
2150 if not name:
2151 name = 'call'
2152 elif not name.startswith('()'):
2153 name = 'call.%s' % name
2154 else:
2155 name = 'call%s' % name
2156 return _format_call_signature(name, args, kwargs)
2157
2158
2159 def call_list(self):
2160 """For a call object that represents multiple calls, `call_list`
2161 returns a list of all the intermediate calls as well as the
2162 final call."""
2163 vals = []
2164 thing = self
2165 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002166 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002167 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002168 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002169 return _CallList(reversed(vals))
2170
2171
2172call = _Call(from_kall=False)
2173
2174
2175
2176def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2177 _name=None, **kwargs):
2178 """Create a mock object using another object as a spec. Attributes on the
2179 mock will use the corresponding attribute on the `spec` object as their
2180 spec.
2181
2182 Functions or methods being mocked will have their arguments checked
2183 to check that they are called with the correct signature.
2184
2185 If `spec_set` is True then attempting to set attributes that don't exist
2186 on the spec object will raise an `AttributeError`.
2187
2188 If a class is used as a spec then the return value of the mock (the
2189 instance of the class) will have the same spec. You can use a class as the
2190 spec for an instance object by passing `instance=True`. The returned mock
2191 will only be callable if instances of the mock are callable.
2192
2193 `create_autospec` also takes arbitrary keyword arguments that are passed to
2194 the constructor of the created mock."""
2195 if _is_list(spec):
2196 # can't pass a list instance to the mock constructor as it will be
2197 # interpreted as a list of strings
2198 spec = type(spec)
2199
2200 is_type = isinstance(spec, type)
2201
2202 _kwargs = {'spec': spec}
2203 if spec_set:
2204 _kwargs = {'spec_set': spec}
2205 elif spec is None:
2206 # None we mock with a normal mock without a spec
2207 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002208 if _kwargs and instance:
2209 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002210
2211 _kwargs.update(kwargs)
2212
2213 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002214 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002215 # descriptors don't have a spec
2216 # because we don't know what type they return
2217 _kwargs = {}
2218 elif not _callable(spec):
2219 Klass = NonCallableMagicMock
2220 elif is_type and instance and not _instance_callable(spec):
2221 Klass = NonCallableMagicMock
2222
Kushal Das484f8a82014-04-16 01:05:50 +05302223 _name = _kwargs.pop('name', _name)
2224
Michael Foord345266a2012-03-14 12:24:34 -07002225 _new_name = _name
2226 if _parent is None:
2227 # for a top level object no _new_name should be set
2228 _new_name = ''
2229
2230 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2231 name=_name, **_kwargs)
2232
2233 if isinstance(spec, FunctionTypes):
2234 # should only happen at the top level because we don't
2235 # recurse for functions
2236 mock = _set_signature(mock, spec)
2237 else:
2238 _check_signature(spec, mock, is_type, instance)
2239
2240 if _parent is not None and not instance:
2241 _parent._mock_children[_name] = mock
2242
2243 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002244 mock.return_value = create_autospec(spec, spec_set, instance=True,
2245 _name='()', _parent=mock)
2246
2247 for entry in dir(spec):
2248 if _is_magic(entry):
2249 # MagicMock already does the useful magic methods for us
2250 continue
2251
Michael Foord345266a2012-03-14 12:24:34 -07002252 # XXXX do we need a better way of getting attributes without
2253 # triggering code execution (?) Probably not - we need the actual
2254 # object to mock it so we would rather trigger a property than mock
2255 # the property descriptor. Likewise we want to mock out dynamically
2256 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002257 # XXXX what about attributes that raise exceptions other than
2258 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002259 # we could be resilient against it, or catch and propagate the
2260 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002261 try:
2262 original = getattr(spec, entry)
2263 except AttributeError:
2264 continue
Michael Foord345266a2012-03-14 12:24:34 -07002265
2266 kwargs = {'spec': original}
2267 if spec_set:
2268 kwargs = {'spec_set': original}
2269
2270 if not isinstance(original, FunctionTypes):
2271 new = _SpecState(original, spec_set, mock, entry, instance)
2272 mock._mock_children[entry] = new
2273 else:
2274 parent = mock
2275 if isinstance(spec, FunctionTypes):
2276 parent = mock.mock
2277
Michael Foord345266a2012-03-14 12:24:34 -07002278 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002279 kwargs['_eat_self'] = skipfirst
2280 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2281 _new_parent=parent,
2282 **kwargs)
2283 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002284 _check_signature(original, new, skipfirst=skipfirst)
2285
2286 # so functions created with _set_signature become instance attributes,
2287 # *plus* their underlying mock exists in _mock_children of the parent
2288 # mock. Adding to _mock_children may be unnecessary where we are also
2289 # setting as an instance attribute?
2290 if isinstance(new, FunctionTypes):
2291 setattr(mock, entry, new)
2292
2293 return mock
2294
2295
2296def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002297 """
2298 Return whether we should skip the first argument on spec's `entry`
2299 attribute.
2300 """
Michael Foord345266a2012-03-14 12:24:34 -07002301 if not isinstance(spec, type):
2302 if entry in getattr(spec, '__dict__', {}):
2303 # instance attribute - shouldn't skip
2304 return False
Michael Foord345266a2012-03-14 12:24:34 -07002305 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002306
2307 for klass in spec.__mro__:
2308 result = klass.__dict__.get(entry, DEFAULT)
2309 if result is DEFAULT:
2310 continue
2311 if isinstance(result, (staticmethod, classmethod)):
2312 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002313 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2314 # Normal method => skip if looked up on type
2315 # (if looked up on instance, self is already skipped)
2316 return is_type
2317 else:
2318 return False
Michael Foord345266a2012-03-14 12:24:34 -07002319
2320 # shouldn't get here unless function is a dynamically provided attribute
2321 # XXXX untested behaviour
2322 return is_type
2323
2324
2325def _get_class(obj):
2326 try:
2327 return obj.__class__
2328 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002329 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002330 return type(obj)
2331
2332
2333class _SpecState(object):
2334
2335 def __init__(self, spec, spec_set=False, parent=None,
2336 name=None, ids=None, instance=False):
2337 self.spec = spec
2338 self.ids = ids
2339 self.spec_set = spec_set
2340 self.parent = parent
2341 self.instance = instance
2342 self.name = name
2343
2344
2345FunctionTypes = (
2346 # python function
2347 type(create_autospec),
2348 # instance method
2349 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002350)
2351
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002352MethodWrapperTypes = (
2353 type(ANY.__eq__.__get__),
2354)
2355
Michael Foord345266a2012-03-14 12:24:34 -07002356
Michael Foorda74561a2012-03-25 19:03:13 +01002357file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002358
Michael Foord04cbe0c2013-03-19 17:22:51 -07002359def _iterate_read_data(read_data):
2360 # Helper for mock_open:
2361 # Retrieve lines from read_data via a generator so that separate calls to
2362 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002363 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2364 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002365
Berker Peksag86b34da2015-08-06 13:15:51 +03002366 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002367 # If the last line ended in a newline, the list comprehension will have an
2368 # extra entry that's just a newline. Remove this.
2369 data_as_list = data_as_list[:-1]
2370 else:
2371 # If there wasn't an extra newline by itself, then the file being
2372 # emulated doesn't have a newline to end the last line remove the
2373 # newline that our naive format() added
2374 data_as_list[-1] = data_as_list[-1][:-1]
2375
2376 for line in data_as_list:
2377 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002378
Robert Collins5329aaa2015-07-17 20:08:45 +12002379
Michael Foord0dccf652012-03-25 19:11:50 +01002380def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002381 """
2382 A helper function to create a mock to replace the use of `open`. It works
2383 for `open` called directly or used as a context manager.
2384
2385 The `mock` argument is the mock object to configure. If `None` (the
2386 default) then a `MagicMock` will be created for you, with the API limited
2387 to methods or attributes available on standard file handles.
2388
Xtreak71f82a22018-12-20 21:30:21 +05302389 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002390 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002391 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002392 def _readlines_side_effect(*args, **kwargs):
2393 if handle.readlines.return_value is not None:
2394 return handle.readlines.return_value
2395 return list(_state[0])
2396
2397 def _read_side_effect(*args, **kwargs):
2398 if handle.read.return_value is not None:
2399 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002400 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002401
2402 def _readline_side_effect():
Tony Flury20870232018-09-12 23:21:16 +01002403 yield from _iter_side_effect()
2404 while True:
2405 yield type(read_data)()
2406
2407 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002408 if handle.readline.return_value is not None:
2409 while True:
2410 yield handle.readline.return_value
2411 for line in _state[0]:
2412 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002413
Michael Foorda74561a2012-03-25 19:03:13 +01002414 global file_spec
2415 if file_spec is None:
2416 import _io
2417 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2418
Michael Foord345266a2012-03-14 12:24:34 -07002419 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002420 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002421
Robert Collinsca647ef2015-07-24 03:48:20 +12002422 handle = MagicMock(spec=file_spec)
2423 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002424
Robert Collinsca647ef2015-07-24 03:48:20 +12002425 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002426
Robert Collinsca647ef2015-07-24 03:48:20 +12002427 handle.write.return_value = None
2428 handle.read.return_value = None
2429 handle.readline.return_value = None
2430 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002431
Robert Collinsca647ef2015-07-24 03:48:20 +12002432 handle.read.side_effect = _read_side_effect
2433 _state[1] = _readline_side_effect()
2434 handle.readline.side_effect = _state[1]
2435 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002436 handle.__iter__.side_effect = _iter_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002437
Robert Collinsca647ef2015-07-24 03:48:20 +12002438 def reset_data(*args, **kwargs):
2439 _state[0] = _iterate_read_data(read_data)
2440 if handle.readline.side_effect == _state[1]:
2441 # Only reset the side effect if the user hasn't overridden it.
2442 _state[1] = _readline_side_effect()
2443 handle.readline.side_effect = _state[1]
2444 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002445
Robert Collinsca647ef2015-07-24 03:48:20 +12002446 mock.side_effect = reset_data
2447 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002448 return mock
2449
2450
2451class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002452 """
2453 A mock intended to be used as a property, or other descriptor, on a class.
2454 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2455 a return value when it is fetched.
2456
2457 Fetching a `PropertyMock` instance from an object calls the mock, with
2458 no args. Setting it calls the mock with the value being set.
2459 """
Michael Foordc2870622012-04-13 16:57:22 +01002460 def _get_child_mock(self, **kwargs):
2461 return MagicMock(**kwargs)
2462
Michael Foord345266a2012-03-14 12:24:34 -07002463 def __get__(self, obj, obj_type):
2464 return self()
2465 def __set__(self, obj, val):
2466 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002467
2468
2469def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002470 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002471
2472 Given an input Mock, seals it to ensure no further mocks will be generated
2473 when accessing an attribute that was not already defined.
2474
Mario Corchero96200eb2018-10-19 22:57:37 +01002475 The operation recursively seals the mock passed in, meaning that
2476 the mock itself, any mocks generated by accessing one of its attributes,
2477 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002478 """
2479 mock._mock_sealed = True
2480 for attr in dir(mock):
2481 try:
2482 m = getattr(mock, attr)
2483 except AttributeError:
2484 continue
2485 if not isinstance(m, NonCallableMock):
2486 continue
2487 if m._mock_new_parent is mock:
2488 seal(m)