mock.py (51156B)
1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\lib\mock.py 2 __all__ = ('Mock', 3 'MagicMock', 4 'patch', 5 'sentinel', 6 'DEFAULT', 7 'ANY', 8 'call', 9 'create_autospec', 10 'FILTER_DIR', 11 'NonCallableMock', 12 'NonCallableMagicMock', 13 'mock_open', 14 'PropertyMock') 15 __version__ = '1.0b1' 16 import pprint 17 import sys 18 try: 19 import inspect 20 except ImportError: 21 inspect = None 22 23 try: 24 from functools import wraps 25 except ImportError: 26 27 def wraps(original): 28 29 def inner(f): 30 f.__name__ = original.__name__ 31 f.__doc__ = original.__doc__ 32 f.__module__ = original.__module__ 33 return f 34 35 return inner 36 37 38 try: 39 unicode 40 except NameError: 41 basestring = unicode = str 42 43 try: 44 long 45 except NameError: 46 long = int 47 48 try: 49 BaseException 50 except NameError: 51 BaseException = Exception 52 53 try: 54 next 55 except NameError: 56 57 def next(obj): 58 return obj.next() 59 60 61 BaseExceptions = (BaseException,) 62 if 'java' in sys.platform: 63 import java 64 BaseExceptions = (BaseException, java.lang.Throwable) 65 try: 66 _isidentifier = str.isidentifier 67 except AttributeError: 68 import keyword 69 import re 70 regex = re.compile('^[a-z_][a-z0-9_]*$', re.I) 71 72 def _isidentifier(string): 73 if string in keyword.kwlist: 74 return False 75 return regex.match(string) 76 77 78 inPy3k = sys.version_info[0] == 3 79 _super = super 80 self = 'im_self' 81 builtin = '__builtin__' 82 if inPy3k: 83 self = '__self__' 84 builtin = 'builtins' 85 FILTER_DIR = True 86 87 def _is_instance_mock(obj): 88 return issubclass(type(obj), NonCallableMock) 89 90 91 def _is_exception(obj): 92 return isinstance(obj, BaseExceptions) or isinstance(obj, ClassTypes) and issubclass(obj, BaseExceptions) 93 94 95 class _slotted(object): 96 __slots__ = ['a'] 97 98 99 DescriptorTypes = (type(_slotted.a), property) 100 101 def _getsignature(func, skipfirst, instance = False): 102 if inspect is None: 103 raise ImportError('inspect module not available') 104 if isinstance(func, ClassTypes) and not instance: 105 try: 106 func = func.__init__ 107 except AttributeError: 108 return 109 110 skipfirst = True 111 elif not isinstance(func, FunctionTypes): 112 try: 113 func = func.__call__ 114 except AttributeError: 115 return 116 117 if inPy3k: 118 try: 119 argspec = inspect.getfullargspec(func) 120 except TypeError: 121 return 122 123 regargs, varargs, varkw, defaults, kwonly, kwonlydef, ann = argspec 124 else: 125 try: 126 regargs, varargs, varkwargs, defaults = inspect.getargspec(func) 127 except TypeError: 128 return 129 130 if getattr(func, self, None) is not None: 131 regargs = regargs[1:] 132 if skipfirst: 133 regargs = regargs[1:] 134 if inPy3k: 135 signature = inspect.formatargspec(regargs, varargs, varkw, defaults, kwonly, kwonlydef, ann, formatvalue=lambda value: '') 136 else: 137 signature = inspect.formatargspec(regargs, varargs, varkwargs, defaults, formatvalue=lambda value: '') 138 return (signature[1:-1], func) 139 140 141 def _check_signature(func, mock, skipfirst, instance = False): 142 if not _callable(func): 143 return 144 result = _getsignature(func, skipfirst, instance) 145 if result is None: 146 return 147 signature, func = result 148 src = 'lambda _mock_self, %s: None' % signature 149 checksig = eval(src, {}) 150 _copy_func_details(func, checksig) 151 type(mock)._mock_check_sig = checksig 152 153 154 def _copy_func_details(func, funcopy): 155 funcopy.__name__ = func.__name__ 156 funcopy.__doc__ = func.__doc__ 157 funcopy.__module__ = func.__module__ 158 if not inPy3k: 159 funcopy.func_defaults = func.func_defaults 160 return 161 funcopy.__defaults__ = func.__defaults__ 162 funcopy.__kwdefaults__ = func.__kwdefaults__ 163 164 165 def _callable(obj): 166 if isinstance(obj, ClassTypes): 167 return True 168 if getattr(obj, '__call__', None) is not None: 169 return True 170 return False 171 172 173 def _is_list(obj): 174 return type(obj) in (list, tuple) 175 176 177 def _instance_callable(obj): 178 if not isinstance(obj, ClassTypes): 179 return getattr(obj, '__call__', None) is not None 180 klass = obj 181 if klass.__dict__.get('__call__') is not None: 182 return True 183 for base in klass.__bases__: 184 if _instance_callable(base): 185 return True 186 187 return False 188 189 190 def _set_signature(mock, original, instance = False): 191 if not _callable(original): 192 return 193 skipfirst = isinstance(original, ClassTypes) 194 result = _getsignature(original, skipfirst, instance) 195 if result is None: 196 return 197 signature, func = result 198 src = 'lambda %s: None' % signature 199 checksig = eval(src, {}) 200 _copy_func_details(func, checksig) 201 name = original.__name__ 202 if not _isidentifier(name): 203 name = 'funcopy' 204 context = {'_checksig_': checksig, 205 'mock': mock} 206 src = 'def %s(*args, **kwargs):\n _checksig_(*args, **kwargs)\n return mock(*args, **kwargs)' % name 207 exec src in context 208 funcopy = context[name] 209 _setup_func(funcopy, mock) 210 return funcopy 211 212 213 def _setup_func(funcopy, mock): 214 funcopy.mock = mock 215 if not _is_instance_mock(mock): 216 return 217 218 def assert_called_with(*args, **kwargs): 219 return mock.assert_called_with(*args, **kwargs) 220 221 def assert_called_once_with(*args, **kwargs): 222 return mock.assert_called_once_with(*args, **kwargs) 223 224 def assert_has_calls(*args, **kwargs): 225 return mock.assert_has_calls(*args, **kwargs) 226 227 def assert_any_call(*args, **kwargs): 228 return mock.assert_any_call(*args, **kwargs) 229 230 def reset_mock(): 231 funcopy.method_calls = _CallList() 232 funcopy.mock_calls = _CallList() 233 mock.reset_mock() 234 ret = funcopy.return_value 235 if _is_instance_mock(ret) and ret is not mock: 236 ret.reset_mock() 237 238 funcopy.called = False 239 funcopy.call_count = 0 240 funcopy.call_args = None 241 funcopy.call_args_list = _CallList() 242 funcopy.method_calls = _CallList() 243 funcopy.mock_calls = _CallList() 244 funcopy.return_value = mock.return_value 245 funcopy.side_effect = mock.side_effect 246 funcopy._mock_children = mock._mock_children 247 funcopy.assert_called_with = assert_called_with 248 funcopy.assert_called_once_with = assert_called_once_with 249 funcopy.assert_has_calls = assert_has_calls 250 funcopy.assert_any_call = assert_any_call 251 funcopy.reset_mock = reset_mock 252 mock._mock_delegate = funcopy 253 254 255 def _is_magic(name): 256 return '__%s__' % name[2:-2] == name 257 258 259 class _SentinelObject(object): 260 261 def __init__(self, name): 262 self.name = name 263 264 def __repr__(self): 265 return 'sentinel.%s' % self.name 266 267 268 class _Sentinel(object): 269 270 def __init__(self): 271 self._sentinels = {} 272 273 def __getattr__(self, name): 274 if name == '__bases__': 275 raise AttributeError 276 return self._sentinels.setdefault(name, _SentinelObject(name)) 277 278 279 sentinel = _Sentinel() 280 DEFAULT = sentinel.DEFAULT 281 _missing = sentinel.MISSING 282 _deleted = sentinel.DELETED 283 284 class OldStyleClass(): 285 pass 286 287 288 ClassType = type(OldStyleClass) 289 290 def _copy(value): 291 if type(value) in (dict, 292 list, 293 tuple, 294 set): 295 return type(value)(value) 296 return value 297 298 299 ClassTypes = (type,) 300 if not inPy3k: 301 ClassTypes = (type, ClassType) 302 _allowed_names = set(['return_value', 303 '_mock_return_value', 304 'side_effect', 305 '_mock_side_effect', 306 '_mock_parent', 307 '_mock_new_parent', 308 '_mock_name', 309 '_mock_new_name']) 310 311 def _delegating_property(name): 312 _allowed_names.add(name) 313 _the_name = '_mock_' + name 314 315 def _get(self, name = name, _the_name = _the_name): 316 sig = self._mock_delegate 317 if sig is None: 318 return getattr(self, _the_name) 319 return getattr(sig, name) 320 321 def _set(self, value, name = name, _the_name = _the_name): 322 sig = self._mock_delegate 323 if sig is None: 324 self.__dict__[_the_name] = value 325 else: 326 setattr(sig, name, value) 327 328 return property(_get, _set) 329 330 331 class _CallList(list): 332 333 def __contains__(self, value): 334 if not isinstance(value, list): 335 return list.__contains__(self, value) 336 len_value = len(value) 337 len_self = len(self) 338 if len_value > len_self: 339 return False 340 for i in range(0, len_self - len_value + 1): 341 sub_list = self[i:i + len_value] 342 if sub_list == value: 343 return True 344 345 return False 346 347 def __repr__(self): 348 return pprint.pformat(list(self)) 349 350 351 def _check_and_set_parent(parent, value, name, new_name): 352 if not _is_instance_mock(value): 353 return False 354 if value._mock_name or value._mock_new_name or value._mock_parent is not None or value._mock_new_parent is not None: 355 return False 356 _parent = parent 357 while _parent is not None: 358 if _parent is value: 359 return False 360 _parent = _parent._mock_new_parent 361 362 if new_name: 363 value._mock_new_parent = parent 364 value._mock_new_name = new_name 365 if name: 366 value._mock_parent = parent 367 value._mock_name = name 368 return True 369 370 371 class Base(object): 372 _mock_return_value = DEFAULT 373 _mock_side_effect = None 374 375 def __init__(self, *args, **kwargs): 376 pass 377 378 379 class NonCallableMock(Base): 380 381 def __new__(cls, *args, **kw): 382 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__}) 383 instance = object.__new__(new) 384 return instance 385 386 def __init__(self, spec = None, wraps = None, name = None, spec_set = None, parent = None, _spec_state = None, _new_name = '', _new_parent = None, **kwargs): 387 if _new_parent is None: 388 _new_parent = parent 389 __dict__ = self.__dict__ 390 __dict__['_mock_parent'] = parent 391 __dict__['_mock_name'] = name 392 __dict__['_mock_new_name'] = _new_name 393 __dict__['_mock_new_parent'] = _new_parent 394 if spec_set is not None: 395 spec = spec_set 396 spec_set = True 397 self._mock_add_spec(spec, spec_set) 398 __dict__['_mock_children'] = {} 399 __dict__['_mock_wraps'] = wraps 400 __dict__['_mock_delegate'] = None 401 __dict__['_mock_called'] = False 402 __dict__['_mock_call_args'] = None 403 __dict__['_mock_call_count'] = 0 404 __dict__['_mock_call_args_list'] = _CallList() 405 __dict__['_mock_mock_calls'] = _CallList() 406 __dict__['method_calls'] = _CallList() 407 if kwargs: 408 self.configure_mock(**kwargs) 409 _super(NonCallableMock, self).__init__(spec, wraps, name, spec_set, parent, _spec_state) 410 411 def attach_mock(self, mock, attribute): 412 mock._mock_parent = None 413 mock._mock_new_parent = None 414 mock._mock_name = '' 415 mock._mock_new_name = None 416 setattr(self, attribute, mock) 417 418 def mock_add_spec(self, spec, spec_set = False): 419 self._mock_add_spec(spec, spec_set) 420 421 def _mock_add_spec(self, spec, spec_set): 422 _spec_class = None 423 if spec is not None and not _is_list(spec): 424 if isinstance(spec, ClassTypes): 425 _spec_class = spec 426 else: 427 _spec_class = _get_class(spec) 428 spec = dir(spec) 429 __dict__ = self.__dict__ 430 __dict__['_spec_class'] = _spec_class 431 __dict__['_spec_set'] = spec_set 432 __dict__['_mock_methods'] = spec 433 434 def __get_return_value(self): 435 ret = self._mock_return_value 436 if self._mock_delegate is not None: 437 ret = self._mock_delegate.return_value 438 if ret is DEFAULT: 439 ret = self._get_child_mock(_new_parent=self, _new_name='()') 440 self.return_value = ret 441 return ret 442 443 def __set_return_value(self, value): 444 if self._mock_delegate is not None: 445 self._mock_delegate.return_value = value 446 else: 447 self._mock_return_value = value 448 _check_and_set_parent(self, value, None, '()') 449 450 __return_value_doc = 'The value to be returned when the mock is called.' 451 return_value = property(__get_return_value, __set_return_value, __return_value_doc) 452 453 @property 454 def __class__(self): 455 if self._spec_class is None: 456 return type(self) 457 return self._spec_class 458 459 called = _delegating_property('called') 460 call_count = _delegating_property('call_count') 461 call_args = _delegating_property('call_args') 462 call_args_list = _delegating_property('call_args_list') 463 mock_calls = _delegating_property('mock_calls') 464 465 def __get_side_effect(self): 466 sig = self._mock_delegate 467 if sig is None: 468 return self._mock_side_effect 469 return sig.side_effect 470 471 def __set_side_effect(self, value): 472 value = _try_iter(value) 473 sig = self._mock_delegate 474 if sig is None: 475 self._mock_side_effect = value 476 else: 477 sig.side_effect = value 478 479 side_effect = property(__get_side_effect, __set_side_effect) 480 481 def reset_mock(self): 482 self.called = False 483 self.call_args = None 484 self.call_count = 0 485 self.mock_calls = _CallList() 486 self.call_args_list = _CallList() 487 self.method_calls = _CallList() 488 for child in self._mock_children.values(): 489 if isinstance(child, _SpecState): 490 continue 491 child.reset_mock() 492 493 ret = self._mock_return_value 494 if _is_instance_mock(ret) and ret is not self: 495 ret.reset_mock() 496 497 def configure_mock(self, **kwargs): 498 for arg, val in sorted(kwargs.items(), key=lambda entry: entry[0].count('.')): 499 args = arg.split('.') 500 final = args.pop() 501 obj = self 502 for entry in args: 503 obj = getattr(obj, entry) 504 505 setattr(obj, final, val) 506 507 def __getattr__(self, name): 508 if name == '_mock_methods': 509 raise AttributeError(name) 510 elif self._mock_methods is not None: 511 if name not in self._mock_methods or name in _all_magics: 512 raise AttributeError('Mock object has no attribute %r' % name) 513 elif _is_magic(name): 514 raise AttributeError(name) 515 result = self._mock_children.get(name) 516 if result is _deleted: 517 raise AttributeError(name) 518 elif result is None: 519 wraps = None 520 if self._mock_wraps is not None: 521 wraps = getattr(self._mock_wraps, name) 522 result = self._get_child_mock(parent=self, name=name, wraps=wraps, _new_name=name, _new_parent=self) 523 self._mock_children[name] = result 524 elif isinstance(result, _SpecState): 525 result = create_autospec(result.spec, result.spec_set, result.instance, result.parent, result.name) 526 self._mock_children[name] = result 527 return result 528 529 def __repr__(self): 530 _name_list = [self._mock_new_name] 531 _parent = self._mock_new_parent 532 last = self 533 dot = '.' 534 if _name_list == ['()']: 535 dot = '' 536 seen = set() 537 while _parent is not None: 538 last = _parent 539 _name_list.append(_parent._mock_new_name + dot) 540 dot = '.' 541 if _parent._mock_new_name == '()': 542 dot = '' 543 _parent = _parent._mock_new_parent 544 if id(_parent) in seen: 545 break 546 seen.add(id(_parent)) 547 548 _name_list = list(reversed(_name_list)) 549 _first = last._mock_name or 'mock' 550 if len(_name_list) > 1: 551 if _name_list[1] not in ('()', '().'): 552 _first += '.' 553 _name_list[0] = _first 554 name = ''.join(_name_list) 555 name_string = '' 556 if name not in ('mock', 'mock.'): 557 name_string = ' name=%r' % name 558 spec_string = '' 559 if self._spec_class is not None: 560 spec_string = ' spec=%r' 561 if self._spec_set: 562 spec_string = ' spec_set=%r' 563 spec_string = spec_string % self._spec_class.__name__ 564 return "<%s%s%s id='%s'>" % (type(self).__name__, 565 name_string, 566 spec_string, 567 id(self)) 568 569 def __dir__(self): 570 extras = self._mock_methods or [] 571 from_type = dir(type(self)) 572 from_dict = list(self.__dict__) 573 if FILTER_DIR: 574 from_type = [ e for e in from_type if not e.startswith('_') ] 575 from_dict = [ e for e in from_dict if not e.startswith('_') or _is_magic(e) ] 576 return sorted(set(extras + from_type + from_dict + list(self._mock_children))) 577 578 def __setattr__(self, name, value): 579 if name in _allowed_names: 580 return object.__setattr__(self, name, value) 581 if self._spec_set and self._mock_methods is not None and name not in self._mock_methods and name not in self.__dict__: 582 raise AttributeError("Mock object has no attribute '%s'" % name) 583 elif name in _unsupported_magics: 584 msg = 'Attempting to set unsupported magic method %r.' % name 585 raise AttributeError(msg) 586 elif name in _all_magics: 587 if self._mock_methods is not None and name not in self._mock_methods: 588 raise AttributeError("Mock object has no attribute '%s'" % name) 589 if not _is_instance_mock(value): 590 setattr(type(self), name, _get_method(name, value)) 591 original = value 592 value = lambda *args, **kw: original(self, *args, **kw) 593 else: 594 _check_and_set_parent(self, value, None, name) 595 setattr(type(self), name, value) 596 self._mock_children[name] = value 597 else: 598 if name == '__class__': 599 self._spec_class = value 600 return 601 if _check_and_set_parent(self, value, name, name): 602 self._mock_children[name] = value 603 return object.__setattr__(self, name, value) 604 605 def __delattr__(self, name): 606 if name in _all_magics and name in type(self).__dict__: 607 delattr(type(self), name) 608 if name not in self.__dict__: 609 return 610 if name in self.__dict__: 611 object.__delattr__(self, name) 612 obj = self._mock_children.get(name, _missing) 613 if obj is _deleted: 614 raise AttributeError(name) 615 if obj is not _missing: 616 del self._mock_children[name] 617 self._mock_children[name] = _deleted 618 619 def _format_mock_call_signature(self, args, kwargs): 620 name = self._mock_name or 'mock' 621 return _format_call_signature(name, args, kwargs) 622 623 def _format_mock_failure_message(self, args, kwargs): 624 message = 'Expected call: %s\nActual call: %s' 625 expected_string = self._format_mock_call_signature(args, kwargs) 626 call_args = self.call_args 627 if len(call_args) == 3: 628 call_args = call_args[1:] 629 actual_string = self._format_mock_call_signature(*call_args) 630 return message % (expected_string, actual_string) 631 632 def assert_called_with(_mock_self, *args, **kwargs): 633 self = _mock_self 634 if self.call_args is None: 635 expected = self._format_mock_call_signature(args, kwargs) 636 raise AssertionError('Expected call: %s\nNot called' % (expected,)) 637 if self.call_args != (args, kwargs): 638 msg = self._format_mock_failure_message(args, kwargs) 639 raise AssertionError(msg) 640 641 def assert_called_once_with(_mock_self, *args, **kwargs): 642 self = _mock_self 643 if not self.call_count == 1: 644 msg = 'Expected to be called once. Called %s times.' % self.call_count 645 raise AssertionError(msg) 646 return self.assert_called_with(*args, **kwargs) 647 648 def assert_not_called(_mock_self, *args, **kwargs): 649 self = _mock_self 650 if not self.call_count == 0: 651 msg = 'Expected to not be called. Called %s times.' % self.call_count 652 raise AssertionError(msg) 653 return True 654 655 def assert_has_calls(self, calls, any_order = False): 656 if not any_order: 657 if calls not in self.mock_calls: 658 raise AssertionError('Calls not found.\nExpected: %r\nActual: %r' % (calls, self.mock_calls)) 659 return 660 all_calls = list(self.mock_calls) 661 not_found = [] 662 for kall in calls: 663 try: 664 all_calls.remove(kall) 665 except ValueError: 666 not_found.append(kall) 667 668 if not_found: 669 raise AssertionError('%r not all found in call list' % (tuple(not_found),)) 670 671 def assert_any_call(self, *args, **kwargs): 672 kall = call(*args, **kwargs) 673 if kall not in self.call_args_list: 674 expected_string = self._format_mock_call_signature(args, kwargs) 675 raise AssertionError('%s call not found' % expected_string) 676 677 def _get_child_mock(self, **kw): 678 _type = type(self) 679 if not issubclass(_type, CallableMixin): 680 if issubclass(_type, NonCallableMagicMock): 681 klass = MagicMock 682 elif issubclass(_type, NonCallableMock): 683 klass = Mock 684 else: 685 klass = _type.__mro__[1] 686 return klass(**kw) 687 688 689 def _try_iter(obj): 690 if obj is None: 691 return obj 692 if _is_exception(obj): 693 return obj 694 if _callable(obj): 695 return obj 696 try: 697 return iter(obj) 698 except TypeError: 699 return obj 700 701 702 class CallableMixin(Base): 703 704 def __init__(self, spec = None, side_effect = None, return_value = DEFAULT, wraps = None, name = None, spec_set = None, parent = None, _spec_state = None, _new_name = '', _new_parent = None, **kwargs): 705 self.__dict__['_mock_return_value'] = return_value 706 _super(CallableMixin, self).__init__(spec, wraps, name, spec_set, parent, _spec_state, _new_name, _new_parent, **kwargs) 707 self.side_effect = side_effect 708 709 def _mock_check_sig(self, *args, **kwargs): 710 pass 711 712 def __call__(_mock_self, *args, **kwargs): 713 _mock_self._mock_check_sig(*args, **kwargs) 714 return _mock_self._mock_call(*args, **kwargs) 715 716 def _mock_call(_mock_self, *args, **kwargs): 717 self = _mock_self 718 self.called = True 719 self.call_count += 1 720 self.call_args = _Call((args, kwargs), two=True) 721 self.call_args_list.append(_Call((args, kwargs), two=True)) 722 _new_name = self._mock_new_name 723 _new_parent = self._mock_new_parent 724 self.mock_calls.append(_Call(('', args, kwargs))) 725 seen = set() 726 skip_next_dot = _new_name == '()' 727 do_method_calls = self._mock_parent is not None 728 name = self._mock_name 729 while _new_parent is not None: 730 this_mock_call = _Call((_new_name, args, kwargs)) 731 if _new_parent._mock_new_name: 732 dot = '.' 733 if skip_next_dot: 734 dot = '' 735 skip_next_dot = False 736 if _new_parent._mock_new_name == '()': 737 skip_next_dot = True 738 _new_name = _new_parent._mock_new_name + dot + _new_name 739 if do_method_calls: 740 if _new_name == name: 741 this_method_call = this_mock_call 742 else: 743 this_method_call = _Call((name, args, kwargs)) 744 _new_parent.method_calls.append(this_method_call) 745 do_method_calls = _new_parent._mock_parent is not None 746 if do_method_calls: 747 name = _new_parent._mock_name + '.' + name 748 _new_parent.mock_calls.append(this_mock_call) 749 _new_parent = _new_parent._mock_new_parent 750 _new_parent_id = id(_new_parent) 751 if _new_parent_id in seen: 752 break 753 seen.add(_new_parent_id) 754 755 ret_val = DEFAULT 756 effect = self.side_effect 757 if effect is not None: 758 if _is_exception(effect): 759 raise effect 760 if not _callable(effect): 761 result = next(effect) 762 if _is_exception(result): 763 raise result 764 return result 765 ret_val = effect(*args, **kwargs) 766 if ret_val is DEFAULT: 767 ret_val = self.return_value 768 if self._mock_wraps is not None and self._mock_return_value is DEFAULT: 769 return self._mock_wraps(*args, **kwargs) 770 if ret_val is DEFAULT: 771 ret_val = self.return_value 772 return ret_val 773 774 775 class Mock(CallableMixin, NonCallableMock): 776 pass 777 778 779 def _dot_lookup(thing, comp, import_path): 780 try: 781 return getattr(thing, comp) 782 except AttributeError: 783 __import__(import_path) 784 return getattr(thing, comp) 785 786 787 def _importer(target): 788 components = target.split('.') 789 import_path = components.pop(0) 790 thing = __import__(import_path) 791 for comp in components: 792 import_path += '.%s' % comp 793 thing = _dot_lookup(thing, comp, import_path) 794 795 return thing 796 797 798 def _is_started(patcher): 799 return hasattr(patcher, 'is_local') 800 801 802 class _patch(object): 803 attribute_name = None 804 _active_patches = set() 805 806 def __init__(self, getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs): 807 if new_callable is not None: 808 if new is not DEFAULT: 809 raise ValueError("Cannot use 'new' and 'new_callable' together") 810 if autospec is not None: 811 raise ValueError("Cannot use 'autospec' and 'new_callable' together") 812 self.getter = getter 813 self.attribute = attribute 814 self.new = new 815 self.new_callable = new_callable 816 self.spec = spec 817 self.create = create 818 self.has_local = False 819 self.spec_set = spec_set 820 self.autospec = autospec 821 self.kwargs = kwargs 822 self.additional_patchers = [] 823 824 def copy(self): 825 patcher = _patch(self.getter, self.attribute, self.new, self.spec, self.create, self.spec_set, self.autospec, self.new_callable, self.kwargs) 826 patcher.attribute_name = self.attribute_name 827 patcher.additional_patchers = [ p.copy() for p in self.additional_patchers ] 828 return patcher 829 830 def __call__(self, func): 831 if isinstance(func, ClassTypes): 832 return self.decorate_class(func) 833 return self.decorate_callable(func) 834 835 def decorate_class(self, klass): 836 for attr in dir(klass): 837 if not attr.startswith(patch.TEST_PREFIX): 838 continue 839 attr_value = getattr(klass, attr) 840 if not hasattr(attr_value, '__call__'): 841 continue 842 patcher = self.copy() 843 setattr(klass, attr, patcher(attr_value)) 844 845 return klass 846 847 def decorate_callable(self, func): 848 if hasattr(func, 'patchings'): 849 func.patchings.append(self) 850 return func 851 852 @wraps(func) 853 def patched(*args, **keywargs): 854 extra_args = [] 855 entered_patchers = [] 856 exc_info = tuple() 857 try: 858 for patching in patched.patchings: 859 arg = patching.__enter__() 860 entered_patchers.append(patching) 861 if patching.attribute_name is not None: 862 keywargs.update(arg) 863 elif patching.new is DEFAULT: 864 extra_args.append(arg) 865 866 args += tuple(extra_args) 867 return func(*args, **keywargs) 868 except: 869 if patching not in entered_patchers and _is_started(patching): 870 entered_patchers.append(patching) 871 exc_info = sys.exc_info() 872 raise 873 finally: 874 for patching in reversed(entered_patchers): 875 patching.__exit__(*exc_info) 876 877 patched.patchings = [self] 878 if hasattr(func, 'func_code'): 879 patched.compat_co_firstlineno = getattr(func, 'compat_co_firstlineno', func.func_code.co_firstlineno) 880 return patched 881 882 def get_original(self): 883 target = self.getter() 884 name = self.attribute 885 original = DEFAULT 886 local = False 887 try: 888 original = target.__dict__[name] 889 except (AttributeError, KeyError): 890 original = getattr(target, name, DEFAULT) 891 else: 892 local = True 893 894 if not self.create and original is DEFAULT: 895 raise AttributeError('%s does not have the attribute %r' % (target, name)) 896 return (original, local) 897 898 def __enter__(self): 899 new, spec, spec_set = self.new, self.spec, self.spec_set 900 autospec, kwargs = self.autospec, self.kwargs 901 new_callable = self.new_callable 902 self.target = self.getter() 903 if spec is False: 904 spec = None 905 if spec_set is False: 906 spec_set = None 907 if autospec is False: 908 autospec = None 909 if spec is not None and autospec is not None: 910 raise TypeError("Can't specify spec and autospec") 911 if (spec is not None or autospec is not None) and spec_set not in (True, None): 912 raise TypeError("Can't provide explicit spec_set *and* spec or autospec") 913 original, local = self.get_original() 914 if new is DEFAULT and autospec is None: 915 inherit = False 916 if spec is True: 917 spec = original 918 if spec_set is True: 919 spec_set = original 920 spec = None 921 elif spec is not None: 922 if spec_set is True: 923 spec_set = spec 924 spec = None 925 elif spec_set is True: 926 spec_set = original 927 if spec is not None or spec_set is not None: 928 if original is DEFAULT: 929 raise TypeError("Can't use 'spec' with create=True") 930 if isinstance(original, ClassTypes): 931 inherit = True 932 Klass = MagicMock 933 _kwargs = {} 934 if new_callable is not None: 935 Klass = new_callable 936 elif spec is not None or spec_set is not None: 937 this_spec = spec 938 if spec_set is not None: 939 this_spec = spec_set 940 if _is_list(this_spec): 941 not_callable = '__call__' not in this_spec 942 else: 943 not_callable = not _callable(this_spec) 944 if not_callable: 945 Klass = NonCallableMagicMock 946 if spec is not None: 947 _kwargs['spec'] = spec 948 if spec_set is not None: 949 _kwargs['spec_set'] = spec_set 950 if isinstance(Klass, type) and issubclass(Klass, NonCallableMock) and self.attribute: 951 _kwargs['name'] = self.attribute 952 _kwargs.update(kwargs) 953 new = Klass(**_kwargs) 954 if inherit and _is_instance_mock(new): 955 this_spec = spec 956 if spec_set is not None: 957 this_spec = spec_set 958 if not _is_list(this_spec) and not _instance_callable(this_spec): 959 Klass = NonCallableMagicMock 960 _kwargs.pop('name') 961 new.return_value = Klass(_new_parent=new, _new_name='()', **_kwargs) 962 elif autospec is not None: 963 if new is not DEFAULT: 964 raise TypeError("autospec creates the mock for you. Can't specify autospec and new.") 965 if original is DEFAULT: 966 raise TypeError("Can't use 'autospec' with create=True") 967 spec_set = bool(spec_set) 968 if autospec is True: 969 autospec = original 970 new = create_autospec(autospec, spec_set=spec_set, _name=self.attribute, **kwargs) 971 elif kwargs: 972 raise TypeError("Can't pass kwargs to a mock we aren't creating") 973 new_attr = new 974 self.temp_original = original 975 self.is_local = local 976 setattr(self.target, self.attribute, new_attr) 977 if self.attribute_name is not None: 978 extra_args = {} 979 if self.new is DEFAULT: 980 extra_args[self.attribute_name] = new 981 for patching in self.additional_patchers: 982 arg = patching.__enter__() 983 if patching.new is DEFAULT: 984 extra_args.update(arg) 985 986 return extra_args 987 return new 988 989 def __exit__(self, *exc_info): 990 if not _is_started(self): 991 raise RuntimeError('stop called on unstarted patcher') 992 if self.is_local and self.temp_original is not DEFAULT: 993 setattr(self.target, self.attribute, self.temp_original) 994 else: 995 delattr(self.target, self.attribute) 996 if not self.create and not hasattr(self.target, self.attribute): 997 setattr(self.target, self.attribute, self.temp_original) 998 del self.temp_original 999 del self.is_local 1000 del self.target 1001 for patcher in reversed(self.additional_patchers): 1002 if _is_started(patcher): 1003 patcher.__exit__(*exc_info) 1004 1005 def start(self): 1006 result = self.__enter__() 1007 self._active_patches.add(self) 1008 return result 1009 1010 def stop(self): 1011 self._active_patches.discard(self) 1012 return self.__exit__() 1013 1014 1015 def _get_target(target): 1016 try: 1017 target, attribute = target.rsplit('.', 1) 1018 except (TypeError, ValueError): 1019 raise TypeError('Need a valid target to patch. You supplied: %r' % (target,)) 1020 1021 getter = lambda : _importer(target) 1022 return (getter, attribute) 1023 1024 1025 def _patch_object(target, attribute, new = DEFAULT, spec = None, create = False, spec_set = None, autospec = None, new_callable = None, **kwargs): 1026 getter = lambda : target 1027 return _patch(getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs) 1028 1029 1030 def _patch_multiple(target, spec = None, create = False, spec_set = None, autospec = None, new_callable = None, **kwargs): 1031 if type(target) in (unicode, str): 1032 getter = lambda : _importer(target) 1033 else: 1034 getter = lambda : target 1035 if not kwargs: 1036 raise ValueError('Must supply at least one keyword argument with patch.multiple') 1037 items = list(kwargs.items()) 1038 attribute, new = items[0] 1039 patcher = _patch(getter, attribute, new, spec, create, spec_set, autospec, new_callable, {}) 1040 patcher.attribute_name = attribute 1041 for attribute, new in items[1:]: 1042 this_patcher = _patch(getter, attribute, new, spec, create, spec_set, autospec, new_callable, {}) 1043 this_patcher.attribute_name = attribute 1044 patcher.additional_patchers.append(this_patcher) 1045 1046 return patcher 1047 1048 1049 def patch(target, new = DEFAULT, spec = None, create = False, spec_set = None, autospec = None, new_callable = None, **kwargs): 1050 getter, attribute = _get_target(target) 1051 return _patch(getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs) 1052 1053 1054 class _patch_dict(object): 1055 1056 def __init__(self, in_dict, values = (), clear = False, **kwargs): 1057 if isinstance(in_dict, basestring): 1058 in_dict = _importer(in_dict) 1059 self.in_dict = in_dict 1060 self.values = dict(values) 1061 self.values.update(kwargs) 1062 self.clear = clear 1063 self._original = None 1064 1065 def __call__(self, f): 1066 if isinstance(f, ClassTypes): 1067 return self.decorate_class(f) 1068 1069 @wraps(f) 1070 def _inner(*args, **kw): 1071 self._patch_dict() 1072 try: 1073 return f(*args, **kw) 1074 finally: 1075 self._unpatch_dict() 1076 1077 return _inner 1078 1079 def decorate_class(self, klass): 1080 for attr in dir(klass): 1081 attr_value = getattr(klass, attr) 1082 if attr.startswith(patch.TEST_PREFIX) and hasattr(attr_value, '__call__'): 1083 decorator = _patch_dict(self.in_dict, self.values, self.clear) 1084 decorated = decorator(attr_value) 1085 setattr(klass, attr, decorated) 1086 1087 return klass 1088 1089 def __enter__(self): 1090 self._patch_dict() 1091 1092 def _patch_dict(self): 1093 values = self.values 1094 in_dict = self.in_dict 1095 clear = self.clear 1096 try: 1097 original = in_dict.copy() 1098 except AttributeError: 1099 original = {} 1100 for key in in_dict: 1101 original[key] = in_dict[key] 1102 1103 self._original = original 1104 if clear: 1105 _clear_dict(in_dict) 1106 try: 1107 in_dict.update(values) 1108 except AttributeError: 1109 for key in values: 1110 in_dict[key] = values[key] 1111 1112 def _unpatch_dict(self): 1113 in_dict = self.in_dict 1114 original = self._original 1115 _clear_dict(in_dict) 1116 try: 1117 in_dict.update(original) 1118 except AttributeError: 1119 for key in original: 1120 in_dict[key] = original[key] 1121 1122 def __exit__(self, *args): 1123 self._unpatch_dict() 1124 return False 1125 1126 start = __enter__ 1127 stop = __exit__ 1128 1129 1130 def _clear_dict(in_dict): 1131 try: 1132 in_dict.clear() 1133 except AttributeError: 1134 keys = list(in_dict) 1135 for key in keys: 1136 del in_dict[key] 1137 1138 1139 def _patch_stopall(): 1140 for patch in list(_patch._active_patches): 1141 patch.stop() 1142 1143 1144 patch.object = _patch_object 1145 patch.dict = _patch_dict 1146 patch.multiple = _patch_multiple 1147 patch.stopall = _patch_stopall 1148 patch.TEST_PREFIX = 'test' 1149 magic_methods = 'lt le gt ge eq ne getitem setitem delitem len contains iter hash str sizeof enter exit divmod neg pos abs invert complex int float index trunc floor ceil ' 1150 numerics = 'add sub mul div floordiv mod lshift rshift and xor or pow ' 1151 inplace = ' '.join(('i%s' % n for n in numerics.split())) 1152 right = ' '.join(('r%s' % n for n in numerics.split())) 1153 extra = '' 1154 if inPy3k: 1155 extra = 'bool next ' 1156 else: 1157 extra = 'unicode long nonzero oct hex truediv rtruediv ' 1158 _non_defaults = set(('__%s__' % method for method in ['cmp', 1159 'getslice', 1160 'setslice', 1161 'coerce', 1162 'subclasses', 1163 'format', 1164 'get', 1165 'set', 1166 'delete', 1167 'reversed', 1168 'missing', 1169 'reduce', 1170 'reduce_ex', 1171 'getinitargs', 1172 'getnewargs', 1173 'getstate', 1174 'setstate', 1175 'getformat', 1176 'setformat', 1177 'repr', 1178 'dir'])) 1179 1180 def _get_method(name, func): 1181 1182 def method(self, *args, **kw): 1183 return func(self, *args, **kw) 1184 1185 method.__name__ = name 1186 return method 1187 1188 1189 _magics = set(('__%s__' % method for method in ' '.join([magic_methods, 1190 numerics, 1191 inplace, 1192 right, 1193 extra]).split())) 1194 _all_magics = _magics | _non_defaults 1195 _unsupported_magics = set(['__getattr__', 1196 '__setattr__', 1197 '__init__', 1198 '__new__', 1199 '__prepare____instancecheck__', 1200 '__subclasscheck__', 1201 '__del__']) 1202 _calculate_return_value = {'__hash__': lambda self: object.__hash__(self), 1203 '__str__': lambda self: object.__str__(self), 1204 '__sizeof__': lambda self: object.__sizeof__(self), 1205 '__unicode__': lambda self: unicode(object.__str__(self))} 1206 _return_values = {'__lt__': NotImplemented, 1207 '__gt__': NotImplemented, 1208 '__le__': NotImplemented, 1209 '__ge__': NotImplemented, 1210 '__int__': 1, 1211 '__contains__': False, 1212 '__len__': 0, 1213 '__exit__': False, 1214 '__complex__': 1j, 1215 '__float__': 1.0, 1216 '__bool__': True, 1217 '__nonzero__': True, 1218 '__oct__': '1', 1219 '__hex__': '0x1', 1220 '__long__': long(1), 1221 '__index__': 1} 1222 1223 def _get_eq(self): 1224 1225 def __eq__(other): 1226 ret_val = self.__eq__._mock_return_value 1227 if ret_val is not DEFAULT: 1228 return ret_val 1229 return self is other 1230 1231 return __eq__ 1232 1233 1234 def _get_ne(self): 1235 1236 def __ne__(other): 1237 if self.__ne__._mock_return_value is not DEFAULT: 1238 return DEFAULT 1239 return self is not other 1240 1241 return __ne__ 1242 1243 1244 def _get_iter(self): 1245 1246 def __iter__(): 1247 ret_val = self.__iter__._mock_return_value 1248 if ret_val is DEFAULT: 1249 return iter([]) 1250 return iter(ret_val) 1251 1252 return __iter__ 1253 1254 1255 _side_effect_methods = {'__eq__': _get_eq, 1256 '__ne__': _get_ne, 1257 '__iter__': _get_iter} 1258 1259 def _set_return_value(mock, method, name): 1260 fixed = _return_values.get(name, DEFAULT) 1261 if fixed is not DEFAULT: 1262 method.return_value = fixed 1263 return 1264 return_calulator = _calculate_return_value.get(name) 1265 if return_calulator is not None: 1266 try: 1267 return_value = return_calulator(mock) 1268 except AttributeError: 1269 return_value = AttributeError(name) 1270 1271 method.return_value = return_value 1272 return 1273 side_effector = _side_effect_methods.get(name) 1274 if side_effector is not None: 1275 method.side_effect = side_effector(mock) 1276 1277 1278 class MagicMixin(object): 1279 1280 def __init__(self, *args, **kw): 1281 _super(MagicMixin, self).__init__(*args, **kw) 1282 self._mock_set_magics() 1283 1284 def _mock_set_magics(self): 1285 these_magics = _magics 1286 if self._mock_methods is not None: 1287 these_magics = _magics.intersection(self._mock_methods) 1288 remove_magics = set() 1289 remove_magics = _magics - these_magics 1290 for entry in remove_magics: 1291 if entry in type(self).__dict__: 1292 delattr(self, entry) 1293 1294 these_magics = these_magics - set(type(self).__dict__) 1295 _type = type(self) 1296 for entry in these_magics: 1297 setattr(_type, entry, MagicProxy(entry, self)) 1298 1299 1300 class NonCallableMagicMock(MagicMixin, NonCallableMock): 1301 1302 def mock_add_spec(self, spec, spec_set = False): 1303 self._mock_add_spec(spec, spec_set) 1304 self._mock_set_magics() 1305 1306 1307 class MagicMock(MagicMixin, Mock): 1308 1309 def mock_add_spec(self, spec, spec_set = False): 1310 self._mock_add_spec(spec, spec_set) 1311 self._mock_set_magics() 1312 1313 1314 class MagicProxy(object): 1315 1316 def __init__(self, name, parent): 1317 self.name = name 1318 self.parent = parent 1319 1320 def __call__(self, *args, **kwargs): 1321 m = self.create_mock() 1322 return m(*args, **kwargs) 1323 1324 def create_mock(self): 1325 entry = self.name 1326 parent = self.parent 1327 m = parent._get_child_mock(name=entry, _new_name=entry, _new_parent=parent) 1328 setattr(parent, entry, m) 1329 _set_return_value(parent, m, entry) 1330 return m 1331 1332 def __get__(self, obj, _type = None): 1333 return self.create_mock() 1334 1335 1336 class _ANY(object): 1337 1338 def __eq__(self, other): 1339 return True 1340 1341 def __ne__(self, other): 1342 return False 1343 1344 def __repr__(self): 1345 return '<ANY>' 1346 1347 1348 ANY = _ANY() 1349 1350 def _format_call_signature(name, args, kwargs): 1351 message = '%s(%%s)' % name 1352 formatted_args = '' 1353 args_string = ', '.join([ repr(arg) for arg in args ]) 1354 kwargs_string = ', '.join([ '%s=%r' % (key, value) for key, value in kwargs.items() ]) 1355 if args_string: 1356 formatted_args = args_string 1357 if kwargs_string: 1358 if formatted_args: 1359 formatted_args += ', ' 1360 formatted_args += kwargs_string 1361 return message % formatted_args 1362 1363 1364 class _Call(tuple): 1365 1366 def __new__(cls, value = (), name = None, parent = None, two = False, from_kall = True): 1367 name = '' 1368 args = () 1369 kwargs = {} 1370 _len = len(value) 1371 if _len == 3: 1372 name, args, kwargs = value 1373 elif _len == 2: 1374 first, second = value 1375 if isinstance(first, basestring): 1376 name = first 1377 if isinstance(second, tuple): 1378 args = second 1379 else: 1380 kwargs = second 1381 else: 1382 args, kwargs = first, second 1383 elif _len == 1: 1384 value, = value 1385 if isinstance(value, basestring): 1386 name = value 1387 elif isinstance(value, tuple): 1388 args = value 1389 else: 1390 kwargs = value 1391 if two: 1392 return tuple.__new__(cls, (args, kwargs)) 1393 return tuple.__new__(cls, (name, args, kwargs)) 1394 1395 def __init__(self, value = (), name = None, parent = None, two = False, from_kall = True): 1396 self.name = name 1397 self.parent = parent 1398 self.from_kall = from_kall 1399 1400 def __eq__(self, other): 1401 if other is ANY: 1402 return True 1403 try: 1404 len_other = len(other) 1405 except TypeError: 1406 return False 1407 1408 self_name = '' 1409 if len(self) == 2: 1410 self_args, self_kwargs = self 1411 else: 1412 self_name, self_args, self_kwargs = self 1413 other_name = '' 1414 if len_other == 0: 1415 other_args, other_kwargs = (), {} 1416 elif len_other == 3: 1417 other_name, other_args, other_kwargs = other 1418 elif len_other == 1: 1419 value, = other 1420 if isinstance(value, tuple): 1421 other_args = value 1422 other_kwargs = {} 1423 elif isinstance(value, basestring): 1424 other_name = value 1425 other_args, other_kwargs = (), {} 1426 else: 1427 other_args = () 1428 other_kwargs = value 1429 else: 1430 first, second = other 1431 if isinstance(first, basestring): 1432 other_name = first 1433 if isinstance(second, tuple): 1434 other_args, other_kwargs = second, {} 1435 else: 1436 other_args, other_kwargs = (), second 1437 else: 1438 other_args, other_kwargs = first, second 1439 if self_name and other_name != self_name: 1440 return False 1441 return (other_args, other_kwargs) == (self_args, self_kwargs) 1442 1443 def __ne__(self, other): 1444 return not self.__eq__(other) 1445 1446 def __call__(self, *args, **kwargs): 1447 if self.name is None: 1448 return _Call(('', args, kwargs), name='()') 1449 name = self.name + '()' 1450 return _Call((self.name, args, kwargs), name=name, parent=self) 1451 1452 def __getattr__(self, attr): 1453 if self.name is None: 1454 return _Call(name=attr, from_kall=False) 1455 name = '%s.%s' % (self.name, attr) 1456 return _Call(name=name, parent=self, from_kall=False) 1457 1458 def __repr__(self): 1459 if not self.from_kall: 1460 name = self.name or 'call' 1461 if name.startswith('()'): 1462 name = 'call%s' % name 1463 return name 1464 if len(self) == 2: 1465 name = 'call' 1466 args, kwargs = self 1467 else: 1468 name, args, kwargs = self 1469 if not name: 1470 name = 'call' 1471 elif not name.startswith('()'): 1472 name = 'call.%s' % name 1473 else: 1474 name = 'call%s' % name 1475 return _format_call_signature(name, args, kwargs) 1476 1477 def call_list(self): 1478 vals = [] 1479 thing = self 1480 while thing is not None: 1481 if thing.from_kall: 1482 vals.append(thing) 1483 thing = thing.parent 1484 1485 return _CallList(reversed(vals)) 1486 1487 1488 call = _Call(from_kall=False) 1489 1490 def create_autospec(spec, spec_set = False, instance = False, _parent = None, _name = None, **kwargs): 1491 if _is_list(spec): 1492 spec = type(spec) 1493 is_type = isinstance(spec, ClassTypes) 1494 _kwargs = {'spec': spec} 1495 if spec_set: 1496 _kwargs = {'spec_set': spec} 1497 elif spec is None: 1498 _kwargs = {} 1499 _kwargs.update(kwargs) 1500 Klass = MagicMock 1501 if type(spec) in DescriptorTypes: 1502 _kwargs = {} 1503 elif not _callable(spec): 1504 Klass = NonCallableMagicMock 1505 elif is_type and instance and not _instance_callable(spec): 1506 Klass = NonCallableMagicMock 1507 _new_name = _name 1508 if _parent is None: 1509 _new_name = '' 1510 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name, name=_name, **_kwargs) 1511 if isinstance(spec, FunctionTypes): 1512 mock = _set_signature(mock, spec) 1513 else: 1514 _check_signature(spec, mock, is_type, instance) 1515 if _parent is not None and not instance: 1516 _parent._mock_children[_name] = mock 1517 if is_type and not instance and 'return_value' not in kwargs: 1518 mock.return_value = create_autospec(spec, spec_set, instance=True, _name='()', _parent=mock) 1519 for entry in dir(spec): 1520 if _is_magic(entry): 1521 continue 1522 if isinstance(spec, FunctionTypes) and entry in FunctionAttributes: 1523 continue 1524 try: 1525 original = getattr(spec, entry) 1526 except AttributeError: 1527 continue 1528 1529 kwargs = {'spec': original} 1530 if spec_set: 1531 kwargs = {'spec_set': original} 1532 if not isinstance(original, FunctionTypes): 1533 new = _SpecState(original, spec_set, mock, entry, instance) 1534 mock._mock_children[entry] = new 1535 else: 1536 parent = mock 1537 if isinstance(spec, FunctionTypes): 1538 parent = mock.mock 1539 new = MagicMock(parent=parent, name=entry, _new_name=entry, _new_parent=parent, **kwargs) 1540 mock._mock_children[entry] = new 1541 skipfirst = _must_skip(spec, entry, is_type) 1542 _check_signature(original, new, skipfirst=skipfirst) 1543 if isinstance(new, FunctionTypes): 1544 setattr(mock, entry, new) 1545 1546 return mock 1547 1548 1549 def _must_skip(spec, entry, is_type): 1550 if not isinstance(spec, ClassTypes): 1551 if entry in getattr(spec, '__dict__', {}): 1552 return False 1553 spec = spec.__class__ 1554 if not hasattr(spec, '__mro__'): 1555 return is_type 1556 for klass in spec.__mro__: 1557 result = klass.__dict__.get(entry, DEFAULT) 1558 if result is DEFAULT: 1559 continue 1560 if isinstance(result, (staticmethod, classmethod)): 1561 return False 1562 return is_type 1563 1564 return is_type 1565 1566 1567 def _get_class(obj): 1568 try: 1569 return obj.__class__ 1570 except AttributeError: 1571 return type(obj) 1572 1573 1574 class _SpecState(object): 1575 1576 def __init__(self, spec, spec_set = False, parent = None, name = None, ids = None, instance = False): 1577 self.spec = spec 1578 self.ids = ids 1579 self.spec_set = spec_set 1580 self.parent = parent 1581 self.instance = instance 1582 self.name = name 1583 1584 1585 FunctionTypes = (type(create_autospec), type(ANY.__eq__), type(_ANY.__eq__)) 1586 FunctionAttributes = set(['func_closure', 1587 'func_code', 1588 'func_defaults', 1589 'func_dict', 1590 'func_doc', 1591 'func_globals', 1592 'func_name']) 1593 file_spec = None 1594 1595 def mock_open(mock = None, read_data = ''): 1596 global file_spec 1597 if file_spec is None: 1598 if inPy3k: 1599 import _io 1600 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO)))) 1601 else: 1602 file_spec = file 1603 if mock is None: 1604 mock = MagicMock(name='open', spec=open) 1605 handle = MagicMock(spec=file_spec) 1606 handle.write.return_value = None 1607 handle.__enter__.return_value = handle 1608 handle.read.return_value = read_data 1609 mock.return_value = handle 1610 return mock 1611 1612 1613 class PropertyMock(Mock): 1614 1615 def _get_child_mock(self, **kwargs): 1616 return MagicMock(**kwargs) 1617 1618 def __get__(self, obj, obj_type): 1619 return self() 1620 1621 def __set__(self, obj, val): 1622 self(val)