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

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

Description of the change

remove vendorized mock and use the one from standard lib

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

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

completely forgot this vendorized version. +1

review: Approve

Preview Diff

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

Subscribers

People subscribed via source and target branches