Merge ~kissiel/checkbox-support:use-standard-mock into checkbox-support:master

Proposed by Maciej Kisielewski
Status: Merged
Approved by: Maciej Kisielewski
Approved revision: e15dd530002b4150e710eb09339ef8601fbe553a
Merged at revision: 521b44bad0166d1e7d39e9e0ce401df184308106
Proposed branch: ~kissiel/checkbox-support:use-standard-mock
Merge into: checkbox-support:master
Diff against target: 2422 lines (+1/-2370)
2 files modified
checkbox_support/scripts/tests/test_gputest_benchmark.py (+1/-1)
dev/null (+0/-2369)
Reviewer Review Type Date Requested Status
Sylvain Pineau (community) Approve
Review via email: mp+332051@code.launchpad.net

Description of the change

remove vendorized mock and use the one from standard lib

The oldest python we target now is 3.4. unittest.mock was introduced in 3.3, so we don't need to vendorized the lib.

To post a comment you must log in.
Revision history for this message
Sylvain Pineau (sylvain-pineau) wrote :

completely forgot this vendorized version. +1

review: Approve

Preview Diff

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

Subscribers

People subscribed via source and target branches