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