blob: 5907e5c240f5f4b7047eb4f2cca64bbea20de5a7 [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
Miss Islington (bot)a9846e02018-06-10 22:05:22 -07005# 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
Antoine Pitrou5c64df72013-02-03 00:23:58 +010033from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070034
35
Michael Foordfddcfa22014-04-14 16:25:20 -040036_builtins = {name for name in dir(builtins) if not name.startswith('_')}
37
Michael Foord345266a2012-03-14 12:24:34 -070038BaseExceptions = (BaseException,)
39if 'java' in sys.platform:
40 # jython
41 import java
42 BaseExceptions = (BaseException, java.lang.Throwable)
43
44
45FILTER_DIR = True
46
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100047# Workaround for issue #12370
48# Without this, the __class__ properties wouldn't be set correctly
49_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070050
51def _is_instance_mock(obj):
52 # can't use isinstance on Mock objects because they override __class__
53 # The base class for all mocks is NonCallableMock
54 return issubclass(type(obj), NonCallableMock)
55
56
57def _is_exception(obj):
58 return (
59 isinstance(obj, BaseExceptions) or
60 isinstance(obj, type) and issubclass(obj, BaseExceptions)
61 )
62
63
Antoine Pitrou5c64df72013-02-03 00:23:58 +010064def _get_signature_object(func, as_instance, eat_self):
65 """
66 Given an arbitrary, possibly callable object, try to create a suitable
67 signature object.
68 Return a (reduced func, signature) tuple, or None.
69 """
70 if isinstance(func, type) and not as_instance:
71 # If it's a type and should be modelled as a type, use __init__.
Michael Foord345266a2012-03-14 12:24:34 -070072 try:
73 func = func.__init__
74 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010075 return None
76 # Skip the `self` argument in __init__
77 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070078 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010079 # If we really want to model an instance of the passed type,
80 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070081 try:
82 func = func.__call__
83 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010084 return None
85 if eat_self:
86 sig_func = partial(func, None)
87 else:
88 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -070089 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010090 return func, inspect.signature(sig_func)
91 except ValueError:
92 # Certain callable types are not supported by inspect.signature()
93 return None
Michael Foord345266a2012-03-14 12:24:34 -070094
95
96def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010097 sig = _get_signature_object(func, instance, skipfirst)
98 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -070099 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100100 func, sig = sig
101 def checksig(_mock_self, *args, **kwargs):
102 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700103 _copy_func_details(func, checksig)
104 type(mock)._mock_check_sig = checksig
Miss Islington (bot)6a129312018-12-12 00:58:36 -0800105 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700106
107
108def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700109 # we explicitly don't copy func.__dict__ into this copy as it would
110 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300111 for attribute in (
112 '__name__', '__doc__', '__text_signature__',
113 '__module__', '__defaults__', '__kwdefaults__',
114 ):
115 try:
116 setattr(funcopy, attribute, getattr(func, attribute))
117 except AttributeError:
118 pass
Michael Foord345266a2012-03-14 12:24:34 -0700119
120
121def _callable(obj):
122 if isinstance(obj, type):
123 return True
124 if getattr(obj, '__call__', None) is not None:
125 return True
126 return False
127
128
129def _is_list(obj):
130 # checks for list or tuples
131 # XXXX badly named!
132 return type(obj) in (list, tuple)
133
134
135def _instance_callable(obj):
136 """Given an object, return True if the object is callable.
137 For classes, return True if instances would be callable."""
138 if not isinstance(obj, type):
139 # already an instance
140 return getattr(obj, '__call__', None) is not None
141
Michael Foorda74b3aa2012-03-14 14:40:22 -0700142 # *could* be broken by a class overriding __mro__ or __dict__ via
143 # a metaclass
144 for base in (obj,) + obj.__mro__:
145 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700146 return True
147 return False
148
149
150def _set_signature(mock, original, instance=False):
151 # creates a function with signature (*args, **kwargs) that delegates to a
152 # mock. It still does signature checking by calling a lambda with the same
153 # signature as the original.
154 if not _callable(original):
155 return
156
157 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100158 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700159 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700160 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100161 func, sig = result
162 def checksig(*args, **kwargs):
163 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700164 _copy_func_details(func, checksig)
165
166 name = original.__name__
167 if not name.isidentifier():
168 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100169 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700170 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100171 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700172 return mock(*args, **kwargs)""" % name
173 exec (src, context)
174 funcopy = context[name]
Miss Islington (bot)6a129312018-12-12 00:58:36 -0800175 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700176 return funcopy
177
178
Miss Islington (bot)6a129312018-12-12 00:58:36 -0800179def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700180 funcopy.mock = mock
181
182 # can't use isinstance with mocks
183 if not _is_instance_mock(mock):
184 return
185
186 def assert_called_with(*args, **kwargs):
187 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700188 def assert_called(*args, **kwargs):
189 return mock.assert_called(*args, **kwargs)
190 def assert_not_called(*args, **kwargs):
191 return mock.assert_not_called(*args, **kwargs)
192 def assert_called_once(*args, **kwargs):
193 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700194 def assert_called_once_with(*args, **kwargs):
195 return mock.assert_called_once_with(*args, **kwargs)
196 def assert_has_calls(*args, **kwargs):
197 return mock.assert_has_calls(*args, **kwargs)
198 def assert_any_call(*args, **kwargs):
199 return mock.assert_any_call(*args, **kwargs)
200 def reset_mock():
201 funcopy.method_calls = _CallList()
202 funcopy.mock_calls = _CallList()
203 mock.reset_mock()
204 ret = funcopy.return_value
205 if _is_instance_mock(ret) and not ret is mock:
206 ret.reset_mock()
207
208 funcopy.called = False
209 funcopy.call_count = 0
210 funcopy.call_args = None
211 funcopy.call_args_list = _CallList()
212 funcopy.method_calls = _CallList()
213 funcopy.mock_calls = _CallList()
214
215 funcopy.return_value = mock.return_value
216 funcopy.side_effect = mock.side_effect
217 funcopy._mock_children = mock._mock_children
218
219 funcopy.assert_called_with = assert_called_with
220 funcopy.assert_called_once_with = assert_called_once_with
221 funcopy.assert_has_calls = assert_has_calls
222 funcopy.assert_any_call = assert_any_call
223 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700224 funcopy.assert_called = assert_called
225 funcopy.assert_not_called = assert_not_called
226 funcopy.assert_called_once = assert_called_once
Miss Islington (bot)6a129312018-12-12 00:58:36 -0800227 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700228
229 mock._mock_delegate = funcopy
230
231
232def _is_magic(name):
233 return '__%s__' % name[2:-2] == name
234
235
236class _SentinelObject(object):
237 "A unique, named, sentinel object."
238 def __init__(self, name):
239 self.name = name
240
241 def __repr__(self):
242 return 'sentinel.%s' % self.name
243
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200244 def __reduce__(self):
245 return 'sentinel.%s' % self.name
246
Michael Foord345266a2012-03-14 12:24:34 -0700247
248class _Sentinel(object):
249 """Access attributes to return a named object, usable as a sentinel."""
250 def __init__(self):
251 self._sentinels = {}
252
253 def __getattr__(self, name):
254 if name == '__bases__':
255 # Without this help(unittest.mock) raises an exception
256 raise AttributeError
257 return self._sentinels.setdefault(name, _SentinelObject(name))
258
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200259 def __reduce__(self):
260 return 'sentinel'
261
Michael Foord345266a2012-03-14 12:24:34 -0700262
263sentinel = _Sentinel()
264
265DEFAULT = sentinel.DEFAULT
266_missing = sentinel.MISSING
267_deleted = sentinel.DELETED
268
269
Michael Foord345266a2012-03-14 12:24:34 -0700270def _copy(value):
271 if type(value) in (dict, list, tuple, set):
272 return type(value)(value)
273 return value
274
275
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200276_allowed_names = {
277 'return_value', '_mock_return_value', 'side_effect',
278 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
279 '_mock_name', '_mock_new_name'
280}
Michael Foord345266a2012-03-14 12:24:34 -0700281
282
283def _delegating_property(name):
284 _allowed_names.add(name)
285 _the_name = '_mock_' + name
286 def _get(self, name=name, _the_name=_the_name):
287 sig = self._mock_delegate
288 if sig is None:
289 return getattr(self, _the_name)
290 return getattr(sig, name)
291 def _set(self, value, name=name, _the_name=_the_name):
292 sig = self._mock_delegate
293 if sig is None:
294 self.__dict__[_the_name] = value
295 else:
296 setattr(sig, name, value)
297
298 return property(_get, _set)
299
300
301
302class _CallList(list):
303
304 def __contains__(self, value):
305 if not isinstance(value, list):
306 return list.__contains__(self, value)
307 len_value = len(value)
308 len_self = len(self)
309 if len_value > len_self:
310 return False
311
312 for i in range(0, len_self - len_value + 1):
313 sub_list = self[i:i+len_value]
314 if sub_list == value:
315 return True
316 return False
317
318 def __repr__(self):
319 return pprint.pformat(list(self))
320
321
322def _check_and_set_parent(parent, value, name, new_name):
323 if not _is_instance_mock(value):
324 return False
325 if ((value._mock_name or value._mock_new_name) or
326 (value._mock_parent is not None) or
327 (value._mock_new_parent is not None)):
328 return False
329
330 _parent = parent
331 while _parent is not None:
332 # setting a mock (value) as a child or return value of itself
333 # should not modify the mock
334 if _parent is value:
335 return False
336 _parent = _parent._mock_new_parent
337
338 if new_name:
339 value._mock_new_parent = parent
340 value._mock_new_name = new_name
341 if name:
342 value._mock_parent = parent
343 value._mock_name = name
344 return True
345
Michael Foord01bafdc2014-04-14 16:09:42 -0400346# Internal class to identify if we wrapped an iterator object or not.
347class _MockIter(object):
348 def __init__(self, obj):
349 self.obj = iter(obj)
350 def __iter__(self):
351 return self
352 def __next__(self):
353 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700354
355class Base(object):
356 _mock_return_value = DEFAULT
357 _mock_side_effect = None
358 def __init__(self, *args, **kwargs):
359 pass
360
361
362
363class NonCallableMock(Base):
364 """A non-callable version of `Mock`"""
365
366 def __new__(cls, *args, **kw):
367 # every instance has its own class
368 # so we can create magic methods on the
369 # class without stomping on other mocks
370 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
371 instance = object.__new__(new)
372 return instance
373
374
375 def __init__(
376 self, spec=None, wraps=None, name=None, spec_set=None,
377 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530378 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700379 ):
380 if _new_parent is None:
381 _new_parent = parent
382
383 __dict__ = self.__dict__
384 __dict__['_mock_parent'] = parent
385 __dict__['_mock_name'] = name
386 __dict__['_mock_new_name'] = _new_name
387 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100388 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700389
390 if spec_set is not None:
391 spec = spec_set
392 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100393 if _eat_self is None:
394 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700395
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100396 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700397
398 __dict__['_mock_children'] = {}
399 __dict__['_mock_wraps'] = wraps
400 __dict__['_mock_delegate'] = None
401
402 __dict__['_mock_called'] = False
403 __dict__['_mock_call_args'] = None
404 __dict__['_mock_call_count'] = 0
405 __dict__['_mock_call_args_list'] = _CallList()
406 __dict__['_mock_mock_calls'] = _CallList()
407
408 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530409 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700410
411 if kwargs:
412 self.configure_mock(**kwargs)
413
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000414 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700415 spec, wraps, name, spec_set, parent,
416 _spec_state
417 )
418
419
420 def attach_mock(self, mock, attribute):
421 """
422 Attach a mock as an attribute of this one, replacing its name and
423 parent. Calls to the attached mock will be recorded in the
424 `method_calls` and `mock_calls` attributes of this one."""
425 mock._mock_parent = None
426 mock._mock_new_parent = None
427 mock._mock_name = ''
428 mock._mock_new_name = None
429
430 setattr(self, attribute, mock)
431
432
433 def mock_add_spec(self, spec, spec_set=False):
434 """Add a spec to a mock. `spec` can either be an object or a
435 list of strings. Only attributes on the `spec` can be fetched as
436 attributes from the mock.
437
438 If `spec_set` is True then only attributes on the spec can be set."""
439 self._mock_add_spec(spec, spec_set)
440
441
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100442 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
443 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700444 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100445 _spec_signature = None
Michael Foord345266a2012-03-14 12:24:34 -0700446
447 if spec is not None and not _is_list(spec):
448 if isinstance(spec, type):
449 _spec_class = spec
450 else:
451 _spec_class = _get_class(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100452 res = _get_signature_object(spec,
453 _spec_as_instance, _eat_self)
454 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700455
456 spec = dir(spec)
457
458 __dict__ = self.__dict__
459 __dict__['_spec_class'] = _spec_class
460 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100461 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700462 __dict__['_mock_methods'] = spec
463
464
465 def __get_return_value(self):
466 ret = self._mock_return_value
467 if self._mock_delegate is not None:
468 ret = self._mock_delegate.return_value
469
470 if ret is DEFAULT:
471 ret = self._get_child_mock(
472 _new_parent=self, _new_name='()'
473 )
474 self.return_value = ret
475 return ret
476
477
478 def __set_return_value(self, value):
479 if self._mock_delegate is not None:
480 self._mock_delegate.return_value = value
481 else:
482 self._mock_return_value = value
483 _check_and_set_parent(self, value, None, '()')
484
485 __return_value_doc = "The value to be returned when the mock is called."
486 return_value = property(__get_return_value, __set_return_value,
487 __return_value_doc)
488
489
490 @property
491 def __class__(self):
492 if self._spec_class is None:
493 return type(self)
494 return self._spec_class
495
496 called = _delegating_property('called')
497 call_count = _delegating_property('call_count')
498 call_args = _delegating_property('call_args')
499 call_args_list = _delegating_property('call_args_list')
500 mock_calls = _delegating_property('mock_calls')
501
502
503 def __get_side_effect(self):
504 delegated = self._mock_delegate
505 if delegated is None:
506 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400507 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200508 if (sf is not None and not callable(sf)
509 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400510 sf = _MockIter(sf)
511 delegated.side_effect = sf
512 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700513
514 def __set_side_effect(self, value):
515 value = _try_iter(value)
516 delegated = self._mock_delegate
517 if delegated is None:
518 self._mock_side_effect = value
519 else:
520 delegated.side_effect = value
521
522 side_effect = property(__get_side_effect, __set_side_effect)
523
524
Kushal Das9cd39a12016-06-02 10:20:16 -0700525 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700526 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200527 if visited is None:
528 visited = []
529 if id(self) in visited:
530 return
531 visited.append(id(self))
532
Michael Foord345266a2012-03-14 12:24:34 -0700533 self.called = False
534 self.call_args = None
535 self.call_count = 0
536 self.mock_calls = _CallList()
537 self.call_args_list = _CallList()
538 self.method_calls = _CallList()
539
Kushal Das9cd39a12016-06-02 10:20:16 -0700540 if return_value:
541 self._mock_return_value = DEFAULT
542 if side_effect:
543 self._mock_side_effect = None
544
Michael Foord345266a2012-03-14 12:24:34 -0700545 for child in self._mock_children.values():
Miss Islington (bot)422c1652018-12-01 02:24:47 -0800546 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100547 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200548 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700549
550 ret = self._mock_return_value
551 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200552 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700553
554
555 def configure_mock(self, **kwargs):
556 """Set attributes on the mock through keyword arguments.
557
558 Attributes plus return values and side effects can be set on child
559 mocks using standard dot notation and unpacking a dictionary in the
560 method call:
561
562 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
563 >>> mock.configure_mock(**attrs)"""
564 for arg, val in sorted(kwargs.items(),
565 # we sort on the number of dots so that
566 # attributes are set before we set attributes on
567 # attributes
568 key=lambda entry: entry[0].count('.')):
569 args = arg.split('.')
570 final = args.pop()
571 obj = self
572 for entry in args:
573 obj = getattr(obj, entry)
574 setattr(obj, final, val)
575
576
577 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530578 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700579 raise AttributeError(name)
580 elif self._mock_methods is not None:
581 if name not in self._mock_methods or name in _all_magics:
582 raise AttributeError("Mock object has no attribute %r" % name)
583 elif _is_magic(name):
584 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530585 if not self._mock_unsafe:
586 if name.startswith(('assert', 'assret')):
587 raise AttributeError(name)
Michael Foord345266a2012-03-14 12:24:34 -0700588
589 result = self._mock_children.get(name)
590 if result is _deleted:
591 raise AttributeError(name)
592 elif result is None:
593 wraps = None
594 if self._mock_wraps is not None:
595 # XXXX should we get the attribute without triggering code
596 # execution?
597 wraps = getattr(self._mock_wraps, name)
598
599 result = self._get_child_mock(
600 parent=self, name=name, wraps=wraps, _new_name=name,
601 _new_parent=self
602 )
603 self._mock_children[name] = result
604
605 elif isinstance(result, _SpecState):
606 result = create_autospec(
607 result.spec, result.spec_set, result.instance,
608 result.parent, result.name
609 )
610 self._mock_children[name] = result
611
612 return result
613
614
Mario Corchero552be9d2017-10-17 12:35:11 +0100615 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700616 _name_list = [self._mock_new_name]
617 _parent = self._mock_new_parent
618 last = self
619
620 dot = '.'
621 if _name_list == ['()']:
622 dot = ''
623 seen = set()
624 while _parent is not None:
625 last = _parent
626
627 _name_list.append(_parent._mock_new_name + dot)
628 dot = '.'
629 if _parent._mock_new_name == '()':
630 dot = ''
631
632 _parent = _parent._mock_new_parent
633
634 # use ids here so as not to call __hash__ on the mocks
635 if id(_parent) in seen:
636 break
637 seen.add(id(_parent))
638
639 _name_list = list(reversed(_name_list))
640 _first = last._mock_name or 'mock'
641 if len(_name_list) > 1:
642 if _name_list[1] not in ('()', '().'):
643 _first += '.'
644 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100645 return ''.join(_name_list)
646
647 def __repr__(self):
648 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700649
650 name_string = ''
651 if name not in ('mock', 'mock.'):
652 name_string = ' name=%r' % name
653
654 spec_string = ''
655 if self._spec_class is not None:
656 spec_string = ' spec=%r'
657 if self._spec_set:
658 spec_string = ' spec_set=%r'
659 spec_string = spec_string % self._spec_class.__name__
660 return "<%s%s%s id='%s'>" % (
661 type(self).__name__,
662 name_string,
663 spec_string,
664 id(self)
665 )
666
667
668 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700669 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100670 if not FILTER_DIR:
671 return object.__dir__(self)
672
Michael Foord345266a2012-03-14 12:24:34 -0700673 extras = self._mock_methods or []
674 from_type = dir(type(self))
675 from_dict = list(self.__dict__)
676
Michael Foord313f85f2012-03-25 18:16:07 +0100677 from_type = [e for e in from_type if not e.startswith('_')]
678 from_dict = [e for e in from_dict if not e.startswith('_') or
679 _is_magic(e)]
Michael Foord345266a2012-03-14 12:24:34 -0700680 return sorted(set(extras + from_type + from_dict +
681 list(self._mock_children)))
682
683
684 def __setattr__(self, name, value):
685 if name in _allowed_names:
686 # property setters go through here
687 return object.__setattr__(self, name, value)
688 elif (self._spec_set and self._mock_methods is not None and
689 name not in self._mock_methods and
690 name not in self.__dict__):
691 raise AttributeError("Mock object has no attribute '%s'" % name)
692 elif name in _unsupported_magics:
693 msg = 'Attempting to set unsupported magic method %r.' % name
694 raise AttributeError(msg)
695 elif name in _all_magics:
696 if self._mock_methods is not None and name not in self._mock_methods:
697 raise AttributeError("Mock object has no attribute '%s'" % name)
698
699 if not _is_instance_mock(value):
700 setattr(type(self), name, _get_method(name, value))
701 original = value
702 value = lambda *args, **kw: original(self, *args, **kw)
703 else:
704 # only set _new_name and not name so that mock_calls is tracked
705 # but not method calls
706 _check_and_set_parent(self, value, None, name)
707 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100708 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700709 elif name == '__class__':
710 self._spec_class = value
711 return
712 else:
713 if _check_and_set_parent(self, value, name, name):
714 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100715
716 if self._mock_sealed and not hasattr(self, name):
717 mock_name = f'{self._extract_mock_name()}.{name}'
718 raise AttributeError(f'Cannot set {mock_name}')
719
Michael Foord345266a2012-03-14 12:24:34 -0700720 return object.__setattr__(self, name, value)
721
722
723 def __delattr__(self, name):
724 if name in _all_magics and name in type(self).__dict__:
725 delattr(type(self), name)
726 if name not in self.__dict__:
727 # for magic methods that are still MagicProxy objects and
728 # not set on the instance itself
729 return
730
731 if name in self.__dict__:
732 object.__delattr__(self, name)
733
734 obj = self._mock_children.get(name, _missing)
735 if obj is _deleted:
736 raise AttributeError(name)
737 if obj is not _missing:
738 del self._mock_children[name]
739 self._mock_children[name] = _deleted
740
741
Michael Foord345266a2012-03-14 12:24:34 -0700742 def _format_mock_call_signature(self, args, kwargs):
743 name = self._mock_name or 'mock'
744 return _format_call_signature(name, args, kwargs)
745
746
747 def _format_mock_failure_message(self, args, kwargs):
748 message = 'Expected call: %s\nActual call: %s'
749 expected_string = self._format_mock_call_signature(args, kwargs)
750 call_args = self.call_args
751 if len(call_args) == 3:
752 call_args = call_args[1:]
753 actual_string = self._format_mock_call_signature(*call_args)
754 return message % (expected_string, actual_string)
755
756
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100757 def _call_matcher(self, _call):
758 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000759 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100760 comparison key suitable for matching with other calls.
761 This is a best effort method which relies on the spec's signature,
762 if available, or falls back on the arguments themselves.
763 """
764 sig = self._spec_signature
765 if sig is not None:
766 if len(_call) == 2:
767 name = ''
768 args, kwargs = _call
769 else:
770 name, args, kwargs = _call
771 try:
772 return name, sig.bind(*args, **kwargs)
773 except TypeError as e:
774 return e.with_traceback(None)
775 else:
776 return _call
777
Kushal Das68290f42014-04-17 01:54:07 +0530778 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530779 """assert that the mock was never called.
780 """
781 self = _mock_self
782 if self.call_count != 0:
783 msg = ("Expected '%s' to not have been called. Called %s times." %
784 (self._mock_name or 'mock', self.call_count))
785 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100786
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100787 def assert_called(_mock_self):
788 """assert that the mock was called at least once
789 """
790 self = _mock_self
791 if self.call_count == 0:
792 msg = ("Expected '%s' to have been called." %
793 self._mock_name or 'mock')
794 raise AssertionError(msg)
795
796 def assert_called_once(_mock_self):
797 """assert that the mock was called only once.
798 """
799 self = _mock_self
800 if not self.call_count == 1:
801 msg = ("Expected '%s' to have been called once. Called %s times." %
802 (self._mock_name or 'mock', self.call_count))
803 raise AssertionError(msg)
804
Michael Foord345266a2012-03-14 12:24:34 -0700805 def assert_called_with(_mock_self, *args, **kwargs):
806 """assert that the mock was called with the specified arguments.
807
808 Raises an AssertionError if the args and keyword args passed in are
809 different to the last call to the mock."""
810 self = _mock_self
811 if self.call_args is None:
812 expected = self._format_mock_call_signature(args, kwargs)
813 raise AssertionError('Expected call: %s\nNot called' % (expected,))
814
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100815 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700816 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100817 return msg
818 expected = self._call_matcher((args, kwargs))
819 actual = self._call_matcher(self.call_args)
820 if expected != actual:
821 cause = expected if isinstance(expected, Exception) else None
822 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700823
824
825 def assert_called_once_with(_mock_self, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100826 """assert that the mock was called exactly once and that that call was
827 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700828 self = _mock_self
829 if not self.call_count == 1:
Michael Foord28d591c2012-09-28 16:15:22 +0100830 msg = ("Expected '%s' to be called once. Called %s times." %
831 (self._mock_name or 'mock', self.call_count))
Michael Foord345266a2012-03-14 12:24:34 -0700832 raise AssertionError(msg)
833 return self.assert_called_with(*args, **kwargs)
834
835
836 def assert_has_calls(self, calls, any_order=False):
837 """assert the mock has been called with the specified calls.
838 The `mock_calls` list is checked for the calls.
839
840 If `any_order` is False (the default) then the calls must be
841 sequential. There can be extra calls before or after the
842 specified calls.
843
844 If `any_order` is True then the calls can be in any order, but
845 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100846 expected = [self._call_matcher(c) for c in calls]
847 cause = expected if isinstance(expected, Exception) else None
848 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700849 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100850 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700851 raise AssertionError(
852 'Calls not found.\nExpected: %r\n'
Senthil Kumaran121edbf2016-01-12 06:18:32 -0800853 'Actual: %r' % (_CallList(calls), self.mock_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100854 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700855 return
856
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100857 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700858
859 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100860 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700861 try:
862 all_calls.remove(kall)
863 except ValueError:
864 not_found.append(kall)
865 if not_found:
866 raise AssertionError(
867 '%r not all found in call list' % (tuple(not_found),)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100868 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700869
870
871 def assert_any_call(self, *args, **kwargs):
872 """assert the mock has been called with the specified arguments.
873
874 The assert passes if the mock has *ever* been called, unlike
875 `assert_called_with` and `assert_called_once_with` that only pass if
876 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100877 expected = self._call_matcher((args, kwargs))
878 actual = [self._call_matcher(c) for c in self.call_args_list]
879 if expected not in actual:
880 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700881 expected_string = self._format_mock_call_signature(args, kwargs)
882 raise AssertionError(
883 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100884 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700885
886
887 def _get_child_mock(self, **kw):
888 """Create the child mocks for attributes and return value.
889 By default child mocks will be the same type as the parent.
890 Subclasses of Mock may want to override this to customize the way
891 child mocks are made.
892
893 For non-callable mocks the callable variant will be used (rather than
894 any custom subclass)."""
895 _type = type(self)
896 if not issubclass(_type, CallableMixin):
897 if issubclass(_type, NonCallableMagicMock):
898 klass = MagicMock
899 elif issubclass(_type, NonCallableMock) :
900 klass = Mock
901 else:
902 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +0100903
904 if self._mock_sealed:
905 attribute = "." + kw["name"] if "name" in kw else "()"
906 mock_name = self._extract_mock_name() + attribute
907 raise AttributeError(mock_name)
908
Michael Foord345266a2012-03-14 12:24:34 -0700909 return klass(**kw)
910
911
912
913def _try_iter(obj):
914 if obj is None:
915 return obj
916 if _is_exception(obj):
917 return obj
918 if _callable(obj):
919 return obj
920 try:
921 return iter(obj)
922 except TypeError:
923 # XXXX backwards compatibility
924 # but this will blow up on first call - so maybe we should fail early?
925 return obj
926
927
928
929class CallableMixin(Base):
930
931 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
932 wraps=None, name=None, spec_set=None, parent=None,
933 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
934 self.__dict__['_mock_return_value'] = return_value
935
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000936 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700937 spec, wraps, name, spec_set, parent,
938 _spec_state, _new_name, _new_parent, **kwargs
939 )
940
941 self.side_effect = side_effect
942
943
944 def _mock_check_sig(self, *args, **kwargs):
945 # stub method that can be replaced with one with a specific signature
946 pass
947
948
949 def __call__(_mock_self, *args, **kwargs):
950 # can't use self in-case a function / method we are mocking uses self
951 # in the signature
952 _mock_self._mock_check_sig(*args, **kwargs)
953 return _mock_self._mock_call(*args, **kwargs)
954
955
956 def _mock_call(_mock_self, *args, **kwargs):
957 self = _mock_self
958 self.called = True
959 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100960
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800961 # handle call_args
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100962 _call = _Call((args, kwargs), two=True)
963 self.call_args = _call
964 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -0700965
966 seen = set()
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800967
968 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700969 do_method_calls = self._mock_parent is not None
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800970 method_call_name = self._mock_name
971
972 # initial stuff for mock_calls:
973 mock_call_name = self._mock_new_name
974 is_a_call = mock_call_name == '()'
975 self.mock_calls.append(_Call(('', args, kwargs)))
976
977 # follow up the chain of mocks:
978 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -0700979 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700980
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800981 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700982 if do_method_calls:
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800983 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -0700984 do_method_calls = _new_parent._mock_parent is not None
985 if do_method_calls:
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800986 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -0700987
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800988 # handle mock_calls:
989 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -0700990 _new_parent.mock_calls.append(this_mock_call)
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800991
992 if _new_parent._mock_new_name:
993 if is_a_call:
994 dot = ''
995 else:
996 dot = '.'
997 is_a_call = _new_parent._mock_new_name == '()'
998 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
999
1000 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001001 _new_parent = _new_parent._mock_new_parent
1002
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -08001003 # check we're not in an infinite loop:
1004 # ( use ids here so as not to call __hash__ on the mocks)
Michael Foord345266a2012-03-14 12:24:34 -07001005 _new_parent_id = id(_new_parent)
1006 if _new_parent_id in seen:
1007 break
1008 seen.add(_new_parent_id)
1009
Michael Foord345266a2012-03-14 12:24:34 -07001010 effect = self.side_effect
1011 if effect is not None:
1012 if _is_exception(effect):
1013 raise effect
Miss Islington (bot)ee2c5a82018-12-08 03:47:01 -08001014 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001015 result = next(effect)
1016 if _is_exception(result):
1017 raise result
Miss Islington (bot)ee2c5a82018-12-08 03:47:01 -08001018 else:
1019 result = effect(*args, **kwargs)
1020
1021 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001022 return result
Michael Foord345266a2012-03-14 12:24:34 -07001023
Miss Islington (bot)ee2c5a82018-12-08 03:47:01 -08001024 if self._mock_return_value is not DEFAULT:
1025 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001026
Miss Islington (bot)ee2c5a82018-12-08 03:47:01 -08001027 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001028 return self._mock_wraps(*args, **kwargs)
Miss Islington (bot)ee2c5a82018-12-08 03:47:01 -08001029
1030 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001031
1032
1033
1034class Mock(CallableMixin, NonCallableMock):
1035 """
1036 Create a new `Mock` object. `Mock` takes several optional arguments
1037 that specify the behaviour of the Mock object:
1038
1039 * `spec`: This can be either a list of strings or an existing object (a
1040 class or instance) that acts as the specification for the mock object. If
1041 you pass in an object then a list of strings is formed by calling dir on
1042 the object (excluding unsupported magic attributes and methods). Accessing
1043 any attribute not in this list will raise an `AttributeError`.
1044
1045 If `spec` is an object (rather than a list of strings) then
1046 `mock.__class__` returns the class of the spec object. This allows mocks
1047 to pass `isinstance` tests.
1048
1049 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1050 or get an attribute on the mock that isn't on the object passed as
1051 `spec_set` will raise an `AttributeError`.
1052
1053 * `side_effect`: A function to be called whenever the Mock is called. See
1054 the `side_effect` attribute. Useful for raising exceptions or
1055 dynamically changing return values. The function is called with the same
1056 arguments as the mock, and unless it returns `DEFAULT`, the return
1057 value of this function is used as the return value.
1058
Michael Foord2cd48732012-04-21 15:52:11 +01001059 If `side_effect` is an iterable then each call to the mock will return
1060 the next value from the iterable. If any of the members of the iterable
1061 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001062
Michael Foord345266a2012-03-14 12:24:34 -07001063 * `return_value`: The value returned when the mock is called. By default
1064 this is a new Mock (created on first access). See the
1065 `return_value` attribute.
1066
Michael Foord0682a0c2012-04-13 20:51:20 +01001067 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1068 calling the Mock will pass the call through to the wrapped object
1069 (returning the real result). Attribute access on the mock will return a
1070 Mock object that wraps the corresponding attribute of the wrapped object
1071 (so attempting to access an attribute that doesn't exist will raise an
1072 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001073
1074 If the mock has an explicit `return_value` set then calls are not passed
1075 to the wrapped object and the `return_value` is returned instead.
1076
1077 * `name`: If the mock has a name then it will be used in the repr of the
1078 mock. This can be useful for debugging. The name is propagated to child
1079 mocks.
1080
1081 Mocks can also be called with arbitrary keyword arguments. These will be
1082 used to set attributes on the mock after it is created.
1083 """
1084
1085
1086
1087def _dot_lookup(thing, comp, import_path):
1088 try:
1089 return getattr(thing, comp)
1090 except AttributeError:
1091 __import__(import_path)
1092 return getattr(thing, comp)
1093
1094
1095def _importer(target):
1096 components = target.split('.')
1097 import_path = components.pop(0)
1098 thing = __import__(import_path)
1099
1100 for comp in components:
1101 import_path += ".%s" % comp
1102 thing = _dot_lookup(thing, comp, import_path)
1103 return thing
1104
1105
1106def _is_started(patcher):
1107 # XXXX horrible
1108 return hasattr(patcher, 'is_local')
1109
1110
1111class _patch(object):
1112
1113 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001114 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001115
1116 def __init__(
1117 self, getter, attribute, new, spec, create,
1118 spec_set, autospec, new_callable, kwargs
1119 ):
1120 if new_callable is not None:
1121 if new is not DEFAULT:
1122 raise ValueError(
1123 "Cannot use 'new' and 'new_callable' together"
1124 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001125 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001126 raise ValueError(
1127 "Cannot use 'autospec' and 'new_callable' together"
1128 )
1129
1130 self.getter = getter
1131 self.attribute = attribute
1132 self.new = new
1133 self.new_callable = new_callable
1134 self.spec = spec
1135 self.create = create
1136 self.has_local = False
1137 self.spec_set = spec_set
1138 self.autospec = autospec
1139 self.kwargs = kwargs
1140 self.additional_patchers = []
1141
1142
1143 def copy(self):
1144 patcher = _patch(
1145 self.getter, self.attribute, self.new, self.spec,
1146 self.create, self.spec_set,
1147 self.autospec, self.new_callable, self.kwargs
1148 )
1149 patcher.attribute_name = self.attribute_name
1150 patcher.additional_patchers = [
1151 p.copy() for p in self.additional_patchers
1152 ]
1153 return patcher
1154
1155
1156 def __call__(self, func):
1157 if isinstance(func, type):
1158 return self.decorate_class(func)
1159 return self.decorate_callable(func)
1160
1161
1162 def decorate_class(self, klass):
1163 for attr in dir(klass):
1164 if not attr.startswith(patch.TEST_PREFIX):
1165 continue
1166
1167 attr_value = getattr(klass, attr)
1168 if not hasattr(attr_value, "__call__"):
1169 continue
1170
1171 patcher = self.copy()
1172 setattr(klass, attr, patcher(attr_value))
1173 return klass
1174
1175
1176 def decorate_callable(self, func):
1177 if hasattr(func, 'patchings'):
1178 func.patchings.append(self)
1179 return func
1180
1181 @wraps(func)
1182 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001183 extra_args = []
1184 entered_patchers = []
1185
Michael Foord50a8c0e2012-03-25 18:57:58 +01001186 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001187 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001188 for patching in patched.patchings:
1189 arg = patching.__enter__()
1190 entered_patchers.append(patching)
1191 if patching.attribute_name is not None:
1192 keywargs.update(arg)
1193 elif patching.new is DEFAULT:
1194 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001195
Michael Foordd7c65e22012-03-14 14:56:54 -07001196 args += tuple(extra_args)
1197 return func(*args, **keywargs)
1198 except:
1199 if (patching not in entered_patchers and
1200 _is_started(patching)):
1201 # the patcher may have been started, but an exception
1202 # raised whilst entering one of its additional_patchers
1203 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001204 # Pass the exception to __exit__
1205 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001206 # re-raise the exception
1207 raise
Michael Foord345266a2012-03-14 12:24:34 -07001208 finally:
1209 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001210 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001211
1212 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001213 return patched
1214
1215
1216 def get_original(self):
1217 target = self.getter()
1218 name = self.attribute
1219
1220 original = DEFAULT
1221 local = False
1222
1223 try:
1224 original = target.__dict__[name]
1225 except (AttributeError, KeyError):
1226 original = getattr(target, name, DEFAULT)
1227 else:
1228 local = True
1229
Michael Foordfddcfa22014-04-14 16:25:20 -04001230 if name in _builtins and isinstance(target, ModuleType):
1231 self.create = True
1232
Michael Foord345266a2012-03-14 12:24:34 -07001233 if not self.create and original is DEFAULT:
1234 raise AttributeError(
1235 "%s does not have the attribute %r" % (target, name)
1236 )
1237 return original, local
1238
1239
1240 def __enter__(self):
1241 """Perform the patch."""
1242 new, spec, spec_set = self.new, self.spec, self.spec_set
1243 autospec, kwargs = self.autospec, self.kwargs
1244 new_callable = self.new_callable
1245 self.target = self.getter()
1246
Michael Foord50a8c0e2012-03-25 18:57:58 +01001247 # normalise False to None
1248 if spec is False:
1249 spec = None
1250 if spec_set is False:
1251 spec_set = None
1252 if autospec is False:
1253 autospec = None
1254
1255 if spec is not None and autospec is not None:
1256 raise TypeError("Can't specify spec and autospec")
1257 if ((spec is not None or autospec is not None) and
1258 spec_set not in (True, None)):
1259 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1260
Michael Foord345266a2012-03-14 12:24:34 -07001261 original, local = self.get_original()
1262
Michael Foord50a8c0e2012-03-25 18:57:58 +01001263 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001264 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001265 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001266 # set spec to the object we are replacing
1267 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001268 if spec_set is True:
1269 spec_set = original
1270 spec = None
1271 elif spec is not None:
1272 if spec_set is True:
1273 spec_set = spec
1274 spec = None
1275 elif spec_set is True:
1276 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001277
Michael Foord50a8c0e2012-03-25 18:57:58 +01001278 if spec is not None or spec_set is not None:
1279 if original is DEFAULT:
1280 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001281 if isinstance(original, type):
1282 # If we're patching out a class and there is a spec
1283 inherit = True
1284
1285 Klass = MagicMock
1286 _kwargs = {}
1287 if new_callable is not None:
1288 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001289 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001290 this_spec = spec
1291 if spec_set is not None:
1292 this_spec = spec_set
1293 if _is_list(this_spec):
1294 not_callable = '__call__' not in this_spec
1295 else:
1296 not_callable = not callable(this_spec)
1297 if not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001298 Klass = NonCallableMagicMock
1299
1300 if spec is not None:
1301 _kwargs['spec'] = spec
1302 if spec_set is not None:
1303 _kwargs['spec_set'] = spec_set
1304
1305 # add a name to mocks
1306 if (isinstance(Klass, type) and
1307 issubclass(Klass, NonCallableMock) and self.attribute):
1308 _kwargs['name'] = self.attribute
1309
1310 _kwargs.update(kwargs)
1311 new = Klass(**_kwargs)
1312
1313 if inherit and _is_instance_mock(new):
1314 # we can only tell if the instance should be callable if the
1315 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001316 this_spec = spec
1317 if spec_set is not None:
1318 this_spec = spec_set
1319 if (not _is_list(this_spec) and not
1320 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001321 Klass = NonCallableMagicMock
1322
1323 _kwargs.pop('name')
1324 new.return_value = Klass(_new_parent=new, _new_name='()',
1325 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001326 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001327 # spec is ignored, new *must* be default, spec_set is treated
1328 # as a boolean. Should we check spec is not None and that spec_set
1329 # is a bool?
1330 if new is not DEFAULT:
1331 raise TypeError(
1332 "autospec creates the mock for you. Can't specify "
1333 "autospec and new."
1334 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001335 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001336 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001337 spec_set = bool(spec_set)
1338 if autospec is True:
1339 autospec = original
1340
1341 new = create_autospec(autospec, spec_set=spec_set,
1342 _name=self.attribute, **kwargs)
1343 elif kwargs:
1344 # can't set keyword args when we aren't creating the mock
1345 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1346 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1347
1348 new_attr = new
1349
1350 self.temp_original = original
1351 self.is_local = local
1352 setattr(self.target, self.attribute, new_attr)
1353 if self.attribute_name is not None:
1354 extra_args = {}
1355 if self.new is DEFAULT:
1356 extra_args[self.attribute_name] = new
1357 for patching in self.additional_patchers:
1358 arg = patching.__enter__()
1359 if patching.new is DEFAULT:
1360 extra_args.update(arg)
1361 return extra_args
1362
1363 return new
1364
1365
Michael Foord50a8c0e2012-03-25 18:57:58 +01001366 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001367 """Undo the patch."""
1368 if not _is_started(self):
1369 raise RuntimeError('stop called on unstarted patcher')
1370
1371 if self.is_local and self.temp_original is not DEFAULT:
1372 setattr(self.target, self.attribute, self.temp_original)
1373 else:
1374 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001375 if not self.create and (not hasattr(self.target, self.attribute) or
1376 self.attribute in ('__doc__', '__module__',
1377 '__defaults__', '__annotations__',
1378 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001379 # needed for proxy objects like django settings
1380 setattr(self.target, self.attribute, self.temp_original)
1381
1382 del self.temp_original
1383 del self.is_local
1384 del self.target
1385 for patcher in reversed(self.additional_patchers):
1386 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001387 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001388
Michael Foordf7c41582012-06-10 20:36:32 +01001389
1390 def start(self):
1391 """Activate a patch, returning any created mock."""
1392 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001393 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001394 return result
1395
1396
1397 def stop(self):
1398 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001399 try:
1400 self._active_patches.remove(self)
1401 except ValueError:
1402 # If the patch hasn't been started this will fail
1403 pass
1404
Michael Foordf7c41582012-06-10 20:36:32 +01001405 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001406
1407
1408
1409def _get_target(target):
1410 try:
1411 target, attribute = target.rsplit('.', 1)
1412 except (TypeError, ValueError):
1413 raise TypeError("Need a valid target to patch. You supplied: %r" %
1414 (target,))
1415 getter = lambda: _importer(target)
1416 return getter, attribute
1417
1418
1419def _patch_object(
1420 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001421 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001422 new_callable=None, **kwargs
1423 ):
1424 """
Michael Foord345266a2012-03-14 12:24:34 -07001425 patch the named member (`attribute`) on an object (`target`) with a mock
1426 object.
1427
1428 `patch.object` can be used as a decorator, class decorator or a context
1429 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1430 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1431 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1432 the mock object it creates.
1433
1434 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1435 for choosing which methods to wrap.
1436 """
1437 getter = lambda: target
1438 return _patch(
1439 getter, attribute, new, spec, create,
1440 spec_set, autospec, new_callable, kwargs
1441 )
1442
1443
Michael Foord50a8c0e2012-03-25 18:57:58 +01001444def _patch_multiple(target, spec=None, create=False, spec_set=None,
1445 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001446 """Perform multiple patches in a single call. It takes the object to be
1447 patched (either as an object or a string to fetch the object by importing)
1448 and keyword arguments for the patches::
1449
1450 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1451 ...
1452
1453 Use `DEFAULT` as the value if you want `patch.multiple` to create
1454 mocks for you. In this case the created mocks are passed into a decorated
1455 function by keyword, and a dictionary is returned when `patch.multiple` is
1456 used as a context manager.
1457
1458 `patch.multiple` can be used as a decorator, class decorator or a context
1459 manager. The arguments `spec`, `spec_set`, `create`,
1460 `autospec` and `new_callable` have the same meaning as for `patch`. These
1461 arguments will be applied to *all* patches done by `patch.multiple`.
1462
1463 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1464 for choosing which methods to wrap.
1465 """
1466 if type(target) is str:
1467 getter = lambda: _importer(target)
1468 else:
1469 getter = lambda: target
1470
1471 if not kwargs:
1472 raise ValueError(
1473 'Must supply at least one keyword argument with patch.multiple'
1474 )
1475 # need to wrap in a list for python 3, where items is a view
1476 items = list(kwargs.items())
1477 attribute, new = items[0]
1478 patcher = _patch(
1479 getter, attribute, new, spec, create, spec_set,
1480 autospec, new_callable, {}
1481 )
1482 patcher.attribute_name = attribute
1483 for attribute, new in items[1:]:
1484 this_patcher = _patch(
1485 getter, attribute, new, spec, create, spec_set,
1486 autospec, new_callable, {}
1487 )
1488 this_patcher.attribute_name = attribute
1489 patcher.additional_patchers.append(this_patcher)
1490 return patcher
1491
1492
1493def patch(
1494 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001495 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001496 ):
1497 """
1498 `patch` acts as a function decorator, class decorator or a context
1499 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001500 is patched with a `new` object. When the function/with statement exits
1501 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001502
Michael Foord54b3db82012-03-28 15:08:08 +01001503 If `new` is omitted, then the target is replaced with a
1504 `MagicMock`. If `patch` is used as a decorator and `new` is
1505 omitted, the created mock is passed in as an extra argument to the
1506 decorated function. If `patch` is used as a context manager the created
1507 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001508
Michael Foord54b3db82012-03-28 15:08:08 +01001509 `target` should be a string in the form `'package.module.ClassName'`. The
1510 `target` is imported and the specified object replaced with the `new`
1511 object, so the `target` must be importable from the environment you are
1512 calling `patch` from. The target is imported when the decorated function
1513 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001514
1515 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1516 if patch is creating one for you.
1517
1518 In addition you can pass `spec=True` or `spec_set=True`, which causes
1519 patch to pass in the object being mocked as the spec/spec_set object.
1520
1521 `new_callable` allows you to specify a different class, or callable object,
1522 that will be called to create the `new` object. By default `MagicMock` is
1523 used.
1524
1525 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001526 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001527 All attributes of the mock will also have the spec of the corresponding
1528 attribute of the object being replaced. Methods and functions being
1529 mocked will have their arguments checked and will raise a `TypeError` if
1530 they are called with the wrong signature. For mocks replacing a class,
1531 their return value (the 'instance') will have the same spec as the class.
1532
1533 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1534 arbitrary object as the spec instead of the one being replaced.
1535
1536 By default `patch` will fail to replace attributes that don't exist. If
1537 you pass in `create=True`, and the attribute doesn't exist, patch will
1538 create the attribute for you when the patched function is called, and
1539 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001540 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001541 default because it can be dangerous. With it switched on you can write
1542 passing tests against APIs that don't actually exist!
1543
1544 Patch can be used as a `TestCase` class decorator. It works by
1545 decorating each test method in the class. This reduces the boilerplate
1546 code when your test methods share a common patchings set. `patch` finds
1547 tests by looking for method names that start with `patch.TEST_PREFIX`.
1548 By default this is `test`, which matches the way `unittest` finds tests.
1549 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1550
1551 Patch can be used as a context manager, with the with statement. Here the
1552 patching applies to the indented block after the with statement. If you
1553 use "as" then the patched object will be bound to the name after the
1554 "as"; very useful if `patch` is creating a mock object for you.
1555
1556 `patch` takes arbitrary keyword arguments. These will be passed to
1557 the `Mock` (or `new_callable`) on construction.
1558
1559 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1560 available for alternate use-cases.
1561 """
1562 getter, attribute = _get_target(target)
1563 return _patch(
1564 getter, attribute, new, spec, create,
1565 spec_set, autospec, new_callable, kwargs
1566 )
1567
1568
1569class _patch_dict(object):
1570 """
1571 Patch a dictionary, or dictionary like object, and restore the dictionary
1572 to its original state after the test.
1573
1574 `in_dict` can be a dictionary or a mapping like container. If it is a
1575 mapping then it must at least support getting, setting and deleting items
1576 plus iterating over keys.
1577
1578 `in_dict` can also be a string specifying the name of the dictionary, which
1579 will then be fetched by importing it.
1580
1581 `values` can be a dictionary of values to set in the dictionary. `values`
1582 can also be an iterable of `(key, value)` pairs.
1583
1584 If `clear` is True then the dictionary will be cleared before the new
1585 values are set.
1586
1587 `patch.dict` can also be called with arbitrary keyword arguments to set
1588 values in the dictionary::
1589
1590 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1591 ...
1592
1593 `patch.dict` can be used as a context manager, decorator or class
1594 decorator. When used as a class decorator `patch.dict` honours
1595 `patch.TEST_PREFIX` for choosing which methods to wrap.
1596 """
1597
1598 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1599 if isinstance(in_dict, str):
1600 in_dict = _importer(in_dict)
1601 self.in_dict = in_dict
1602 # support any argument supported by dict(...) constructor
1603 self.values = dict(values)
1604 self.values.update(kwargs)
1605 self.clear = clear
1606 self._original = None
1607
1608
1609 def __call__(self, f):
1610 if isinstance(f, type):
1611 return self.decorate_class(f)
1612 @wraps(f)
1613 def _inner(*args, **kw):
1614 self._patch_dict()
1615 try:
1616 return f(*args, **kw)
1617 finally:
1618 self._unpatch_dict()
1619
1620 return _inner
1621
1622
1623 def decorate_class(self, klass):
1624 for attr in dir(klass):
1625 attr_value = getattr(klass, attr)
1626 if (attr.startswith(patch.TEST_PREFIX) and
1627 hasattr(attr_value, "__call__")):
1628 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1629 decorated = decorator(attr_value)
1630 setattr(klass, attr, decorated)
1631 return klass
1632
1633
1634 def __enter__(self):
1635 """Patch the dict."""
1636 self._patch_dict()
1637
1638
1639 def _patch_dict(self):
1640 values = self.values
1641 in_dict = self.in_dict
1642 clear = self.clear
1643
1644 try:
1645 original = in_dict.copy()
1646 except AttributeError:
1647 # dict like object with no copy method
1648 # must support iteration over keys
1649 original = {}
1650 for key in in_dict:
1651 original[key] = in_dict[key]
1652 self._original = original
1653
1654 if clear:
1655 _clear_dict(in_dict)
1656
1657 try:
1658 in_dict.update(values)
1659 except AttributeError:
1660 # dict like object with no update method
1661 for key in values:
1662 in_dict[key] = values[key]
1663
1664
1665 def _unpatch_dict(self):
1666 in_dict = self.in_dict
1667 original = self._original
1668
1669 _clear_dict(in_dict)
1670
1671 try:
1672 in_dict.update(original)
1673 except AttributeError:
1674 for key in original:
1675 in_dict[key] = original[key]
1676
1677
1678 def __exit__(self, *args):
1679 """Unpatch the dict."""
1680 self._unpatch_dict()
1681 return False
1682
1683 start = __enter__
1684 stop = __exit__
1685
1686
1687def _clear_dict(in_dict):
1688 try:
1689 in_dict.clear()
1690 except AttributeError:
1691 keys = list(in_dict)
1692 for key in keys:
1693 del in_dict[key]
1694
1695
Michael Foordf7c41582012-06-10 20:36:32 +01001696def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001697 """Stop all active patches. LIFO to unroll nested patches."""
1698 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001699 patch.stop()
1700
1701
Michael Foord345266a2012-03-14 12:24:34 -07001702patch.object = _patch_object
1703patch.dict = _patch_dict
1704patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001705patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001706patch.TEST_PREFIX = 'test'
1707
1708magic_methods = (
1709 "lt le gt ge eq ne "
1710 "getitem setitem delitem "
1711 "len contains iter "
1712 "hash str sizeof "
1713 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001714 # we added divmod and rdivmod here instead of numerics
1715 # because there is no idivmod
1716 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001717 "complex int float index "
1718 "trunc floor ceil "
1719 "bool next "
1720)
1721
Michael Foordd2623d72014-04-14 11:23:48 -04001722numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001723 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001724)
Michael Foord345266a2012-03-14 12:24:34 -07001725inplace = ' '.join('i%s' % n for n in numerics.split())
1726right = ' '.join('r%s' % n for n in numerics.split())
1727
1728# not including __prepare__, __instancecheck__, __subclasscheck__
1729# (as they are metaclass methods)
1730# __del__ is not supported at all as it causes problems if it exists
1731
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001732_non_defaults = {
1733 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1734 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1735 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1736 '__repr__', '__dir__', '__subclasses__', '__format__',
Serhiy Storchaka5943ea72016-06-19 18:30:43 +03001737 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001738}
Michael Foord345266a2012-03-14 12:24:34 -07001739
1740
1741def _get_method(name, func):
1742 "Turns a callable object (like a mock) into a real function"
1743 def method(self, *args, **kw):
1744 return func(self, *args, **kw)
1745 method.__name__ = name
1746 return method
1747
1748
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001749_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001750 '__%s__' % method for method in
1751 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001752}
Michael Foord345266a2012-03-14 12:24:34 -07001753
1754_all_magics = _magics | _non_defaults
1755
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001756_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001757 '__getattr__', '__setattr__',
Miss Islington (bot)7beb8c52018-11-05 06:52:58 -08001758 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001759 '__instancecheck__', '__subclasscheck__',
1760 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001761}
Michael Foord345266a2012-03-14 12:24:34 -07001762
1763_calculate_return_value = {
1764 '__hash__': lambda self: object.__hash__(self),
1765 '__str__': lambda self: object.__str__(self),
1766 '__sizeof__': lambda self: object.__sizeof__(self),
1767}
1768
1769_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001770 '__lt__': NotImplemented,
1771 '__gt__': NotImplemented,
1772 '__le__': NotImplemented,
1773 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001774 '__int__': 1,
1775 '__contains__': False,
1776 '__len__': 0,
1777 '__exit__': False,
1778 '__complex__': 1j,
1779 '__float__': 1.0,
1780 '__bool__': True,
1781 '__index__': 1,
1782}
1783
1784
1785def _get_eq(self):
1786 def __eq__(other):
1787 ret_val = self.__eq__._mock_return_value
1788 if ret_val is not DEFAULT:
1789 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001790 if self is other:
1791 return True
1792 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001793 return __eq__
1794
1795def _get_ne(self):
1796 def __ne__(other):
1797 if self.__ne__._mock_return_value is not DEFAULT:
1798 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001799 if self is other:
1800 return False
1801 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001802 return __ne__
1803
1804def _get_iter(self):
1805 def __iter__():
1806 ret_val = self.__iter__._mock_return_value
1807 if ret_val is DEFAULT:
1808 return iter([])
1809 # if ret_val was already an iterator, then calling iter on it should
1810 # return the iterator unchanged
1811 return iter(ret_val)
1812 return __iter__
1813
1814_side_effect_methods = {
1815 '__eq__': _get_eq,
1816 '__ne__': _get_ne,
1817 '__iter__': _get_iter,
1818}
1819
1820
1821
1822def _set_return_value(mock, method, name):
1823 fixed = _return_values.get(name, DEFAULT)
1824 if fixed is not DEFAULT:
1825 method.return_value = fixed
1826 return
1827
1828 return_calulator = _calculate_return_value.get(name)
1829 if return_calulator is not None:
1830 try:
1831 return_value = return_calulator(mock)
1832 except AttributeError:
1833 # XXXX why do we return AttributeError here?
1834 # set it as a side_effect instead?
1835 return_value = AttributeError(name)
1836 method.return_value = return_value
1837 return
1838
1839 side_effector = _side_effect_methods.get(name)
1840 if side_effector is not None:
1841 method.side_effect = side_effector(mock)
1842
1843
1844
1845class MagicMixin(object):
1846 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001847 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001848 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001849 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001850
1851
1852 def _mock_set_magics(self):
1853 these_magics = _magics
1854
Łukasz Langaa468db92015-04-13 23:12:42 -07001855 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001856 these_magics = _magics.intersection(self._mock_methods)
1857
1858 remove_magics = set()
1859 remove_magics = _magics - these_magics
1860
1861 for entry in remove_magics:
1862 if entry in type(self).__dict__:
1863 # remove unneeded magic methods
1864 delattr(self, entry)
1865
1866 # don't overwrite existing attributes if called a second time
1867 these_magics = these_magics - set(type(self).__dict__)
1868
1869 _type = type(self)
1870 for entry in these_magics:
1871 setattr(_type, entry, MagicProxy(entry, self))
1872
1873
1874
1875class NonCallableMagicMock(MagicMixin, NonCallableMock):
1876 """A version of `MagicMock` that isn't callable."""
1877 def mock_add_spec(self, spec, spec_set=False):
1878 """Add a spec to a mock. `spec` can either be an object or a
1879 list of strings. Only attributes on the `spec` can be fetched as
1880 attributes from the mock.
1881
1882 If `spec_set` is True then only attributes on the spec can be set."""
1883 self._mock_add_spec(spec, spec_set)
1884 self._mock_set_magics()
1885
1886
1887
1888class MagicMock(MagicMixin, Mock):
1889 """
1890 MagicMock is a subclass of Mock with default implementations
1891 of most of the magic methods. You can use MagicMock without having to
1892 configure the magic methods yourself.
1893
1894 If you use the `spec` or `spec_set` arguments then *only* magic
1895 methods that exist in the spec will be created.
1896
1897 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1898 """
1899 def mock_add_spec(self, spec, spec_set=False):
1900 """Add a spec to a mock. `spec` can either be an object or a
1901 list of strings. Only attributes on the `spec` can be fetched as
1902 attributes from the mock.
1903
1904 If `spec_set` is True then only attributes on the spec can be set."""
1905 self._mock_add_spec(spec, spec_set)
1906 self._mock_set_magics()
1907
1908
1909
1910class MagicProxy(object):
1911 def __init__(self, name, parent):
1912 self.name = name
1913 self.parent = parent
1914
1915 def __call__(self, *args, **kwargs):
1916 m = self.create_mock()
1917 return m(*args, **kwargs)
1918
1919 def create_mock(self):
1920 entry = self.name
1921 parent = self.parent
1922 m = parent._get_child_mock(name=entry, _new_name=entry,
1923 _new_parent=parent)
1924 setattr(parent, entry, m)
1925 _set_return_value(parent, m, entry)
1926 return m
1927
1928 def __get__(self, obj, _type=None):
1929 return self.create_mock()
1930
1931
1932
1933class _ANY(object):
1934 "A helper object that compares equal to everything."
1935
1936 def __eq__(self, other):
1937 return True
1938
1939 def __ne__(self, other):
1940 return False
1941
1942 def __repr__(self):
1943 return '<ANY>'
1944
1945ANY = _ANY()
1946
1947
1948
1949def _format_call_signature(name, args, kwargs):
1950 message = '%s(%%s)' % name
1951 formatted_args = ''
1952 args_string = ', '.join([repr(arg) for arg in args])
1953 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05301954 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07001955 ])
1956 if args_string:
1957 formatted_args = args_string
1958 if kwargs_string:
1959 if formatted_args:
1960 formatted_args += ', '
1961 formatted_args += kwargs_string
1962
1963 return message % formatted_args
1964
1965
1966
1967class _Call(tuple):
1968 """
1969 A tuple for holding the results of a call to a mock, either in the form
1970 `(args, kwargs)` or `(name, args, kwargs)`.
1971
1972 If args or kwargs are empty then a call tuple will compare equal to
1973 a tuple without those values. This makes comparisons less verbose::
1974
1975 _Call(('name', (), {})) == ('name',)
1976 _Call(('name', (1,), {})) == ('name', (1,))
1977 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1978
1979 The `_Call` object provides a useful shortcut for comparing with call::
1980
1981 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1982 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1983
1984 If the _Call has no name then it will match any name.
1985 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01001986 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07001987 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07001988 args = ()
1989 kwargs = {}
1990 _len = len(value)
1991 if _len == 3:
1992 name, args, kwargs = value
1993 elif _len == 2:
1994 first, second = value
1995 if isinstance(first, str):
1996 name = first
1997 if isinstance(second, tuple):
1998 args = second
1999 else:
2000 kwargs = second
2001 else:
2002 args, kwargs = first, second
2003 elif _len == 1:
2004 value, = value
2005 if isinstance(value, str):
2006 name = value
2007 elif isinstance(value, tuple):
2008 args = value
2009 else:
2010 kwargs = value
2011
2012 if two:
2013 return tuple.__new__(cls, (args, kwargs))
2014
2015 return tuple.__new__(cls, (name, args, kwargs))
2016
2017
2018 def __init__(self, value=(), name=None, parent=None, two=False,
2019 from_kall=True):
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002020 self._mock_name = name
2021 self._mock_parent = parent
2022 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002023
2024
2025 def __eq__(self, other):
2026 if other is ANY:
2027 return True
2028 try:
2029 len_other = len(other)
2030 except TypeError:
2031 return False
2032
2033 self_name = ''
2034 if len(self) == 2:
2035 self_args, self_kwargs = self
2036 else:
2037 self_name, self_args, self_kwargs = self
2038
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002039 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2040 and self._mock_parent != other._mock_parent):
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -08002041 return False
2042
Michael Foord345266a2012-03-14 12:24:34 -07002043 other_name = ''
2044 if len_other == 0:
2045 other_args, other_kwargs = (), {}
2046 elif len_other == 3:
2047 other_name, other_args, other_kwargs = other
2048 elif len_other == 1:
2049 value, = other
2050 if isinstance(value, tuple):
2051 other_args = value
2052 other_kwargs = {}
2053 elif isinstance(value, str):
2054 other_name = value
2055 other_args, other_kwargs = (), {}
2056 else:
2057 other_args = ()
2058 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002059 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002060 # could be (name, args) or (name, kwargs) or (args, kwargs)
2061 first, second = other
2062 if isinstance(first, str):
2063 other_name = first
2064 if isinstance(second, tuple):
2065 other_args, other_kwargs = second, {}
2066 else:
2067 other_args, other_kwargs = (), second
2068 else:
2069 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002070 else:
2071 return False
Michael Foord345266a2012-03-14 12:24:34 -07002072
2073 if self_name and other_name != self_name:
2074 return False
2075
2076 # this order is important for ANY to work!
2077 return (other_args, other_kwargs) == (self_args, self_kwargs)
2078
2079
Berker Peksagce913872016-03-28 00:30:02 +03002080 __ne__ = object.__ne__
2081
2082
Michael Foord345266a2012-03-14 12:24:34 -07002083 def __call__(self, *args, **kwargs):
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002084 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002085 return _Call(('', args, kwargs), name='()')
2086
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002087 name = self._mock_name + '()'
2088 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002089
2090
2091 def __getattr__(self, attr):
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002092 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002093 return _Call(name=attr, from_kall=False)
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002094 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002095 return _Call(name=name, parent=self, from_kall=False)
2096
2097
Kushal Dasa37b9582014-09-16 18:33:37 +05302098 def count(self, *args, **kwargs):
2099 return self.__getattr__('count')(*args, **kwargs)
2100
2101 def index(self, *args, **kwargs):
2102 return self.__getattr__('index')(*args, **kwargs)
2103
Michael Foord345266a2012-03-14 12:24:34 -07002104 def __repr__(self):
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002105 if not self._mock_from_kall:
2106 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002107 if name.startswith('()'):
2108 name = 'call%s' % name
2109 return name
2110
2111 if len(self) == 2:
2112 name = 'call'
2113 args, kwargs = self
2114 else:
2115 name, args, kwargs = self
2116 if not name:
2117 name = 'call'
2118 elif not name.startswith('()'):
2119 name = 'call.%s' % name
2120 else:
2121 name = 'call%s' % name
2122 return _format_call_signature(name, args, kwargs)
2123
2124
2125 def call_list(self):
2126 """For a call object that represents multiple calls, `call_list`
2127 returns a list of all the intermediate calls as well as the
2128 final call."""
2129 vals = []
2130 thing = self
2131 while thing is not None:
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002132 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002133 vals.append(thing)
Miss Islington (bot)12735c12018-12-04 01:34:34 -08002134 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002135 return _CallList(reversed(vals))
2136
2137
2138call = _Call(from_kall=False)
2139
2140
2141
2142def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2143 _name=None, **kwargs):
2144 """Create a mock object using another object as a spec. Attributes on the
2145 mock will use the corresponding attribute on the `spec` object as their
2146 spec.
2147
2148 Functions or methods being mocked will have their arguments checked
2149 to check that they are called with the correct signature.
2150
2151 If `spec_set` is True then attempting to set attributes that don't exist
2152 on the spec object will raise an `AttributeError`.
2153
2154 If a class is used as a spec then the return value of the mock (the
2155 instance of the class) will have the same spec. You can use a class as the
2156 spec for an instance object by passing `instance=True`. The returned mock
2157 will only be callable if instances of the mock are callable.
2158
2159 `create_autospec` also takes arbitrary keyword arguments that are passed to
2160 the constructor of the created mock."""
2161 if _is_list(spec):
2162 # can't pass a list instance to the mock constructor as it will be
2163 # interpreted as a list of strings
2164 spec = type(spec)
2165
2166 is_type = isinstance(spec, type)
2167
2168 _kwargs = {'spec': spec}
2169 if spec_set:
2170 _kwargs = {'spec_set': spec}
2171 elif spec is None:
2172 # None we mock with a normal mock without a spec
2173 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002174 if _kwargs and instance:
2175 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002176
2177 _kwargs.update(kwargs)
2178
2179 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002180 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002181 # descriptors don't have a spec
2182 # because we don't know what type they return
2183 _kwargs = {}
2184 elif not _callable(spec):
2185 Klass = NonCallableMagicMock
2186 elif is_type and instance and not _instance_callable(spec):
2187 Klass = NonCallableMagicMock
2188
Kushal Das484f8a82014-04-16 01:05:50 +05302189 _name = _kwargs.pop('name', _name)
2190
Michael Foord345266a2012-03-14 12:24:34 -07002191 _new_name = _name
2192 if _parent is None:
2193 # for a top level object no _new_name should be set
2194 _new_name = ''
2195
2196 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2197 name=_name, **_kwargs)
2198
2199 if isinstance(spec, FunctionTypes):
2200 # should only happen at the top level because we don't
2201 # recurse for functions
2202 mock = _set_signature(mock, spec)
2203 else:
2204 _check_signature(spec, mock, is_type, instance)
2205
2206 if _parent is not None and not instance:
2207 _parent._mock_children[_name] = mock
2208
2209 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002210 mock.return_value = create_autospec(spec, spec_set, instance=True,
2211 _name='()', _parent=mock)
2212
2213 for entry in dir(spec):
2214 if _is_magic(entry):
2215 # MagicMock already does the useful magic methods for us
2216 continue
2217
Michael Foord345266a2012-03-14 12:24:34 -07002218 # XXXX do we need a better way of getting attributes without
2219 # triggering code execution (?) Probably not - we need the actual
2220 # object to mock it so we would rather trigger a property than mock
2221 # the property descriptor. Likewise we want to mock out dynamically
2222 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002223 # XXXX what about attributes that raise exceptions other than
2224 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002225 # we could be resilient against it, or catch and propagate the
2226 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002227 try:
2228 original = getattr(spec, entry)
2229 except AttributeError:
2230 continue
Michael Foord345266a2012-03-14 12:24:34 -07002231
2232 kwargs = {'spec': original}
2233 if spec_set:
2234 kwargs = {'spec_set': original}
2235
2236 if not isinstance(original, FunctionTypes):
2237 new = _SpecState(original, spec_set, mock, entry, instance)
2238 mock._mock_children[entry] = new
2239 else:
2240 parent = mock
2241 if isinstance(spec, FunctionTypes):
2242 parent = mock.mock
2243
Michael Foord345266a2012-03-14 12:24:34 -07002244 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002245 kwargs['_eat_self'] = skipfirst
2246 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2247 _new_parent=parent,
2248 **kwargs)
2249 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002250 _check_signature(original, new, skipfirst=skipfirst)
2251
2252 # so functions created with _set_signature become instance attributes,
2253 # *plus* their underlying mock exists in _mock_children of the parent
2254 # mock. Adding to _mock_children may be unnecessary where we are also
2255 # setting as an instance attribute?
2256 if isinstance(new, FunctionTypes):
2257 setattr(mock, entry, new)
2258
2259 return mock
2260
2261
2262def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002263 """
2264 Return whether we should skip the first argument on spec's `entry`
2265 attribute.
2266 """
Michael Foord345266a2012-03-14 12:24:34 -07002267 if not isinstance(spec, type):
2268 if entry in getattr(spec, '__dict__', {}):
2269 # instance attribute - shouldn't skip
2270 return False
Michael Foord345266a2012-03-14 12:24:34 -07002271 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002272
2273 for klass in spec.__mro__:
2274 result = klass.__dict__.get(entry, DEFAULT)
2275 if result is DEFAULT:
2276 continue
2277 if isinstance(result, (staticmethod, classmethod)):
2278 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002279 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2280 # Normal method => skip if looked up on type
2281 # (if looked up on instance, self is already skipped)
2282 return is_type
2283 else:
2284 return False
Michael Foord345266a2012-03-14 12:24:34 -07002285
2286 # shouldn't get here unless function is a dynamically provided attribute
2287 # XXXX untested behaviour
2288 return is_type
2289
2290
2291def _get_class(obj):
2292 try:
2293 return obj.__class__
2294 except AttributeError:
Michael Foord50a8c0e2012-03-25 18:57:58 +01002295 # it is possible for objects to have no __class__
Michael Foord345266a2012-03-14 12:24:34 -07002296 return type(obj)
2297
2298
2299class _SpecState(object):
2300
2301 def __init__(self, spec, spec_set=False, parent=None,
2302 name=None, ids=None, instance=False):
2303 self.spec = spec
2304 self.ids = ids
2305 self.spec_set = spec_set
2306 self.parent = parent
2307 self.instance = instance
2308 self.name = name
2309
2310
2311FunctionTypes = (
2312 # python function
2313 type(create_autospec),
2314 # instance method
2315 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002316)
2317
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002318MethodWrapperTypes = (
2319 type(ANY.__eq__.__get__),
2320)
2321
Michael Foord345266a2012-03-14 12:24:34 -07002322
Michael Foorda74561a2012-03-25 19:03:13 +01002323file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002324
Michael Foord04cbe0c2013-03-19 17:22:51 -07002325def _iterate_read_data(read_data):
2326 # Helper for mock_open:
2327 # Retrieve lines from read_data via a generator so that separate calls to
2328 # readline, read, and readlines are properly interleaved
Berker Peksag86b34da2015-08-06 13:15:51 +03002329 sep = b'\n' if isinstance(read_data, bytes) else '\n'
2330 data_as_list = [l + sep for l in read_data.split(sep)]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002331
Berker Peksag86b34da2015-08-06 13:15:51 +03002332 if data_as_list[-1] == sep:
Michael Foord04cbe0c2013-03-19 17:22:51 -07002333 # If the last line ended in a newline, the list comprehension will have an
2334 # extra entry that's just a newline. Remove this.
2335 data_as_list = data_as_list[:-1]
2336 else:
2337 # If there wasn't an extra newline by itself, then the file being
2338 # emulated doesn't have a newline to end the last line remove the
2339 # newline that our naive format() added
2340 data_as_list[-1] = data_as_list[-1][:-1]
2341
2342 for line in data_as_list:
2343 yield line
Michael Foord0dccf652012-03-25 19:11:50 +01002344
Robert Collins5329aaa2015-07-17 20:08:45 +12002345
Michael Foord0dccf652012-03-25 19:11:50 +01002346def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002347 """
2348 A helper function to create a mock to replace the use of `open`. It works
2349 for `open` called directly or used as a context manager.
2350
2351 The `mock` argument is the mock object to configure. If `None` (the
2352 default) then a `MagicMock` will be created for you, with the API limited
2353 to methods or attributes available on standard file handles.
2354
Michael Foord04cbe0c2013-03-19 17:22:51 -07002355 `read_data` is a string for the `read` methoddline`, and `readlines` of the
2356 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002357 """
Robert Collinsca647ef2015-07-24 03:48:20 +12002358 def _readlines_side_effect(*args, **kwargs):
2359 if handle.readlines.return_value is not None:
2360 return handle.readlines.return_value
2361 return list(_state[0])
2362
2363 def _read_side_effect(*args, **kwargs):
2364 if handle.read.return_value is not None:
2365 return handle.read.return_value
Berker Peksag86b34da2015-08-06 13:15:51 +03002366 return type(read_data)().join(_state[0])
Robert Collinsca647ef2015-07-24 03:48:20 +12002367
2368 def _readline_side_effect():
Miss Islington (bot)c83c3752018-09-14 14:30:04 -07002369 yield from _iter_side_effect()
2370 while True:
2371 yield type(read_data)()
2372
2373 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002374 if handle.readline.return_value is not None:
2375 while True:
2376 yield handle.readline.return_value
2377 for line in _state[0]:
2378 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002379
Michael Foorda74561a2012-03-25 19:03:13 +01002380 global file_spec
2381 if file_spec is None:
2382 import _io
2383 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2384
Michael Foord345266a2012-03-14 12:24:34 -07002385 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002386 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002387
Robert Collinsca647ef2015-07-24 03:48:20 +12002388 handle = MagicMock(spec=file_spec)
2389 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002390
Robert Collinsca647ef2015-07-24 03:48:20 +12002391 _state = [_iterate_read_data(read_data), None]
Michael Foord04cbe0c2013-03-19 17:22:51 -07002392
Robert Collinsca647ef2015-07-24 03:48:20 +12002393 handle.write.return_value = None
2394 handle.read.return_value = None
2395 handle.readline.return_value = None
2396 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002397
Robert Collinsca647ef2015-07-24 03:48:20 +12002398 handle.read.side_effect = _read_side_effect
2399 _state[1] = _readline_side_effect()
2400 handle.readline.side_effect = _state[1]
2401 handle.readlines.side_effect = _readlines_side_effect
Miss Islington (bot)c83c3752018-09-14 14:30:04 -07002402 handle.__iter__.side_effect = _iter_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002403
Robert Collinsca647ef2015-07-24 03:48:20 +12002404 def reset_data(*args, **kwargs):
2405 _state[0] = _iterate_read_data(read_data)
2406 if handle.readline.side_effect == _state[1]:
2407 # Only reset the side effect if the user hasn't overridden it.
2408 _state[1] = _readline_side_effect()
2409 handle.readline.side_effect = _state[1]
2410 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002411
Robert Collinsca647ef2015-07-24 03:48:20 +12002412 mock.side_effect = reset_data
2413 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002414 return mock
2415
2416
2417class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002418 """
2419 A mock intended to be used as a property, or other descriptor, on a class.
2420 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2421 a return value when it is fetched.
2422
2423 Fetching a `PropertyMock` instance from an object calls the mock, with
2424 no args. Setting it calls the mock with the value being set.
2425 """
Michael Foordc2870622012-04-13 16:57:22 +01002426 def _get_child_mock(self, **kwargs):
2427 return MagicMock(**kwargs)
2428
Michael Foord345266a2012-03-14 12:24:34 -07002429 def __get__(self, obj, obj_type):
2430 return self()
2431 def __set__(self, obj, val):
2432 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002433
2434
2435def seal(mock):
Miss Islington (bot)984a8002018-10-19 15:17:31 -07002436 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002437
2438 Given an input Mock, seals it to ensure no further mocks will be generated
2439 when accessing an attribute that was not already defined.
2440
Miss Islington (bot)984a8002018-10-19 15:17:31 -07002441 The operation recursively seals the mock passed in, meaning that
2442 the mock itself, any mocks generated by accessing one of its attributes,
2443 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002444 """
2445 mock._mock_sealed = True
2446 for attr in dir(mock):
2447 try:
2448 m = getattr(mock, attr)
2449 except AttributeError:
2450 continue
2451 if not isinstance(m, NonCallableMock):
2452 continue
2453 if m._mock_new_parent is mock:
2454 seal(m)