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