ยปCore Development>Code coverage>Lib/unittest/mock.py

Python code coverage for Lib/unittest/mock.py

#countcontent
1n/a# mock.py
2n/a# Test tools for mocking and patching.
3n/a# Maintained by Michael Foord
4n/a# Backport for other versions of Python available from
5n/a# http://pypi.python.org/pypi/mock
6n/a
7n/a__all__ = (
8n/a 'Mock',
9n/a 'MagicMock',
10n/a 'patch',
11n/a 'sentinel',
12n/a 'DEFAULT',
13n/a 'ANY',
14n/a 'call',
15n/a 'create_autospec',
16n/a 'FILTER_DIR',
17n/a 'NonCallableMock',
18n/a 'NonCallableMagicMock',
19n/a 'mock_open',
20n/a 'PropertyMock',
21n/a)
22n/a
23n/a
24n/a__version__ = '1.0'
25n/a
26n/a
27n/aimport inspect
28n/aimport pprint
29n/aimport sys
30n/aimport builtins
31n/afrom types import ModuleType
32n/afrom functools import wraps, partial
33n/a
34n/a
35n/a_builtins = {name for name in dir(builtins) if not name.startswith('_')}
36n/a
37n/aBaseExceptions = (BaseException,)
38n/aif 'java' in sys.platform:
39n/a # jython
40n/a import java
41n/a BaseExceptions = (BaseException, java.lang.Throwable)
42n/a
43n/a
44n/aFILTER_DIR = True
45n/a
46n/a# Workaround for issue #12370
47n/a# Without this, the __class__ properties wouldn't be set correctly
48n/a_safe_super = super
49n/a
50n/adef _is_instance_mock(obj):
51n/a # can't use isinstance on Mock objects because they override __class__
52n/a # The base class for all mocks is NonCallableMock
53n/a return issubclass(type(obj), NonCallableMock)
54n/a
55n/a
56n/adef _is_exception(obj):
57n/a return (
58n/a isinstance(obj, BaseExceptions) or
59n/a isinstance(obj, type) and issubclass(obj, BaseExceptions)
60n/a )
61n/a
62n/a
63n/adef _get_signature_object(func, as_instance, eat_self):
64n/a """
65n/a Given an arbitrary, possibly callable object, try to create a suitable
66n/a signature object.
67n/a Return a (reduced func, signature) tuple, or None.
68n/a """
69n/a if isinstance(func, type) and not as_instance:
70n/a # If it's a type and should be modelled as a type, use __init__.
71n/a try:
72n/a func = func.__init__
73n/a except AttributeError:
74n/a return None
75n/a # Skip the `self` argument in __init__
76n/a eat_self = True
77n/a elif not isinstance(func, FunctionTypes):
78n/a # If we really want to model an instance of the passed type,
79n/a # __call__ should be looked up, not __init__.
80n/a try:
81n/a func = func.__call__
82n/a except AttributeError:
83n/a return None
84n/a if eat_self:
85n/a sig_func = partial(func, None)
86n/a else:
87n/a sig_func = func
88n/a try:
89n/a return func, inspect.signature(sig_func)
90n/a except ValueError:
91n/a # Certain callable types are not supported by inspect.signature()
92n/a return None
93n/a
94n/a
95n/adef _check_signature(func, mock, skipfirst, instance=False):
96n/a sig = _get_signature_object(func, instance, skipfirst)
97n/a if sig is None:
98n/a return
99n/a func, sig = sig
100n/a def checksig(_mock_self, *args, **kwargs):
101n/a sig.bind(*args, **kwargs)
102n/a _copy_func_details(func, checksig)
103n/a type(mock)._mock_check_sig = checksig
104n/a
105n/a
106n/adef _copy_func_details(func, funcopy):
107n/a # we explicitly don't copy func.__dict__ into this copy as it would
108n/a # expose original attributes that should be mocked
109n/a for attribute in (
110n/a '__name__', '__doc__', '__text_signature__',
111n/a '__module__', '__defaults__', '__kwdefaults__',
112n/a ):
113n/a try:
114n/a setattr(funcopy, attribute, getattr(func, attribute))
115n/a except AttributeError:
116n/a pass
117n/a
118n/a
119n/adef _callable(obj):
120n/a if isinstance(obj, type):
121n/a return True
122n/a if getattr(obj, '__call__', None) is not None:
123n/a return True
124n/a return False
125n/a
126n/a
127n/adef _is_list(obj):
128n/a # checks for list or tuples
129n/a # XXXX badly named!
130n/a return type(obj) in (list, tuple)
131n/a
132n/a
133n/adef _instance_callable(obj):
134n/a """Given an object, return True if the object is callable.
135n/a For classes, return True if instances would be callable."""
136n/a if not isinstance(obj, type):
137n/a # already an instance
138n/a return getattr(obj, '__call__', None) is not None
139n/a
140n/a # *could* be broken by a class overriding __mro__ or __dict__ via
141n/a # a metaclass
142n/a for base in (obj,) + obj.__mro__:
143n/a if base.__dict__.get('__call__') is not None:
144n/a return True
145n/a return False
146n/a
147n/a
148n/adef _set_signature(mock, original, instance=False):
149n/a # creates a function with signature (*args, **kwargs) that delegates to a
150n/a # mock. It still does signature checking by calling a lambda with the same
151n/a # signature as the original.
152n/a if not _callable(original):
153n/a return
154n/a
155n/a skipfirst = isinstance(original, type)
156n/a result = _get_signature_object(original, instance, skipfirst)
157n/a if result is None:
158n/a return
159n/a func, sig = result
160n/a def checksig(*args, **kwargs):
161n/a sig.bind(*args, **kwargs)
162n/a _copy_func_details(func, checksig)
163n/a
164n/a name = original.__name__
165n/a if not name.isidentifier():
166n/a name = 'funcopy'
167n/a context = {'_checksig_': checksig, 'mock': mock}
168n/a src = """def %s(*args, **kwargs):
169n/a _checksig_(*args, **kwargs)
170n/a return mock(*args, **kwargs)""" % name
171n/a exec (src, context)
172n/a funcopy = context[name]
173n/a _setup_func(funcopy, mock)
174n/a return funcopy
175n/a
176n/a
177n/adef _setup_func(funcopy, mock):
178n/a funcopy.mock = mock
179n/a
180n/a # can't use isinstance with mocks
181n/a if not _is_instance_mock(mock):
182n/a return
183n/a
184n/a def assert_called_with(*args, **kwargs):
185n/a return mock.assert_called_with(*args, **kwargs)
186n/a def assert_called(*args, **kwargs):
187n/a return mock.assert_called(*args, **kwargs)
188n/a def assert_not_called(*args, **kwargs):
189n/a return mock.assert_not_called(*args, **kwargs)
190n/a def assert_called_once(*args, **kwargs):
191n/a return mock.assert_called_once(*args, **kwargs)
192n/a def assert_called_once_with(*args, **kwargs):
193n/a return mock.assert_called_once_with(*args, **kwargs)
194n/a def assert_has_calls(*args, **kwargs):
195n/a return mock.assert_has_calls(*args, **kwargs)
196n/a def assert_any_call(*args, **kwargs):
197n/a return mock.assert_any_call(*args, **kwargs)
198n/a def reset_mock():
199n/a funcopy.method_calls = _CallList()
200n/a funcopy.mock_calls = _CallList()
201n/a mock.reset_mock()
202n/a ret = funcopy.return_value
203n/a if _is_instance_mock(ret) and not ret is mock:
204n/a ret.reset_mock()
205n/a
206n/a funcopy.called = False
207n/a funcopy.call_count = 0
208n/a funcopy.call_args = None
209n/a funcopy.call_args_list = _CallList()
210n/a funcopy.method_calls = _CallList()
211n/a funcopy.mock_calls = _CallList()
212n/a
213n/a funcopy.return_value = mock.return_value
214n/a funcopy.side_effect = mock.side_effect
215n/a funcopy._mock_children = mock._mock_children
216n/a
217n/a funcopy.assert_called_with = assert_called_with
218n/a funcopy.assert_called_once_with = assert_called_once_with
219n/a funcopy.assert_has_calls = assert_has_calls
220n/a funcopy.assert_any_call = assert_any_call
221n/a funcopy.reset_mock = reset_mock
222n/a funcopy.assert_called = assert_called
223n/a funcopy.assert_not_called = assert_not_called
224n/a funcopy.assert_called_once = assert_called_once
225n/a
226n/a mock._mock_delegate = funcopy
227n/a
228n/a
229n/adef _is_magic(name):
230n/a return '__%s__' % name[2:-2] == name
231n/a
232n/a
233n/aclass _SentinelObject(object):
234n/a "A unique, named, sentinel object."
235n/a def __init__(self, name):
236n/a self.name = name
237n/a
238n/a def __repr__(self):
239n/a return 'sentinel.%s' % self.name
240n/a
241n/a def __reduce__(self):
242n/a return 'sentinel.%s' % self.name
243n/a
244n/a
245n/aclass _Sentinel(object):
246n/a """Access attributes to return a named object, usable as a sentinel."""
247n/a def __init__(self):
248n/a self._sentinels = {}
249n/a
250n/a def __getattr__(self, name):
251n/a if name == '__bases__':
252n/a # Without this help(unittest.mock) raises an exception
253n/a raise AttributeError
254n/a return self._sentinels.setdefault(name, _SentinelObject(name))
255n/a
256n/a def __reduce__(self):
257n/a return 'sentinel'
258n/a
259n/a
260n/asentinel = _Sentinel()
261n/a
262n/aDEFAULT = sentinel.DEFAULT
263n/a_missing = sentinel.MISSING
264n/a_deleted = sentinel.DELETED
265n/a
266n/a
267n/adef _copy(value):
268n/a if type(value) in (dict, list, tuple, set):
269n/a return type(value)(value)
270n/a return value
271n/a
272n/a
273n/a_allowed_names = {
274n/a 'return_value', '_mock_return_value', 'side_effect',
275n/a '_mock_side_effect', '_mock_parent', '_mock_new_parent',
276n/a '_mock_name', '_mock_new_name'
277n/a}
278n/a
279n/a
280n/adef _delegating_property(name):
281n/a _allowed_names.add(name)
282n/a _the_name = '_mock_' + name
283n/a def _get(self, name=name, _the_name=_the_name):
284n/a sig = self._mock_delegate
285n/a if sig is None:
286n/a return getattr(self, _the_name)
287n/a return getattr(sig, name)
288n/a def _set(self, value, name=name, _the_name=_the_name):
289n/a sig = self._mock_delegate
290n/a if sig is None:
291n/a self.__dict__[_the_name] = value
292n/a else:
293n/a setattr(sig, name, value)
294n/a
295n/a return property(_get, _set)
296n/a
297n/a
298n/a
299n/aclass _CallList(list):
300n/a
301n/a def __contains__(self, value):
302n/a if not isinstance(value, list):
303n/a return list.__contains__(self, value)
304n/a len_value = len(value)
305n/a len_self = len(self)
306n/a if len_value > len_self:
307n/a return False
308n/a
309n/a for i in range(0, len_self - len_value + 1):
310n/a sub_list = self[i:i+len_value]
311n/a if sub_list == value:
312n/a return True
313n/a return False
314n/a
315n/a def __repr__(self):
316n/a return pprint.pformat(list(self))
317n/a
318n/a
319n/adef _check_and_set_parent(parent, value, name, new_name):
320n/a if not _is_instance_mock(value):
321n/a return False
322n/a if ((value._mock_name or value._mock_new_name) or
323n/a (value._mock_parent is not None) or
324n/a (value._mock_new_parent is not None)):
325n/a return False
326n/a
327n/a _parent = parent
328n/a while _parent is not None:
329n/a # setting a mock (value) as a child or return value of itself
330n/a # should not modify the mock
331n/a if _parent is value:
332n/a return False
333n/a _parent = _parent._mock_new_parent
334n/a
335n/a if new_name:
336n/a value._mock_new_parent = parent
337n/a value._mock_new_name = new_name
338n/a if name:
339n/a value._mock_parent = parent
340n/a value._mock_name = name
341n/a return True
342n/a
343n/a# Internal class to identify if we wrapped an iterator object or not.
344n/aclass _MockIter(object):
345n/a def __init__(self, obj):
346n/a self.obj = iter(obj)
347n/a def __iter__(self):
348n/a return self
349n/a def __next__(self):
350n/a return next(self.obj)
351n/a
352n/aclass Base(object):
353n/a _mock_return_value = DEFAULT
354n/a _mock_side_effect = None
355n/a def __init__(self, *args, **kwargs):
356n/a pass
357n/a
358n/a
359n/a
360n/aclass NonCallableMock(Base):
361n/a """A non-callable version of `Mock`"""
362n/a
363n/a def __new__(cls, *args, **kw):
364n/a # every instance has its own class
365n/a # so we can create magic methods on the
366n/a # class without stomping on other mocks
367n/a new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
368n/a instance = object.__new__(new)
369n/a return instance
370n/a
371n/a
372n/a def __init__(
373n/a self, spec=None, wraps=None, name=None, spec_set=None,
374n/a parent=None, _spec_state=None, _new_name='', _new_parent=None,
375n/a _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
376n/a ):
377n/a if _new_parent is None:
378n/a _new_parent = parent
379n/a
380n/a __dict__ = self.__dict__
381n/a __dict__['_mock_parent'] = parent
382n/a __dict__['_mock_name'] = name
383n/a __dict__['_mock_new_name'] = _new_name
384n/a __dict__['_mock_new_parent'] = _new_parent
385n/a
386n/a if spec_set is not None:
387n/a spec = spec_set
388n/a spec_set = True
389n/a if _eat_self is None:
390n/a _eat_self = parent is not None
391n/a
392n/a self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
393n/a
394n/a __dict__['_mock_children'] = {}
395n/a __dict__['_mock_wraps'] = wraps
396n/a __dict__['_mock_delegate'] = None
397n/a
398n/a __dict__['_mock_called'] = False
399n/a __dict__['_mock_call_args'] = None
400n/a __dict__['_mock_call_count'] = 0
401n/a __dict__['_mock_call_args_list'] = _CallList()
402n/a __dict__['_mock_mock_calls'] = _CallList()
403n/a
404n/a __dict__['method_calls'] = _CallList()
405n/a __dict__['_mock_unsafe'] = unsafe
406n/a
407n/a if kwargs:
408n/a self.configure_mock(**kwargs)
409n/a
410n/a _safe_super(NonCallableMock, self).__init__(
411n/a spec, wraps, name, spec_set, parent,
412n/a _spec_state
413n/a )
414n/a
415n/a
416n/a def attach_mock(self, mock, attribute):
417n/a """
418n/a Attach a mock as an attribute of this one, replacing its name and
419n/a parent. Calls to the attached mock will be recorded in the
420n/a `method_calls` and `mock_calls` attributes of this one."""
421n/a mock._mock_parent = None
422n/a mock._mock_new_parent = None
423n/a mock._mock_name = ''
424n/a mock._mock_new_name = None
425n/a
426n/a setattr(self, attribute, mock)
427n/a
428n/a
429n/a def mock_add_spec(self, spec, spec_set=False):
430n/a """Add a spec to a mock. `spec` can either be an object or a
431n/a list of strings. Only attributes on the `spec` can be fetched as
432n/a attributes from the mock.
433n/a
434n/a If `spec_set` is True then only attributes on the spec can be set."""
435n/a self._mock_add_spec(spec, spec_set)
436n/a
437n/a
438n/a def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
439n/a _eat_self=False):
440n/a _spec_class = None
441n/a _spec_signature = None
442n/a
443n/a if spec is not None and not _is_list(spec):
444n/a if isinstance(spec, type):
445n/a _spec_class = spec
446n/a else:
447n/a _spec_class = _get_class(spec)
448n/a res = _get_signature_object(spec,
449n/a _spec_as_instance, _eat_self)
450n/a _spec_signature = res and res[1]
451n/a
452n/a spec = dir(spec)
453n/a
454n/a __dict__ = self.__dict__
455n/a __dict__['_spec_class'] = _spec_class
456n/a __dict__['_spec_set'] = spec_set
457n/a __dict__['_spec_signature'] = _spec_signature
458n/a __dict__['_mock_methods'] = spec
459n/a
460n/a
461n/a def __get_return_value(self):
462n/a ret = self._mock_return_value
463n/a if self._mock_delegate is not None:
464n/a ret = self._mock_delegate.return_value
465n/a
466n/a if ret is DEFAULT:
467n/a ret = self._get_child_mock(
468n/a _new_parent=self, _new_name='()'
469n/a )
470n/a self.return_value = ret
471n/a return ret
472n/a
473n/a
474n/a def __set_return_value(self, value):
475n/a if self._mock_delegate is not None:
476n/a self._mock_delegate.return_value = value
477n/a else:
478n/a self._mock_return_value = value
479n/a _check_and_set_parent(self, value, None, '()')
480n/a
481n/a __return_value_doc = "The value to be returned when the mock is called."
482n/a return_value = property(__get_return_value, __set_return_value,
483n/a __return_value_doc)
484n/a
485n/a
486n/a @property
487n/a def __class__(self):
488n/a if self._spec_class is None:
489n/a return type(self)
490n/a return self._spec_class
491n/a
492n/a called = _delegating_property('called')
493n/a call_count = _delegating_property('call_count')
494n/a call_args = _delegating_property('call_args')
495n/a call_args_list = _delegating_property('call_args_list')
496n/a mock_calls = _delegating_property('mock_calls')
497n/a
498n/a
499n/a def __get_side_effect(self):
500n/a delegated = self._mock_delegate
501n/a if delegated is None:
502n/a return self._mock_side_effect
503n/a sf = delegated.side_effect
504n/a if (sf is not None and not callable(sf)
505n/a and not isinstance(sf, _MockIter) and not _is_exception(sf)):
506n/a sf = _MockIter(sf)
507n/a delegated.side_effect = sf
508n/a return sf
509n/a
510n/a def __set_side_effect(self, value):
511n/a value = _try_iter(value)
512n/a delegated = self._mock_delegate
513n/a if delegated is None:
514n/a self._mock_side_effect = value
515n/a else:
516n/a delegated.side_effect = value
517n/a
518n/a side_effect = property(__get_side_effect, __set_side_effect)
519n/a
520n/a
521n/a def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
522n/a "Restore the mock object to its initial state."
523n/a if visited is None:
524n/a visited = []
525n/a if id(self) in visited:
526n/a return
527n/a visited.append(id(self))
528n/a
529n/a self.called = False
530n/a self.call_args = None
531n/a self.call_count = 0
532n/a self.mock_calls = _CallList()
533n/a self.call_args_list = _CallList()
534n/a self.method_calls = _CallList()
535n/a
536n/a if return_value:
537n/a self._mock_return_value = DEFAULT
538n/a if side_effect:
539n/a self._mock_side_effect = None
540n/a
541n/a for child in self._mock_children.values():
542n/a if isinstance(child, _SpecState):
543n/a continue
544n/a child.reset_mock(visited)
545n/a
546n/a ret = self._mock_return_value
547n/a if _is_instance_mock(ret) and ret is not self:
548n/a ret.reset_mock(visited)
549n/a
550n/a
551n/a def configure_mock(self, **kwargs):
552n/a """Set attributes on the mock through keyword arguments.
553n/a
554n/a Attributes plus return values and side effects can be set on child
555n/a mocks using standard dot notation and unpacking a dictionary in the
556n/a method call:
557n/a
558n/a >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
559n/a >>> mock.configure_mock(**attrs)"""
560n/a for arg, val in sorted(kwargs.items(),
561n/a # we sort on the number of dots so that
562n/a # attributes are set before we set attributes on
563n/a # attributes
564n/a key=lambda entry: entry[0].count('.')):
565n/a args = arg.split('.')
566n/a final = args.pop()
567n/a obj = self
568n/a for entry in args:
569n/a obj = getattr(obj, entry)
570n/a setattr(obj, final, val)
571n/a
572n/a
573n/a def __getattr__(self, name):
574n/a if name in {'_mock_methods', '_mock_unsafe'}:
575n/a raise AttributeError(name)
576n/a elif self._mock_methods is not None:
577n/a if name not in self._mock_methods or name in _all_magics:
578n/a raise AttributeError("Mock object has no attribute %r" % name)
579n/a elif _is_magic(name):
580n/a raise AttributeError(name)
581n/a if not self._mock_unsafe:
582n/a if name.startswith(('assert', 'assret')):
583n/a raise AttributeError(name)
584n/a
585n/a result = self._mock_children.get(name)
586n/a if result is _deleted:
587n/a raise AttributeError(name)
588n/a elif result is None:
589n/a wraps = None
590n/a if self._mock_wraps is not None:
591n/a # XXXX should we get the attribute without triggering code
592n/a # execution?
593n/a wraps = getattr(self._mock_wraps, name)
594n/a
595n/a result = self._get_child_mock(
596n/a parent=self, name=name, wraps=wraps, _new_name=name,
597n/a _new_parent=self
598n/a )
599n/a self._mock_children[name] = result
600n/a
601n/a elif isinstance(result, _SpecState):
602n/a result = create_autospec(
603n/a result.spec, result.spec_set, result.instance,
604n/a result.parent, result.name
605n/a )
606n/a self._mock_children[name] = result
607n/a
608n/a return result
609n/a
610n/a
611n/a def __repr__(self):
612n/a _name_list = [self._mock_new_name]
613n/a _parent = self._mock_new_parent
614n/a last = self
615n/a
616n/a dot = '.'
617n/a if _name_list == ['()']:
618n/a dot = ''
619n/a seen = set()
620n/a while _parent is not None:
621n/a last = _parent
622n/a
623n/a _name_list.append(_parent._mock_new_name + dot)
624n/a dot = '.'
625n/a if _parent._mock_new_name == '()':
626n/a dot = ''
627n/a
628n/a _parent = _parent._mock_new_parent
629n/a
630n/a # use ids here so as not to call __hash__ on the mocks
631n/a if id(_parent) in seen:
632n/a break
633n/a seen.add(id(_parent))
634n/a
635n/a _name_list = list(reversed(_name_list))
636n/a _first = last._mock_name or 'mock'
637n/a if len(_name_list) > 1:
638n/a if _name_list[1] not in ('()', '().'):
639n/a _first += '.'
640n/a _name_list[0] = _first
641n/a name = ''.join(_name_list)
642n/a
643n/a name_string = ''
644n/a if name not in ('mock', 'mock.'):
645n/a name_string = ' name=%r' % name
646n/a
647n/a spec_string = ''
648n/a if self._spec_class is not None:
649n/a spec_string = ' spec=%r'
650n/a if self._spec_set:
651n/a spec_string = ' spec_set=%r'
652n/a spec_string = spec_string % self._spec_class.__name__
653n/a return "<%s%s%s id='%s'>" % (
654n/a type(self).__name__,
655n/a name_string,
656n/a spec_string,
657n/a id(self)
658n/a )
659n/a
660n/a
661n/a def __dir__(self):
662n/a """Filter the output of `dir(mock)` to only useful members."""
663n/a if not FILTER_DIR:
664n/a return object.__dir__(self)
665n/a
666n/a extras = self._mock_methods or []
667n/a from_type = dir(type(self))
668n/a from_dict = list(self.__dict__)
669n/a
670n/a from_type = [e for e in from_type if not e.startswith('_')]
671n/a from_dict = [e for e in from_dict if not e.startswith('_') or
672n/a _is_magic(e)]
673n/a return sorted(set(extras + from_type + from_dict +
674n/a list(self._mock_children)))
675n/a
676n/a
677n/a def __setattr__(self, name, value):
678n/a if name in _allowed_names:
679n/a # property setters go through here
680n/a return object.__setattr__(self, name, value)
681n/a elif (self._spec_set and self._mock_methods is not None and
682n/a name not in self._mock_methods and
683n/a name not in self.__dict__):
684n/a raise AttributeError("Mock object has no attribute '%s'" % name)
685n/a elif name in _unsupported_magics:
686n/a msg = 'Attempting to set unsupported magic method %r.' % name
687n/a raise AttributeError(msg)
688n/a elif name in _all_magics:
689n/a if self._mock_methods is not None and name not in self._mock_methods:
690n/a raise AttributeError("Mock object has no attribute '%s'" % name)
691n/a
692n/a if not _is_instance_mock(value):
693n/a setattr(type(self), name, _get_method(name, value))
694n/a original = value
695n/a value = lambda *args, **kw: original(self, *args, **kw)
696n/a else:
697n/a # only set _new_name and not name so that mock_calls is tracked
698n/a # but not method calls
699n/a _check_and_set_parent(self, value, None, name)
700n/a setattr(type(self), name, value)
701n/a self._mock_children[name] = value
702n/a elif name == '__class__':
703n/a self._spec_class = value
704n/a return
705n/a else:
706n/a if _check_and_set_parent(self, value, name, name):
707n/a self._mock_children[name] = value
708n/a return object.__setattr__(self, name, value)
709n/a
710n/a
711n/a def __delattr__(self, name):
712n/a if name in _all_magics and name in type(self).__dict__:
713n/a delattr(type(self), name)
714n/a if name not in self.__dict__:
715n/a # for magic methods that are still MagicProxy objects and
716n/a # not set on the instance itself
717n/a return
718n/a
719n/a if name in self.__dict__:
720n/a object.__delattr__(self, name)
721n/a
722n/a obj = self._mock_children.get(name, _missing)
723n/a if obj is _deleted:
724n/a raise AttributeError(name)
725n/a if obj is not _missing:
726n/a del self._mock_children[name]
727n/a self._mock_children[name] = _deleted
728n/a
729n/a
730n/a def _format_mock_call_signature(self, args, kwargs):
731n/a name = self._mock_name or 'mock'
732n/a return _format_call_signature(name, args, kwargs)
733n/a
734n/a
735n/a def _format_mock_failure_message(self, args, kwargs):
736n/a message = 'Expected call: %s\nActual call: %s'
737n/a expected_string = self._format_mock_call_signature(args, kwargs)
738n/a call_args = self.call_args
739n/a if len(call_args) == 3:
740n/a call_args = call_args[1:]
741n/a actual_string = self._format_mock_call_signature(*call_args)
742n/a return message % (expected_string, actual_string)
743n/a
744n/a
745n/a def _call_matcher(self, _call):
746n/a """
747n/a Given a call (or simply an (args, kwargs) tuple), return a
748n/a comparison key suitable for matching with other calls.
749n/a This is a best effort method which relies on the spec's signature,
750n/a if available, or falls back on the arguments themselves.
751n/a """
752n/a sig = self._spec_signature
753n/a if sig is not None:
754n/a if len(_call) == 2:
755n/a name = ''
756n/a args, kwargs = _call
757n/a else:
758n/a name, args, kwargs = _call
759n/a try:
760n/a return name, sig.bind(*args, **kwargs)
761n/a except TypeError as e:
762n/a return e.with_traceback(None)
763n/a else:
764n/a return _call
765n/a
766n/a def assert_not_called(_mock_self):
767n/a """assert that the mock was never called.
768n/a """
769n/a self = _mock_self
770n/a if self.call_count != 0:
771n/a msg = ("Expected '%s' to not have been called. Called %s times." %
772n/a (self._mock_name or 'mock', self.call_count))
773n/a raise AssertionError(msg)
774n/a
775n/a def assert_called(_mock_self):
776n/a """assert that the mock was called at least once
777n/a """
778n/a self = _mock_self
779n/a if self.call_count == 0:
780n/a msg = ("Expected '%s' to have been called." %
781n/a self._mock_name or 'mock')
782n/a raise AssertionError(msg)
783n/a
784n/a def assert_called_once(_mock_self):
785n/a """assert that the mock was called only once.
786n/a """
787n/a self = _mock_self
788n/a if not self.call_count == 1:
789n/a msg = ("Expected '%s' to have been called once. Called %s times." %
790n/a (self._mock_name or 'mock', self.call_count))
791n/a raise AssertionError(msg)
792n/a
793n/a def assert_called_with(_mock_self, *args, **kwargs):
794n/a """assert that the mock was called with the specified arguments.
795n/a
796n/a Raises an AssertionError if the args and keyword args passed in are
797n/a different to the last call to the mock."""
798n/a self = _mock_self
799n/a if self.call_args is None:
800n/a expected = self._format_mock_call_signature(args, kwargs)
801n/a raise AssertionError('Expected call: %s\nNot called' % (expected,))
802n/a
803n/a def _error_message():
804n/a msg = self._format_mock_failure_message(args, kwargs)
805n/a return msg
806n/a expected = self._call_matcher((args, kwargs))
807n/a actual = self._call_matcher(self.call_args)
808n/a if expected != actual:
809n/a cause = expected if isinstance(expected, Exception) else None
810n/a raise AssertionError(_error_message()) from cause
811n/a
812n/a
813n/a def assert_called_once_with(_mock_self, *args, **kwargs):
814n/a """assert that the mock was called exactly once and with the specified
815n/a arguments."""
816n/a self = _mock_self
817n/a if not self.call_count == 1:
818n/a msg = ("Expected '%s' to be called once. Called %s times." %
819n/a (self._mock_name or 'mock', self.call_count))
820n/a raise AssertionError(msg)
821n/a return self.assert_called_with(*args, **kwargs)
822n/a
823n/a
824n/a def assert_has_calls(self, calls, any_order=False):
825n/a """assert the mock has been called with the specified calls.
826n/a The `mock_calls` list is checked for the calls.
827n/a
828n/a If `any_order` is False (the default) then the calls must be
829n/a sequential. There can be extra calls before or after the
830n/a specified calls.
831n/a
832n/a If `any_order` is True then the calls can be in any order, but
833n/a they must all appear in `mock_calls`."""
834n/a expected = [self._call_matcher(c) for c in calls]
835n/a cause = expected if isinstance(expected, Exception) else None
836n/a all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
837n/a if not any_order:
838n/a if expected not in all_calls:
839n/a raise AssertionError(
840n/a 'Calls not found.\nExpected: %r\n'
841n/a 'Actual: %r' % (_CallList(calls), self.mock_calls)
842n/a ) from cause
843n/a return
844n/a
845n/a all_calls = list(all_calls)
846n/a
847n/a not_found = []
848n/a for kall in expected:
849n/a try:
850n/a all_calls.remove(kall)
851n/a except ValueError:
852n/a not_found.append(kall)
853n/a if not_found:
854n/a raise AssertionError(
855n/a '%r not all found in call list' % (tuple(not_found),)
856n/a ) from cause
857n/a
858n/a
859n/a def assert_any_call(self, *args, **kwargs):
860n/a """assert the mock has been called with the specified arguments.
861n/a
862n/a The assert passes if the mock has *ever* been called, unlike
863n/a `assert_called_with` and `assert_called_once_with` that only pass if
864n/a the call is the most recent one."""
865n/a expected = self._call_matcher((args, kwargs))
866n/a actual = [self._call_matcher(c) for c in self.call_args_list]
867n/a if expected not in actual:
868n/a cause = expected if isinstance(expected, Exception) else None
869n/a expected_string = self._format_mock_call_signature(args, kwargs)
870n/a raise AssertionError(
871n/a '%s call not found' % expected_string
872n/a ) from cause
873n/a
874n/a
875n/a def _get_child_mock(self, **kw):
876n/a """Create the child mocks for attributes and return value.
877n/a By default child mocks will be the same type as the parent.
878n/a Subclasses of Mock may want to override this to customize the way
879n/a child mocks are made.
880n/a
881n/a For non-callable mocks the callable variant will be used (rather than
882n/a any custom subclass)."""
883n/a _type = type(self)
884n/a if not issubclass(_type, CallableMixin):
885n/a if issubclass(_type, NonCallableMagicMock):
886n/a klass = MagicMock
887n/a elif issubclass(_type, NonCallableMock) :
888n/a klass = Mock
889n/a else:
890n/a klass = _type.__mro__[1]
891n/a return klass(**kw)
892n/a
893n/a
894n/a
895n/adef _try_iter(obj):
896n/a if obj is None:
897n/a return obj
898n/a if _is_exception(obj):
899n/a return obj
900n/a if _callable(obj):
901n/a return obj
902n/a try:
903n/a return iter(obj)
904n/a except TypeError:
905n/a # XXXX backwards compatibility
906n/a # but this will blow up on first call - so maybe we should fail early?
907n/a return obj
908n/a
909n/a
910n/a
911n/aclass CallableMixin(Base):
912n/a
913n/a def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
914n/a wraps=None, name=None, spec_set=None, parent=None,
915n/a _spec_state=None, _new_name='', _new_parent=None, **kwargs):
916n/a self.__dict__['_mock_return_value'] = return_value
917n/a
918n/a _safe_super(CallableMixin, self).__init__(
919n/a spec, wraps, name, spec_set, parent,
920n/a _spec_state, _new_name, _new_parent, **kwargs
921n/a )
922n/a
923n/a self.side_effect = side_effect
924n/a
925n/a
926n/a def _mock_check_sig(self, *args, **kwargs):
927n/a # stub method that can be replaced with one with a specific signature
928n/a pass
929n/a
930n/a
931n/a def __call__(_mock_self, *args, **kwargs):
932n/a # can't use self in-case a function / method we are mocking uses self
933n/a # in the signature
934n/a _mock_self._mock_check_sig(*args, **kwargs)
935n/a return _mock_self._mock_call(*args, **kwargs)
936n/a
937n/a
938n/a def _mock_call(_mock_self, *args, **kwargs):
939n/a self = _mock_self
940n/a self.called = True
941n/a self.call_count += 1
942n/a _new_name = self._mock_new_name
943n/a _new_parent = self._mock_new_parent
944n/a
945n/a _call = _Call((args, kwargs), two=True)
946n/a self.call_args = _call
947n/a self.call_args_list.append(_call)
948n/a self.mock_calls.append(_Call(('', args, kwargs)))
949n/a
950n/a seen = set()
951n/a skip_next_dot = _new_name == '()'
952n/a do_method_calls = self._mock_parent is not None
953n/a name = self._mock_name
954n/a while _new_parent is not None:
955n/a this_mock_call = _Call((_new_name, args, kwargs))
956n/a if _new_parent._mock_new_name:
957n/a dot = '.'
958n/a if skip_next_dot:
959n/a dot = ''
960n/a
961n/a skip_next_dot = False
962n/a if _new_parent._mock_new_name == '()':
963n/a skip_next_dot = True
964n/a
965n/a _new_name = _new_parent._mock_new_name + dot + _new_name
966n/a
967n/a if do_method_calls:
968n/a if _new_name == name:
969n/a this_method_call = this_mock_call
970n/a else:
971n/a this_method_call = _Call((name, args, kwargs))
972n/a _new_parent.method_calls.append(this_method_call)
973n/a
974n/a do_method_calls = _new_parent._mock_parent is not None
975n/a if do_method_calls:
976n/a name = _new_parent._mock_name + '.' + name
977n/a
978n/a _new_parent.mock_calls.append(this_mock_call)
979n/a _new_parent = _new_parent._mock_new_parent
980n/a
981n/a # use ids here so as not to call __hash__ on the mocks
982n/a _new_parent_id = id(_new_parent)
983n/a if _new_parent_id in seen:
984n/a break
985n/a seen.add(_new_parent_id)
986n/a
987n/a ret_val = DEFAULT
988n/a effect = self.side_effect
989n/a if effect is not None:
990n/a if _is_exception(effect):
991n/a raise effect
992n/a
993n/a if not _callable(effect):
994n/a result = next(effect)
995n/a if _is_exception(result):
996n/a raise result
997n/a if result is DEFAULT:
998n/a result = self.return_value
999n/a return result
1000n/a
1001n/a ret_val = effect(*args, **kwargs)
1002n/a
1003n/a if (self._mock_wraps is not None and
1004n/a self._mock_return_value is DEFAULT):
1005n/a return self._mock_wraps(*args, **kwargs)
1006n/a if ret_val is DEFAULT:
1007n/a ret_val = self.return_value
1008n/a return ret_val
1009n/a
1010n/a
1011n/a
1012n/aclass Mock(CallableMixin, NonCallableMock):
1013n/a """
1014n/a Create a new `Mock` object. `Mock` takes several optional arguments
1015n/a that specify the behaviour of the Mock object:
1016n/a
1017n/a * `spec`: This can be either a list of strings or an existing object (a
1018n/a class or instance) that acts as the specification for the mock object. If
1019n/a you pass in an object then a list of strings is formed by calling dir on
1020n/a the object (excluding unsupported magic attributes and methods). Accessing
1021n/a any attribute not in this list will raise an `AttributeError`.
1022n/a
1023n/a If `spec` is an object (rather than a list of strings) then
1024n/a `mock.__class__` returns the class of the spec object. This allows mocks
1025n/a to pass `isinstance` tests.
1026n/a
1027n/a * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1028n/a or get an attribute on the mock that isn't on the object passed as
1029n/a `spec_set` will raise an `AttributeError`.
1030n/a
1031n/a * `side_effect`: A function to be called whenever the Mock is called. See
1032n/a the `side_effect` attribute. Useful for raising exceptions or
1033n/a dynamically changing return values. The function is called with the same
1034n/a arguments as the mock, and unless it returns `DEFAULT`, the return
1035n/a value of this function is used as the return value.
1036n/a
1037n/a If `side_effect` is an iterable then each call to the mock will return
1038n/a the next value from the iterable. If any of the members of the iterable
1039n/a are exceptions they will be raised instead of returned.
1040n/a
1041n/a * `return_value`: The value returned when the mock is called. By default
1042n/a this is a new Mock (created on first access). See the
1043n/a `return_value` attribute.
1044n/a
1045n/a * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1046n/a calling the Mock will pass the call through to the wrapped object
1047n/a (returning the real result). Attribute access on the mock will return a
1048n/a Mock object that wraps the corresponding attribute of the wrapped object
1049n/a (so attempting to access an attribute that doesn't exist will raise an
1050n/a `AttributeError`).
1051n/a
1052n/a If the mock has an explicit `return_value` set then calls are not passed
1053n/a to the wrapped object and the `return_value` is returned instead.
1054n/a
1055n/a * `name`: If the mock has a name then it will be used in the repr of the
1056n/a mock. This can be useful for debugging. The name is propagated to child
1057n/a mocks.
1058n/a
1059n/a Mocks can also be called with arbitrary keyword arguments. These will be
1060n/a used to set attributes on the mock after it is created.
1061n/a """
1062n/a
1063n/a
1064n/a
1065n/adef _dot_lookup(thing, comp, import_path):
1066n/a try:
1067n/a return getattr(thing, comp)
1068n/a except AttributeError:
1069n/a __import__(import_path)
1070n/a return getattr(thing, comp)
1071n/a
1072n/a
1073n/adef _importer(target):
1074n/a components = target.split('.')
1075n/a import_path = components.pop(0)
1076n/a thing = __import__(import_path)
1077n/a
1078n/a for comp in components:
1079n/a import_path += ".%s" % comp
1080n/a thing = _dot_lookup(thing, comp, import_path)
1081n/a return thing
1082n/a
1083n/a
1084n/adef _is_started(patcher):
1085n/a # XXXX horrible
1086n/a return hasattr(patcher, 'is_local')
1087n/a
1088n/a
1089n/aclass _patch(object):
1090n/a
1091n/a attribute_name = None
1092n/a _active_patches = []
1093n/a
1094n/a def __init__(
1095n/a self, getter, attribute, new, spec, create,
1096n/a spec_set, autospec, new_callable, kwargs
1097n/a ):
1098n/a if new_callable is not None:
1099n/a if new is not DEFAULT:
1100n/a raise ValueError(
1101n/a "Cannot use 'new' and 'new_callable' together"
1102n/a )
1103n/a if autospec is not None:
1104n/a raise ValueError(
1105n/a "Cannot use 'autospec' and 'new_callable' together"
1106n/a )
1107n/a
1108n/a self.getter = getter
1109n/a self.attribute = attribute
1110n/a self.new = new
1111n/a self.new_callable = new_callable
1112n/a self.spec = spec
1113n/a self.create = create
1114n/a self.has_local = False
1115n/a self.spec_set = spec_set
1116n/a self.autospec = autospec
1117n/a self.kwargs = kwargs
1118n/a self.additional_patchers = []
1119n/a
1120n/a
1121n/a def copy(self):
1122n/a patcher = _patch(
1123n/a self.getter, self.attribute, self.new, self.spec,
1124n/a self.create, self.spec_set,
1125n/a self.autospec, self.new_callable, self.kwargs
1126n/a )
1127n/a patcher.attribute_name = self.attribute_name
1128n/a patcher.additional_patchers = [
1129n/a p.copy() for p in self.additional_patchers
1130n/a ]
1131n/a return patcher
1132n/a
1133n/a
1134n/a def __call__(self, func):
1135n/a if isinstance(func, type):
1136n/a return self.decorate_class(func)
1137n/a return self.decorate_callable(func)
1138n/a
1139n/a
1140n/a def decorate_class(self, klass):
1141n/a for attr in dir(klass):
1142n/a if not attr.startswith(patch.TEST_PREFIX):
1143n/a continue
1144n/a
1145n/a attr_value = getattr(klass, attr)
1146n/a if not hasattr(attr_value, "__call__"):
1147n/a continue
1148n/a
1149n/a patcher = self.copy()
1150n/a setattr(klass, attr, patcher(attr_value))
1151n/a return klass
1152n/a
1153n/a
1154n/a def decorate_callable(self, func):
1155n/a if hasattr(func, 'patchings'):
1156n/a func.patchings.append(self)
1157n/a return func
1158n/a
1159n/a @wraps(func)
1160n/a def patched(*args, **keywargs):
1161n/a extra_args = []
1162n/a entered_patchers = []
1163n/a
1164n/a exc_info = tuple()
1165n/a try:
1166n/a for patching in patched.patchings:
1167n/a arg = patching.__enter__()
1168n/a entered_patchers.append(patching)
1169n/a if patching.attribute_name is not None:
1170n/a keywargs.update(arg)
1171n/a elif patching.new is DEFAULT:
1172n/a extra_args.append(arg)
1173n/a
1174n/a args += tuple(extra_args)
1175n/a return func(*args, **keywargs)
1176n/a except:
1177n/a if (patching not in entered_patchers and
1178n/a _is_started(patching)):
1179n/a # the patcher may have been started, but an exception
1180n/a # raised whilst entering one of its additional_patchers
1181n/a entered_patchers.append(patching)
1182n/a # Pass the exception to __exit__
1183n/a exc_info = sys.exc_info()
1184n/a # re-raise the exception
1185n/a raise
1186n/a finally:
1187n/a for patching in reversed(entered_patchers):
1188n/a patching.__exit__(*exc_info)
1189n/a
1190n/a patched.patchings = [self]
1191n/a return patched
1192n/a
1193n/a
1194n/a def get_original(self):
1195n/a target = self.getter()
1196n/a name = self.attribute
1197n/a
1198n/a original = DEFAULT
1199n/a local = False
1200n/a
1201n/a try:
1202n/a original = target.__dict__[name]
1203n/a except (AttributeError, KeyError):
1204n/a original = getattr(target, name, DEFAULT)
1205n/a else:
1206n/a local = True
1207n/a
1208n/a if name in _builtins and isinstance(target, ModuleType):
1209n/a self.create = True
1210n/a
1211n/a if not self.create and original is DEFAULT:
1212n/a raise AttributeError(
1213n/a "%s does not have the attribute %r" % (target, name)
1214n/a )
1215n/a return original, local
1216n/a
1217n/a
1218n/a def __enter__(self):
1219n/a """Perform the patch."""
1220n/a new, spec, spec_set = self.new, self.spec, self.spec_set
1221n/a autospec, kwargs = self.autospec, self.kwargs
1222n/a new_callable = self.new_callable
1223n/a self.target = self.getter()
1224n/a
1225n/a # normalise False to None
1226n/a if spec is False:
1227n/a spec = None
1228n/a if spec_set is False:
1229n/a spec_set = None
1230n/a if autospec is False:
1231n/a autospec = None
1232n/a
1233n/a if spec is not None and autospec is not None:
1234n/a raise TypeError("Can't specify spec and autospec")
1235n/a if ((spec is not None or autospec is not None) and
1236n/a spec_set not in (True, None)):
1237n/a raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1238n/a
1239n/a original, local = self.get_original()
1240n/a
1241n/a if new is DEFAULT and autospec is None:
1242n/a inherit = False
1243n/a if spec is True:
1244n/a # set spec to the object we are replacing
1245n/a spec = original
1246n/a if spec_set is True:
1247n/a spec_set = original
1248n/a spec = None
1249n/a elif spec is not None:
1250n/a if spec_set is True:
1251n/a spec_set = spec
1252n/a spec = None
1253n/a elif spec_set is True:
1254n/a spec_set = original
1255n/a
1256n/a if spec is not None or spec_set is not None:
1257n/a if original is DEFAULT:
1258n/a raise TypeError("Can't use 'spec' with create=True")
1259n/a if isinstance(original, type):
1260n/a # If we're patching out a class and there is a spec
1261n/a inherit = True
1262n/a
1263n/a Klass = MagicMock
1264n/a _kwargs = {}
1265n/a if new_callable is not None:
1266n/a Klass = new_callable
1267n/a elif spec is not None or spec_set is not None:
1268n/a this_spec = spec
1269n/a if spec_set is not None:
1270n/a this_spec = spec_set
1271n/a if _is_list(this_spec):
1272n/a not_callable = '__call__' not in this_spec
1273n/a else:
1274n/a not_callable = not callable(this_spec)
1275n/a if not_callable:
1276n/a Klass = NonCallableMagicMock
1277n/a
1278n/a if spec is not None:
1279n/a _kwargs['spec'] = spec
1280n/a if spec_set is not None:
1281n/a _kwargs['spec_set'] = spec_set
1282n/a
1283n/a # add a name to mocks
1284n/a if (isinstance(Klass, type) and
1285n/a issubclass(Klass, NonCallableMock) and self.attribute):
1286n/a _kwargs['name'] = self.attribute
1287n/a
1288n/a _kwargs.update(kwargs)
1289n/a new = Klass(**_kwargs)
1290n/a
1291n/a if inherit and _is_instance_mock(new):
1292n/a # we can only tell if the instance should be callable if the
1293n/a # spec is not a list
1294n/a this_spec = spec
1295n/a if spec_set is not None:
1296n/a this_spec = spec_set
1297n/a if (not _is_list(this_spec) and not
1298n/a _instance_callable(this_spec)):
1299n/a Klass = NonCallableMagicMock
1300n/a
1301n/a _kwargs.pop('name')
1302n/a new.return_value = Klass(_new_parent=new, _new_name='()',
1303n/a **_kwargs)
1304n/a elif autospec is not None:
1305n/a # spec is ignored, new *must* be default, spec_set is treated
1306n/a # as a boolean. Should we check spec is not None and that spec_set
1307n/a # is a bool?
1308n/a if new is not DEFAULT:
1309n/a raise TypeError(
1310n/a "autospec creates the mock for you. Can't specify "
1311n/a "autospec and new."
1312n/a )
1313n/a if original is DEFAULT:
1314n/a raise TypeError("Can't use 'autospec' with create=True")
1315n/a spec_set = bool(spec_set)
1316n/a if autospec is True:
1317n/a autospec = original
1318n/a
1319n/a new = create_autospec(autospec, spec_set=spec_set,
1320n/a _name=self.attribute, **kwargs)
1321n/a elif kwargs:
1322n/a # can't set keyword args when we aren't creating the mock
1323n/a # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1324n/a raise TypeError("Can't pass kwargs to a mock we aren't creating")
1325n/a
1326n/a new_attr = new
1327n/a
1328n/a self.temp_original = original
1329n/a self.is_local = local
1330n/a setattr(self.target, self.attribute, new_attr)
1331n/a if self.attribute_name is not None:
1332n/a extra_args = {}
1333n/a if self.new is DEFAULT:
1334n/a extra_args[self.attribute_name] = new
1335n/a for patching in self.additional_patchers:
1336n/a arg = patching.__enter__()
1337n/a if patching.new is DEFAULT:
1338n/a extra_args.update(arg)
1339n/a return extra_args
1340n/a
1341n/a return new
1342n/a
1343n/a
1344n/a def __exit__(self, *exc_info):
1345n/a """Undo the patch."""
1346n/a if not _is_started(self):
1347n/a raise RuntimeError('stop called on unstarted patcher')
1348n/a
1349n/a if self.is_local and self.temp_original is not DEFAULT:
1350n/a setattr(self.target, self.attribute, self.temp_original)
1351n/a else:
1352n/a delattr(self.target, self.attribute)
1353n/a if not self.create and (not hasattr(self.target, self.attribute) or
1354n/a self.attribute in ('__doc__', '__module__',
1355n/a '__defaults__', '__annotations__',
1356n/a '__kwdefaults__')):
1357n/a # needed for proxy objects like django settings
1358n/a setattr(self.target, self.attribute, self.temp_original)
1359n/a
1360n/a del self.temp_original
1361n/a del self.is_local
1362n/a del self.target
1363n/a for patcher in reversed(self.additional_patchers):
1364n/a if _is_started(patcher):
1365n/a patcher.__exit__(*exc_info)
1366n/a
1367n/a
1368n/a def start(self):
1369n/a """Activate a patch, returning any created mock."""
1370n/a result = self.__enter__()
1371n/a self._active_patches.append(self)
1372n/a return result
1373n/a
1374n/a
1375n/a def stop(self):
1376n/a """Stop an active patch."""
1377n/a try:
1378n/a self._active_patches.remove(self)
1379n/a except ValueError:
1380n/a # If the patch hasn't been started this will fail
1381n/a pass
1382n/a
1383n/a return self.__exit__()
1384n/a
1385n/a
1386n/a
1387n/adef _get_target(target):
1388n/a try:
1389n/a target, attribute = target.rsplit('.', 1)
1390n/a except (TypeError, ValueError):
1391n/a raise TypeError("Need a valid target to patch. You supplied: %r" %
1392n/a (target,))
1393n/a getter = lambda: _importer(target)
1394n/a return getter, attribute
1395n/a
1396n/a
1397n/adef _patch_object(
1398n/a target, attribute, new=DEFAULT, spec=None,
1399n/a create=False, spec_set=None, autospec=None,
1400n/a new_callable=None, **kwargs
1401n/a ):
1402n/a """
1403n/a patch the named member (`attribute`) on an object (`target`) with a mock
1404n/a object.
1405n/a
1406n/a `patch.object` can be used as a decorator, class decorator or a context
1407n/a manager. Arguments `new`, `spec`, `create`, `spec_set`,
1408n/a `autospec` and `new_callable` have the same meaning as for `patch`. Like
1409n/a `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1410n/a the mock object it creates.
1411n/a
1412n/a When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1413n/a for choosing which methods to wrap.
1414n/a """
1415n/a getter = lambda: target
1416n/a return _patch(
1417n/a getter, attribute, new, spec, create,
1418n/a spec_set, autospec, new_callable, kwargs
1419n/a )
1420n/a
1421n/a
1422n/adef _patch_multiple(target, spec=None, create=False, spec_set=None,
1423n/a autospec=None, new_callable=None, **kwargs):
1424n/a """Perform multiple patches in a single call. It takes the object to be
1425n/a patched (either as an object or a string to fetch the object by importing)
1426n/a and keyword arguments for the patches::
1427n/a
1428n/a with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1429n/a ...
1430n/a
1431n/a Use `DEFAULT` as the value if you want `patch.multiple` to create
1432n/a mocks for you. In this case the created mocks are passed into a decorated
1433n/a function by keyword, and a dictionary is returned when `patch.multiple` is
1434n/a used as a context manager.
1435n/a
1436n/a `patch.multiple` can be used as a decorator, class decorator or a context
1437n/a manager. The arguments `spec`, `spec_set`, `create`,
1438n/a `autospec` and `new_callable` have the same meaning as for `patch`. These
1439n/a arguments will be applied to *all* patches done by `patch.multiple`.
1440n/a
1441n/a When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1442n/a for choosing which methods to wrap.
1443n/a """
1444n/a if type(target) is str:
1445n/a getter = lambda: _importer(target)
1446n/a else:
1447n/a getter = lambda: target
1448n/a
1449n/a if not kwargs:
1450n/a raise ValueError(
1451n/a 'Must supply at least one keyword argument with patch.multiple'
1452n/a )
1453n/a # need to wrap in a list for python 3, where items is a view
1454n/a items = list(kwargs.items())
1455n/a attribute, new = items[0]
1456n/a patcher = _patch(
1457n/a getter, attribute, new, spec, create, spec_set,
1458n/a autospec, new_callable, {}
1459n/a )
1460n/a patcher.attribute_name = attribute
1461n/a for attribute, new in items[1:]:
1462n/a this_patcher = _patch(
1463n/a getter, attribute, new, spec, create, spec_set,
1464n/a autospec, new_callable, {}
1465n/a )
1466n/a this_patcher.attribute_name = attribute
1467n/a patcher.additional_patchers.append(this_patcher)
1468n/a return patcher
1469n/a
1470n/a
1471n/adef patch(
1472n/a target, new=DEFAULT, spec=None, create=False,
1473n/a spec_set=None, autospec=None, new_callable=None, **kwargs
1474n/a ):
1475n/a """
1476n/a `patch` acts as a function decorator, class decorator or a context
1477n/a manager. Inside the body of the function or with statement, the `target`
1478n/a is patched with a `new` object. When the function/with statement exits
1479n/a the patch is undone.
1480n/a
1481n/a If `new` is omitted, then the target is replaced with a
1482n/a `MagicMock`. If `patch` is used as a decorator and `new` is
1483n/a omitted, the created mock is passed in as an extra argument to the
1484n/a decorated function. If `patch` is used as a context manager the created
1485n/a mock is returned by the context manager.
1486n/a
1487n/a `target` should be a string in the form `'package.module.ClassName'`. The
1488n/a `target` is imported and the specified object replaced with the `new`
1489n/a object, so the `target` must be importable from the environment you are
1490n/a calling `patch` from. The target is imported when the decorated function
1491n/a is executed, not at decoration time.
1492n/a
1493n/a The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1494n/a if patch is creating one for you.
1495n/a
1496n/a In addition you can pass `spec=True` or `spec_set=True`, which causes
1497n/a patch to pass in the object being mocked as the spec/spec_set object.
1498n/a
1499n/a `new_callable` allows you to specify a different class, or callable object,
1500n/a that will be called to create the `new` object. By default `MagicMock` is
1501n/a used.
1502n/a
1503n/a A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1504n/a then the mock will be created with a spec from the object being replaced.
1505n/a All attributes of the mock will also have the spec of the corresponding
1506n/a attribute of the object being replaced. Methods and functions being
1507n/a mocked will have their arguments checked and will raise a `TypeError` if
1508n/a they are called with the wrong signature. For mocks replacing a class,
1509n/a their return value (the 'instance') will have the same spec as the class.
1510n/a
1511n/a Instead of `autospec=True` you can pass `autospec=some_object` to use an
1512n/a arbitrary object as the spec instead of the one being replaced.
1513n/a
1514n/a By default `patch` will fail to replace attributes that don't exist. If
1515n/a you pass in `create=True`, and the attribute doesn't exist, patch will
1516n/a create the attribute for you when the patched function is called, and
1517n/a delete it again afterwards. This is useful for writing tests against
1518n/a attributes that your production code creates at runtime. It is off by
1519n/a default because it can be dangerous. With it switched on you can write
1520n/a passing tests against APIs that don't actually exist!
1521n/a
1522n/a Patch can be used as a `TestCase` class decorator. It works by
1523n/a decorating each test method in the class. This reduces the boilerplate
1524n/a code when your test methods share a common patchings set. `patch` finds
1525n/a tests by looking for method names that start with `patch.TEST_PREFIX`.
1526n/a By default this is `test`, which matches the way `unittest` finds tests.
1527n/a You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1528n/a
1529n/a Patch can be used as a context manager, with the with statement. Here the
1530n/a patching applies to the indented block after the with statement. If you
1531n/a use "as" then the patched object will be bound to the name after the
1532n/a "as"; very useful if `patch` is creating a mock object for you.
1533n/a
1534n/a `patch` takes arbitrary keyword arguments. These will be passed to
1535n/a the `Mock` (or `new_callable`) on construction.
1536n/a
1537n/a `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1538n/a available for alternate use-cases.
1539n/a """
1540n/a getter, attribute = _get_target(target)
1541n/a return _patch(
1542n/a getter, attribute, new, spec, create,
1543n/a spec_set, autospec, new_callable, kwargs
1544n/a )
1545n/a
1546n/a
1547n/aclass _patch_dict(object):
1548n/a """
1549n/a Patch a dictionary, or dictionary like object, and restore the dictionary
1550n/a to its original state after the test.
1551n/a
1552n/a `in_dict` can be a dictionary or a mapping like container. If it is a
1553n/a mapping then it must at least support getting, setting and deleting items
1554n/a plus iterating over keys.
1555n/a
1556n/a `in_dict` can also be a string specifying the name of the dictionary, which
1557n/a will then be fetched by importing it.
1558n/a
1559n/a `values` can be a dictionary of values to set in the dictionary. `values`
1560n/a can also be an iterable of `(key, value)` pairs.
1561n/a
1562n/a If `clear` is True then the dictionary will be cleared before the new
1563n/a values are set.
1564n/a
1565n/a `patch.dict` can also be called with arbitrary keyword arguments to set
1566n/a values in the dictionary::
1567n/a
1568n/a with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1569n/a ...
1570n/a
1571n/a `patch.dict` can be used as a context manager, decorator or class
1572n/a decorator. When used as a class decorator `patch.dict` honours
1573n/a `patch.TEST_PREFIX` for choosing which methods to wrap.
1574n/a """
1575n/a
1576n/a def __init__(self, in_dict, values=(), clear=False, **kwargs):
1577n/a if isinstance(in_dict, str):
1578n/a in_dict = _importer(in_dict)
1579n/a self.in_dict = in_dict
1580n/a # support any argument supported by dict(...) constructor
1581n/a self.values = dict(values)
1582n/a self.values.update(kwargs)
1583n/a self.clear = clear
1584n/a self._original = None
1585n/a
1586n/a
1587n/a def __call__(self, f):
1588n/a if isinstance(f, type):
1589n/a return self.decorate_class(f)
1590n/a @wraps(f)
1591n/a def _inner(*args, **kw):
1592n/a self._patch_dict()
1593n/a try:
1594n/a return f(*args, **kw)
1595n/a finally:
1596n/a self._unpatch_dict()
1597n/a
1598n/a return _inner
1599n/a
1600n/a
1601n/a def decorate_class(self, klass):
1602n/a for attr in dir(klass):
1603n/a attr_value = getattr(klass, attr)
1604n/a if (attr.startswith(patch.TEST_PREFIX) and
1605n/a hasattr(attr_value, "__call__")):
1606n/a decorator = _patch_dict(self.in_dict, self.values, self.clear)
1607n/a decorated = decorator(attr_value)
1608n/a setattr(klass, attr, decorated)
1609n/a return klass
1610n/a
1611n/a
1612n/a def __enter__(self):
1613n/a """Patch the dict."""
1614n/a self._patch_dict()
1615n/a
1616n/a
1617n/a def _patch_dict(self):
1618n/a values = self.values
1619n/a in_dict = self.in_dict
1620n/a clear = self.clear
1621n/a
1622n/a try:
1623n/a original = in_dict.copy()
1624n/a except AttributeError:
1625n/a # dict like object with no copy method
1626n/a # must support iteration over keys
1627n/a original = {}
1628n/a for key in in_dict:
1629n/a original[key] = in_dict[key]
1630n/a self._original = original
1631n/a
1632n/a if clear:
1633n/a _clear_dict(in_dict)
1634n/a
1635n/a try:
1636n/a in_dict.update(values)
1637n/a except AttributeError:
1638n/a # dict like object with no update method
1639n/a for key in values:
1640n/a in_dict[key] = values[key]
1641n/a
1642n/a
1643n/a def _unpatch_dict(self):
1644n/a in_dict = self.in_dict
1645n/a original = self._original
1646n/a
1647n/a _clear_dict(in_dict)
1648n/a
1649n/a try:
1650n/a in_dict.update(original)
1651n/a except AttributeError:
1652n/a for key in original:
1653n/a in_dict[key] = original[key]
1654n/a
1655n/a
1656n/a def __exit__(self, *args):
1657n/a """Unpatch the dict."""
1658n/a self._unpatch_dict()
1659n/a return False
1660n/a
1661n/a start = __enter__
1662n/a stop = __exit__
1663n/a
1664n/a
1665n/adef _clear_dict(in_dict):
1666n/a try:
1667n/a in_dict.clear()
1668n/a except AttributeError:
1669n/a keys = list(in_dict)
1670n/a for key in keys:
1671n/a del in_dict[key]
1672n/a
1673n/a
1674n/adef _patch_stopall():
1675n/a """Stop all active patches. LIFO to unroll nested patches."""
1676n/a for patch in reversed(_patch._active_patches):
1677n/a patch.stop()
1678n/a
1679n/a
1680n/apatch.object = _patch_object
1681n/apatch.dict = _patch_dict
1682n/apatch.multiple = _patch_multiple
1683n/apatch.stopall = _patch_stopall
1684n/apatch.TEST_PREFIX = 'test'
1685n/a
1686n/amagic_methods = (
1687n/a "lt le gt ge eq ne "
1688n/a "getitem setitem delitem "
1689n/a "len contains iter "
1690n/a "hash str sizeof "
1691n/a "enter exit "
1692n/a # we added divmod and rdivmod here instead of numerics
1693n/a # because there is no idivmod
1694n/a "divmod rdivmod neg pos abs invert "
1695n/a "complex int float index "
1696n/a "trunc floor ceil "
1697n/a "bool next "
1698n/a)
1699n/a
1700n/anumerics = (
1701n/a "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
1702n/a)
1703n/ainplace = ' '.join('i%s' % n for n in numerics.split())
1704n/aright = ' '.join('r%s' % n for n in numerics.split())
1705n/a
1706n/a# not including __prepare__, __instancecheck__, __subclasscheck__
1707n/a# (as they are metaclass methods)
1708n/a# __del__ is not supported at all as it causes problems if it exists
1709n/a
1710n/a_non_defaults = {
1711n/a '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1712n/a '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1713n/a '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1714n/a '__repr__', '__dir__', '__subclasses__', '__format__',
1715n/a '__getnewargs_ex__',
1716n/a}
1717n/a
1718n/a
1719n/adef _get_method(name, func):
1720n/a "Turns a callable object (like a mock) into a real function"
1721n/a def method(self, *args, **kw):
1722n/a return func(self, *args, **kw)
1723n/a method.__name__ = name
1724n/a return method
1725n/a
1726n/a
1727n/a_magics = {
1728n/a '__%s__' % method for method in
1729n/a ' '.join([magic_methods, numerics, inplace, right]).split()
1730n/a}
1731n/a
1732n/a_all_magics = _magics | _non_defaults
1733n/a
1734n/a_unsupported_magics = {
1735n/a '__getattr__', '__setattr__',
1736n/a '__init__', '__new__', '__prepare__'
1737n/a '__instancecheck__', '__subclasscheck__',
1738n/a '__del__'
1739n/a}
1740n/a
1741n/a_calculate_return_value = {
1742n/a '__hash__': lambda self: object.__hash__(self),
1743n/a '__str__': lambda self: object.__str__(self),
1744n/a '__sizeof__': lambda self: object.__sizeof__(self),
1745n/a}
1746n/a
1747n/a_return_values = {
1748n/a '__lt__': NotImplemented,
1749n/a '__gt__': NotImplemented,
1750n/a '__le__': NotImplemented,
1751n/a '__ge__': NotImplemented,
1752n/a '__int__': 1,
1753n/a '__contains__': False,
1754n/a '__len__': 0,
1755n/a '__exit__': False,
1756n/a '__complex__': 1j,
1757n/a '__float__': 1.0,
1758n/a '__bool__': True,
1759n/a '__index__': 1,
1760n/a}
1761n/a
1762n/a
1763n/adef _get_eq(self):
1764n/a def __eq__(other):
1765n/a ret_val = self.__eq__._mock_return_value
1766n/a if ret_val is not DEFAULT:
1767n/a return ret_val
1768n/a if self is other:
1769n/a return True
1770n/a return NotImplemented
1771n/a return __eq__
1772n/a
1773n/adef _get_ne(self):
1774n/a def __ne__(other):
1775n/a if self.__ne__._mock_return_value is not DEFAULT:
1776n/a return DEFAULT
1777n/a if self is other:
1778n/a return False
1779n/a return NotImplemented
1780n/a return __ne__
1781n/a
1782n/adef _get_iter(self):
1783n/a def __iter__():
1784n/a ret_val = self.__iter__._mock_return_value
1785n/a if ret_val is DEFAULT:
1786n/a return iter([])
1787n/a # if ret_val was already an iterator, then calling iter on it should
1788n/a # return the iterator unchanged
1789n/a return iter(ret_val)
1790n/a return __iter__
1791n/a
1792n/a_side_effect_methods = {
1793n/a '__eq__': _get_eq,
1794n/a '__ne__': _get_ne,
1795n/a '__iter__': _get_iter,
1796n/a}
1797n/a
1798n/a
1799n/a
1800n/adef _set_return_value(mock, method, name):
1801n/a fixed = _return_values.get(name, DEFAULT)
1802n/a if fixed is not DEFAULT:
1803n/a method.return_value = fixed
1804n/a return
1805n/a
1806n/a return_calulator = _calculate_return_value.get(name)
1807n/a if return_calulator is not None:
1808n/a try:
1809n/a return_value = return_calulator(mock)
1810n/a except AttributeError:
1811n/a # XXXX why do we return AttributeError here?
1812n/a # set it as a side_effect instead?
1813n/a return_value = AttributeError(name)
1814n/a method.return_value = return_value
1815n/a return
1816n/a
1817n/a side_effector = _side_effect_methods.get(name)
1818n/a if side_effector is not None:
1819n/a method.side_effect = side_effector(mock)
1820n/a
1821n/a
1822n/a
1823n/aclass MagicMixin(object):
1824n/a def __init__(self, *args, **kw):
1825n/a self._mock_set_magics() # make magic work for kwargs in init
1826n/a _safe_super(MagicMixin, self).__init__(*args, **kw)
1827n/a self._mock_set_magics() # fix magic broken by upper level init
1828n/a
1829n/a
1830n/a def _mock_set_magics(self):
1831n/a these_magics = _magics
1832n/a
1833n/a if getattr(self, "_mock_methods", None) is not None:
1834n/a these_magics = _magics.intersection(self._mock_methods)
1835n/a
1836n/a remove_magics = set()
1837n/a remove_magics = _magics - these_magics
1838n/a
1839n/a for entry in remove_magics:
1840n/a if entry in type(self).__dict__:
1841n/a # remove unneeded magic methods
1842n/a delattr(self, entry)
1843n/a
1844n/a # don't overwrite existing attributes if called a second time
1845n/a these_magics = these_magics - set(type(self).__dict__)
1846n/a
1847n/a _type = type(self)
1848n/a for entry in these_magics:
1849n/a setattr(_type, entry, MagicProxy(entry, self))
1850n/a
1851n/a
1852n/a
1853n/aclass NonCallableMagicMock(MagicMixin, NonCallableMock):
1854n/a """A version of `MagicMock` that isn't callable."""
1855n/a def mock_add_spec(self, spec, spec_set=False):
1856n/a """Add a spec to a mock. `spec` can either be an object or a
1857n/a list of strings. Only attributes on the `spec` can be fetched as
1858n/a attributes from the mock.
1859n/a
1860n/a If `spec_set` is True then only attributes on the spec can be set."""
1861n/a self._mock_add_spec(spec, spec_set)
1862n/a self._mock_set_magics()
1863n/a
1864n/a
1865n/a
1866n/aclass MagicMock(MagicMixin, Mock):
1867n/a """
1868n/a MagicMock is a subclass of Mock with default implementations
1869n/a of most of the magic methods. You can use MagicMock without having to
1870n/a configure the magic methods yourself.
1871n/a
1872n/a If you use the `spec` or `spec_set` arguments then *only* magic
1873n/a methods that exist in the spec will be created.
1874n/a
1875n/a Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1876n/a """
1877n/a def mock_add_spec(self, spec, spec_set=False):
1878n/a """Add a spec to a mock. `spec` can either be an object or a
1879n/a list of strings. Only attributes on the `spec` can be fetched as
1880n/a attributes from the mock.
1881n/a
1882n/a If `spec_set` is True then only attributes on the spec can be set."""
1883n/a self._mock_add_spec(spec, spec_set)
1884n/a self._mock_set_magics()
1885n/a
1886n/a
1887n/a
1888n/aclass MagicProxy(object):
1889n/a def __init__(self, name, parent):
1890n/a self.name = name
1891n/a self.parent = parent
1892n/a
1893n/a def __call__(self, *args, **kwargs):
1894n/a m = self.create_mock()
1895n/a return m(*args, **kwargs)
1896n/a
1897n/a def create_mock(self):
1898n/a entry = self.name
1899n/a parent = self.parent
1900n/a m = parent._get_child_mock(name=entry, _new_name=entry,
1901n/a _new_parent=parent)
1902n/a setattr(parent, entry, m)
1903n/a _set_return_value(parent, m, entry)
1904n/a return m
1905n/a
1906n/a def __get__(self, obj, _type=None):
1907n/a return self.create_mock()
1908n/a
1909n/a
1910n/a
1911n/aclass _ANY(object):
1912n/a "A helper object that compares equal to everything."
1913n/a
1914n/a def __eq__(self, other):
1915n/a return True
1916n/a
1917n/a def __ne__(self, other):
1918n/a return False
1919n/a
1920n/a def __repr__(self):
1921n/a return '<ANY>'
1922n/a
1923n/aANY = _ANY()
1924n/a
1925n/a
1926n/a
1927n/adef _format_call_signature(name, args, kwargs):
1928n/a message = '%s(%%s)' % name
1929n/a formatted_args = ''
1930n/a args_string = ', '.join([repr(arg) for arg in args])
1931n/a kwargs_string = ', '.join([
1932n/a '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
1933n/a ])
1934n/a if args_string:
1935n/a formatted_args = args_string
1936n/a if kwargs_string:
1937n/a if formatted_args:
1938n/a formatted_args += ', '
1939n/a formatted_args += kwargs_string
1940n/a
1941n/a return message % formatted_args
1942n/a
1943n/a
1944n/a
1945n/aclass _Call(tuple):
1946n/a """
1947n/a A tuple for holding the results of a call to a mock, either in the form
1948n/a `(args, kwargs)` or `(name, args, kwargs)`.
1949n/a
1950n/a If args or kwargs are empty then a call tuple will compare equal to
1951n/a a tuple without those values. This makes comparisons less verbose::
1952n/a
1953n/a _Call(('name', (), {})) == ('name',)
1954n/a _Call(('name', (1,), {})) == ('name', (1,))
1955n/a _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1956n/a
1957n/a The `_Call` object provides a useful shortcut for comparing with call::
1958n/a
1959n/a _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1960n/a _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1961n/a
1962n/a If the _Call has no name then it will match any name.
1963n/a """
1964n/a def __new__(cls, value=(), name='', parent=None, two=False,
1965n/a from_kall=True):
1966n/a args = ()
1967n/a kwargs = {}
1968n/a _len = len(value)
1969n/a if _len == 3:
1970n/a name, args, kwargs = value
1971n/a elif _len == 2:
1972n/a first, second = value
1973n/a if isinstance(first, str):
1974n/a name = first
1975n/a if isinstance(second, tuple):
1976n/a args = second
1977n/a else:
1978n/a kwargs = second
1979n/a else:
1980n/a args, kwargs = first, second
1981n/a elif _len == 1:
1982n/a value, = value
1983n/a if isinstance(value, str):
1984n/a name = value
1985n/a elif isinstance(value, tuple):
1986n/a args = value
1987n/a else:
1988n/a kwargs = value
1989n/a
1990n/a if two:
1991n/a return tuple.__new__(cls, (args, kwargs))
1992n/a
1993n/a return tuple.__new__(cls, (name, args, kwargs))
1994n/a
1995n/a
1996n/a def __init__(self, value=(), name=None, parent=None, two=False,
1997n/a from_kall=True):
1998n/a self.name = name
1999n/a self.parent = parent
2000n/a self.from_kall = from_kall
2001n/a
2002n/a
2003n/a def __eq__(self, other):
2004n/a if other is ANY:
2005n/a return True
2006n/a try:
2007n/a len_other = len(other)
2008n/a except TypeError:
2009n/a return False
2010n/a
2011n/a self_name = ''
2012n/a if len(self) == 2:
2013n/a self_args, self_kwargs = self
2014n/a else:
2015n/a self_name, self_args, self_kwargs = self
2016n/a
2017n/a other_name = ''
2018n/a if len_other == 0:
2019n/a other_args, other_kwargs = (), {}
2020n/a elif len_other == 3:
2021n/a other_name, other_args, other_kwargs = other
2022n/a elif len_other == 1:
2023n/a value, = other
2024n/a if isinstance(value, tuple):
2025n/a other_args = value
2026n/a other_kwargs = {}
2027n/a elif isinstance(value, str):
2028n/a other_name = value
2029n/a other_args, other_kwargs = (), {}
2030n/a else:
2031n/a other_args = ()
2032n/a other_kwargs = value
2033n/a elif len_other == 2:
2034n/a # could be (name, args) or (name, kwargs) or (args, kwargs)
2035n/a first, second = other
2036n/a if isinstance(first, str):
2037n/a other_name = first
2038n/a if isinstance(second, tuple):
2039n/a other_args, other_kwargs = second, {}
2040n/a else:
2041n/a other_args, other_kwargs = (), second
2042n/a else:
2043n/a other_args, other_kwargs = first, second
2044n/a else:
2045n/a return False
2046n/a
2047n/a if self_name and other_name != self_name:
2048n/a return False
2049n/a
2050n/a # this order is important for ANY to work!
2051n/a return (other_args, other_kwargs) == (self_args, self_kwargs)
2052n/a
2053n/a
2054n/a __ne__ = object.__ne__
2055n/a
2056n/a
2057n/a def __call__(self, *args, **kwargs):
2058n/a if self.name is None:
2059n/a return _Call(('', args, kwargs), name='()')
2060n/a
2061n/a name = self.name + '()'
2062n/a return _Call((self.name, args, kwargs), name=name, parent=self)
2063n/a
2064n/a
2065n/a def __getattr__(self, attr):
2066n/a if self.name is None:
2067n/a return _Call(name=attr, from_kall=False)
2068n/a name = '%s.%s' % (self.name, attr)
2069n/a return _Call(name=name, parent=self, from_kall=False)
2070n/a
2071n/a
2072n/a def count(self, *args, **kwargs):
2073n/a return self.__getattr__('count')(*args, **kwargs)
2074n/a
2075n/a def index(self, *args, **kwargs):
2076n/a return self.__getattr__('index')(*args, **kwargs)
2077n/a
2078n/a def __repr__(self):
2079n/a if not self.from_kall:
2080n/a name = self.name or 'call'
2081n/a if name.startswith('()'):
2082n/a name = 'call%s' % name
2083n/a return name
2084n/a
2085n/a if len(self) == 2:
2086n/a name = 'call'
2087n/a args, kwargs = self
2088n/a else:
2089n/a name, args, kwargs = self
2090n/a if not name:
2091n/a name = 'call'
2092n/a elif not name.startswith('()'):
2093n/a name = 'call.%s' % name
2094n/a else:
2095n/a name = 'call%s' % name
2096n/a return _format_call_signature(name, args, kwargs)
2097n/a
2098n/a
2099n/a def call_list(self):
2100n/a """For a call object that represents multiple calls, `call_list`
2101n/a returns a list of all the intermediate calls as well as the
2102n/a final call."""
2103n/a vals = []
2104n/a thing = self
2105n/a while thing is not None:
2106n/a if thing.from_kall:
2107n/a vals.append(thing)
2108n/a thing = thing.parent
2109n/a return _CallList(reversed(vals))
2110n/a
2111n/a
2112n/acall = _Call(from_kall=False)
2113n/a
2114n/a
2115n/a
2116n/adef create_autospec(spec, spec_set=False, instance=False, _parent=None,
2117n/a _name=None, **kwargs):
2118n/a """Create a mock object using another object as a spec. Attributes on the
2119n/a mock will use the corresponding attribute on the `spec` object as their
2120n/a spec.
2121n/a
2122n/a Functions or methods being mocked will have their arguments checked
2123n/a to check that they are called with the correct signature.
2124n/a
2125n/a If `spec_set` is True then attempting to set attributes that don't exist
2126n/a on the spec object will raise an `AttributeError`.
2127n/a
2128n/a If a class is used as a spec then the return value of the mock (the
2129n/a instance of the class) will have the same spec. You can use a class as the
2130n/a spec for an instance object by passing `instance=True`. The returned mock
2131n/a will only be callable if instances of the mock are callable.
2132n/a
2133n/a `create_autospec` also takes arbitrary keyword arguments that are passed to
2134n/a the constructor of the created mock."""
2135n/a if _is_list(spec):
2136n/a # can't pass a list instance to the mock constructor as it will be
2137n/a # interpreted as a list of strings
2138n/a spec = type(spec)
2139n/a
2140n/a is_type = isinstance(spec, type)
2141n/a
2142n/a _kwargs = {'spec': spec}
2143n/a if spec_set:
2144n/a _kwargs = {'spec_set': spec}
2145n/a elif spec is None:
2146n/a # None we mock with a normal mock without a spec
2147n/a _kwargs = {}
2148n/a if _kwargs and instance:
2149n/a _kwargs['_spec_as_instance'] = True
2150n/a
2151n/a _kwargs.update(kwargs)
2152n/a
2153n/a Klass = MagicMock
2154n/a if inspect.isdatadescriptor(spec):
2155n/a # descriptors don't have a spec
2156n/a # because we don't know what type they return
2157n/a _kwargs = {}
2158n/a elif not _callable(spec):
2159n/a Klass = NonCallableMagicMock
2160n/a elif is_type and instance and not _instance_callable(spec):
2161n/a Klass = NonCallableMagicMock
2162n/a
2163n/a _name = _kwargs.pop('name', _name)
2164n/a
2165n/a _new_name = _name
2166n/a if _parent is None:
2167n/a # for a top level object no _new_name should be set
2168n/a _new_name = ''
2169n/a
2170n/a mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2171n/a name=_name, **_kwargs)
2172n/a
2173n/a if isinstance(spec, FunctionTypes):
2174n/a # should only happen at the top level because we don't
2175n/a # recurse for functions
2176n/a mock = _set_signature(mock, spec)
2177n/a else:
2178n/a _check_signature(spec, mock, is_type, instance)
2179n/a
2180n/a if _parent is not None and not instance:
2181n/a _parent._mock_children[_name] = mock
2182n/a
2183n/a if is_type and not instance and 'return_value' not in kwargs:
2184n/a mock.return_value = create_autospec(spec, spec_set, instance=True,
2185n/a _name='()', _parent=mock)
2186n/a
2187n/a for entry in dir(spec):
2188n/a if _is_magic(entry):
2189n/a # MagicMock already does the useful magic methods for us
2190n/a continue
2191n/a
2192n/a # XXXX do we need a better way of getting attributes without
2193n/a # triggering code execution (?) Probably not - we need the actual
2194n/a # object to mock it so we would rather trigger a property than mock
2195n/a # the property descriptor. Likewise we want to mock out dynamically
2196n/a # provided attributes.
2197n/a # XXXX what about attributes that raise exceptions other than
2198n/a # AttributeError on being fetched?
2199n/a # we could be resilient against it, or catch and propagate the
2200n/a # exception when the attribute is fetched from the mock
2201n/a try:
2202n/a original = getattr(spec, entry)
2203n/a except AttributeError:
2204n/a continue
2205n/a
2206n/a kwargs = {'spec': original}
2207n/a if spec_set:
2208n/a kwargs = {'spec_set': original}
2209n/a
2210n/a if not isinstance(original, FunctionTypes):
2211n/a new = _SpecState(original, spec_set, mock, entry, instance)
2212n/a mock._mock_children[entry] = new
2213n/a else:
2214n/a parent = mock
2215n/a if isinstance(spec, FunctionTypes):
2216n/a parent = mock.mock
2217n/a
2218n/a skipfirst = _must_skip(spec, entry, is_type)
2219n/a kwargs['_eat_self'] = skipfirst
2220n/a new = MagicMock(parent=parent, name=entry, _new_name=entry,
2221n/a _new_parent=parent,
2222n/a **kwargs)
2223n/a mock._mock_children[entry] = new
2224n/a _check_signature(original, new, skipfirst=skipfirst)
2225n/a
2226n/a # so functions created with _set_signature become instance attributes,
2227n/a # *plus* their underlying mock exists in _mock_children of the parent
2228n/a # mock. Adding to _mock_children may be unnecessary where we are also
2229n/a # setting as an instance attribute?
2230n/a if isinstance(new, FunctionTypes):
2231n/a setattr(mock, entry, new)
2232n/a
2233n/a return mock
2234n/a
2235n/a
2236n/adef _must_skip(spec, entry, is_type):
2237n/a """
2238n/a Return whether we should skip the first argument on spec's `entry`
2239n/a attribute.
2240n/a """
2241n/a if not isinstance(spec, type):
2242n/a if entry in getattr(spec, '__dict__', {}):
2243n/a # instance attribute - shouldn't skip
2244n/a return False
2245n/a spec = spec.__class__
2246n/a
2247n/a for klass in spec.__mro__:
2248n/a result = klass.__dict__.get(entry, DEFAULT)
2249n/a if result is DEFAULT:
2250n/a continue
2251n/a if isinstance(result, (staticmethod, classmethod)):
2252n/a return False
2253n/a elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2254n/a # Normal method => skip if looked up on type
2255n/a # (if looked up on instance, self is already skipped)
2256n/a return is_type
2257n/a else:
2258n/a return False
2259n/a
2260n/a # shouldn't get here unless function is a dynamically provided attribute
2261n/a # XXXX untested behaviour
2262n/a return is_type
2263n/a
2264n/a
2265n/adef _get_class(obj):
2266n/a try:
2267n/a return obj.__class__
2268n/a except AttributeError:
2269n/a # it is possible for objects to have no __class__
2270n/a return type(obj)
2271n/a
2272n/a
2273n/aclass _SpecState(object):
2274n/a
2275n/a def __init__(self, spec, spec_set=False, parent=None,
2276n/a name=None, ids=None, instance=False):
2277n/a self.spec = spec
2278n/a self.ids = ids
2279n/a self.spec_set = spec_set
2280n/a self.parent = parent
2281n/a self.instance = instance
2282n/a self.name = name
2283n/a
2284n/a
2285n/aFunctionTypes = (
2286n/a # python function
2287n/a type(create_autospec),
2288n/a # instance method
2289n/a type(ANY.__eq__),
2290n/a)
2291n/a
2292n/aMethodWrapperTypes = (
2293n/a type(ANY.__eq__.__get__),
2294n/a)
2295n/a
2296n/a
2297n/afile_spec = None
2298n/a
2299n/adef _iterate_read_data(read_data):
2300n/a # Helper for mock_open:
2301n/a # Retrieve lines from read_data via a generator so that separate calls to
2302n/a # readline, read, and readlines are properly interleaved
2303n/a sep = b'\n' if isinstance(read_data, bytes) else '\n'
2304n/a data_as_list = [l + sep for l in read_data.split(sep)]
2305n/a
2306n/a if data_as_list[-1] == sep:
2307n/a # If the last line ended in a newline, the list comprehension will have an
2308n/a # extra entry that's just a newline. Remove this.
2309n/a data_as_list = data_as_list[:-1]
2310n/a else:
2311n/a # If there wasn't an extra newline by itself, then the file being
2312n/a # emulated doesn't have a newline to end the last line remove the
2313n/a # newline that our naive format() added
2314n/a data_as_list[-1] = data_as_list[-1][:-1]
2315n/a
2316n/a for line in data_as_list:
2317n/a yield line
2318n/a
2319n/a
2320n/adef mock_open(mock=None, read_data=''):
2321n/a """
2322n/a A helper function to create a mock to replace the use of `open`. It works
2323n/a for `open` called directly or used as a context manager.
2324n/a
2325n/a The `mock` argument is the mock object to configure. If `None` (the
2326n/a default) then a `MagicMock` will be created for you, with the API limited
2327n/a to methods or attributes available on standard file handles.
2328n/a
2329n/a `read_data` is a string for the `read` methoddline`, and `readlines` of the
2330n/a file handle to return. This is an empty string by default.
2331n/a """
2332n/a def _readlines_side_effect(*args, **kwargs):
2333n/a if handle.readlines.return_value is not None:
2334n/a return handle.readlines.return_value
2335n/a return list(_state[0])
2336n/a
2337n/a def _read_side_effect(*args, **kwargs):
2338n/a if handle.read.return_value is not None:
2339n/a return handle.read.return_value
2340n/a return type(read_data)().join(_state[0])
2341n/a
2342n/a def _readline_side_effect():
2343n/a if handle.readline.return_value is not None:
2344n/a while True:
2345n/a yield handle.readline.return_value
2346n/a for line in _state[0]:
2347n/a yield line
2348n/a while True:
2349n/a yield type(read_data)()
2350n/a
2351n/a
2352n/a global file_spec
2353n/a if file_spec is None:
2354n/a import _io
2355n/a file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2356n/a
2357n/a if mock is None:
2358n/a mock = MagicMock(name='open', spec=open)
2359n/a
2360n/a handle = MagicMock(spec=file_spec)
2361n/a handle.__enter__.return_value = handle
2362n/a
2363n/a _state = [_iterate_read_data(read_data), None]
2364n/a
2365n/a handle.write.return_value = None
2366n/a handle.read.return_value = None
2367n/a handle.readline.return_value = None
2368n/a handle.readlines.return_value = None
2369n/a
2370n/a handle.read.side_effect = _read_side_effect
2371n/a _state[1] = _readline_side_effect()
2372n/a handle.readline.side_effect = _state[1]
2373n/a handle.readlines.side_effect = _readlines_side_effect
2374n/a
2375n/a def reset_data(*args, **kwargs):
2376n/a _state[0] = _iterate_read_data(read_data)
2377n/a if handle.readline.side_effect == _state[1]:
2378n/a # Only reset the side effect if the user hasn't overridden it.
2379n/a _state[1] = _readline_side_effect()
2380n/a handle.readline.side_effect = _state[1]
2381n/a return DEFAULT
2382n/a
2383n/a mock.side_effect = reset_data
2384n/a mock.return_value = handle
2385n/a return mock
2386n/a
2387n/a
2388n/aclass PropertyMock(Mock):
2389n/a """
2390n/a A mock intended to be used as a property, or other descriptor, on a class.
2391n/a `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2392n/a a return value when it is fetched.
2393n/a
2394n/a Fetching a `PropertyMock` instance from an object calls the mock, with
2395n/a no args. Setting it calls the mock with the value being set.
2396n/a """
2397n/a def _get_child_mock(self, **kwargs):
2398n/a return MagicMock(**kwargs)
2399n/a
2400n/a def __get__(self, obj, obj_type):
2401n/a return self()
2402n/a def __set__(self, obj, val):
2403n/a self(val)