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

Subscribers

People subscribed via source and target branches