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