Merge ~bladernr/checkbox-support/+git/packaging:remove-mock-patch into ~checkbox-dev/checkbox-support/+git/packaging:master

Proposed by Jeff Lane 
Status: Merged
Approved by: Jeff Lane 
Approved revision: a00a6a77ac90f0c539f9f87ebe58b9723a24806f
Merged at revision: a00a6a77ac90f0c539f9f87ebe58b9723a24806f
Proposed branch: ~bladernr/checkbox-support/+git/packaging:remove-mock-patch
Merge into: ~checkbox-dev/checkbox-support/+git/packaging:master
Diff against target: 2425 lines (+0/-2419)
1 file modified
dev/null (+0/-2419)
Reviewer Review Type Date Requested Status
Maciej Kisielewski (community) Approve
Review via email: mp+332263@code.launchpad.net

Description of the change

Removes the unvendorize patch that affected checkbox_support/vendors/mock.py because that file no longer exists, and the patch is triggering build failures.

To post a comment you must log in.
Revision history for this message
Maciej Kisielewski (kissiel) wrote :

I'm sorry for missing that .deb build dependency.
The patch makes sense.

review: Approve

Preview Diff

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

Subscribers

People subscribed via source and target branches