1# Copyright (C) 2007-2012 Michael Foord & the mock team 2# E-mail: fuzzyman AT voidspace DOT org DOT uk 3# http://www.voidspace.org.uk/python/mock/ 4 5import os 6import sys 7from collections import OrderedDict 8 9import unittest 10from unittest.test.testmock import support 11from unittest.test.testmock.support import SomeClass, is_instance 12 13from test.test_importlib.util import uncache 14from unittest.mock import ( 15 NonCallableMock, CallableMixin, sentinel, 16 MagicMock, Mock, NonCallableMagicMock, patch, _patch, 17 DEFAULT, call, _get_target 18) 19 20 21builtin_string = 'builtins' 22 23PTModule = sys.modules[__name__] 24MODNAME = '%s.PTModule' % __name__ 25 26 27def _get_proxy(obj, get_only=True): 28 class Proxy(object): 29 def __getattr__(self, name): 30 return getattr(obj, name) 31 if not get_only: 32 def __setattr__(self, name, value): 33 setattr(obj, name, value) 34 def __delattr__(self, name): 35 delattr(obj, name) 36 Proxy.__setattr__ = __setattr__ 37 Proxy.__delattr__ = __delattr__ 38 return Proxy() 39 40 41# for use in the test 42something = sentinel.Something 43something_else = sentinel.SomethingElse 44 45 46class Foo(object): 47 def __init__(self, a): pass 48 def f(self, a): pass 49 def g(self): pass 50 foo = 'bar' 51 52 @staticmethod 53 def static_method(): pass 54 55 @classmethod 56 def class_method(cls): pass 57 58 class Bar(object): 59 def a(self): pass 60 61foo_name = '%s.Foo' % __name__ 62 63 64def function(a, b=Foo): pass 65 66 67class Container(object): 68 def __init__(self): 69 self.values = {} 70 71 def __getitem__(self, name): 72 return self.values[name] 73 74 def __setitem__(self, name, value): 75 self.values[name] = value 76 77 def __delitem__(self, name): 78 del self.values[name] 79 80 def __iter__(self): 81 return iter(self.values) 82 83 84 85class PatchTest(unittest.TestCase): 86 87 def assertNotCallable(self, obj, magic=True): 88 MockClass = NonCallableMagicMock 89 if not magic: 90 MockClass = NonCallableMock 91 92 self.assertRaises(TypeError, obj) 93 self.assertTrue(is_instance(obj, MockClass)) 94 self.assertFalse(is_instance(obj, CallableMixin)) 95 96 97 def test_single_patchobject(self): 98 class Something(object): 99 attribute = sentinel.Original 100 101 @patch.object(Something, 'attribute', sentinel.Patched) 102 def test(): 103 self.assertEqual(Something.attribute, sentinel.Patched, "unpatched") 104 105 test() 106 self.assertEqual(Something.attribute, sentinel.Original, 107 "patch not restored") 108 109 def test_patchobject_with_string_as_target(self): 110 msg = "'Something' must be the actual object to be patched, not a str" 111 with self.assertRaisesRegex(TypeError, msg): 112 patch.object('Something', 'do_something') 113 114 def test_patchobject_with_none(self): 115 class Something(object): 116 attribute = sentinel.Original 117 118 @patch.object(Something, 'attribute', None) 119 def test(): 120 self.assertIsNone(Something.attribute, "unpatched") 121 122 test() 123 self.assertEqual(Something.attribute, sentinel.Original, 124 "patch not restored") 125 126 127 def test_multiple_patchobject(self): 128 class Something(object): 129 attribute = sentinel.Original 130 next_attribute = sentinel.Original2 131 132 @patch.object(Something, 'attribute', sentinel.Patched) 133 @patch.object(Something, 'next_attribute', sentinel.Patched2) 134 def test(): 135 self.assertEqual(Something.attribute, sentinel.Patched, 136 "unpatched") 137 self.assertEqual(Something.next_attribute, sentinel.Patched2, 138 "unpatched") 139 140 test() 141 self.assertEqual(Something.attribute, sentinel.Original, 142 "patch not restored") 143 self.assertEqual(Something.next_attribute, sentinel.Original2, 144 "patch not restored") 145 146 147 def test_object_lookup_is_quite_lazy(self): 148 global something 149 original = something 150 @patch('%s.something' % __name__, sentinel.Something2) 151 def test(): 152 pass 153 154 try: 155 something = sentinel.replacement_value 156 test() 157 self.assertEqual(something, sentinel.replacement_value) 158 finally: 159 something = original 160 161 162 def test_patch(self): 163 @patch('%s.something' % __name__, sentinel.Something2) 164 def test(): 165 self.assertEqual(PTModule.something, sentinel.Something2, 166 "unpatched") 167 168 test() 169 self.assertEqual(PTModule.something, sentinel.Something, 170 "patch not restored") 171 172 @patch('%s.something' % __name__, sentinel.Something2) 173 @patch('%s.something_else' % __name__, sentinel.SomethingElse) 174 def test(): 175 self.assertEqual(PTModule.something, sentinel.Something2, 176 "unpatched") 177 self.assertEqual(PTModule.something_else, sentinel.SomethingElse, 178 "unpatched") 179 180 self.assertEqual(PTModule.something, sentinel.Something, 181 "patch not restored") 182 self.assertEqual(PTModule.something_else, sentinel.SomethingElse, 183 "patch not restored") 184 185 # Test the patching and restoring works a second time 186 test() 187 188 self.assertEqual(PTModule.something, sentinel.Something, 189 "patch not restored") 190 self.assertEqual(PTModule.something_else, sentinel.SomethingElse, 191 "patch not restored") 192 193 mock = Mock() 194 mock.return_value = sentinel.Handle 195 @patch('%s.open' % builtin_string, mock) 196 def test(): 197 self.assertEqual(open('filename', 'r'), sentinel.Handle, 198 "open not patched") 199 test() 200 test() 201 202 self.assertNotEqual(open, mock, "patch not restored") 203 204 205 def test_patch_class_attribute(self): 206 @patch('%s.SomeClass.class_attribute' % __name__, 207 sentinel.ClassAttribute) 208 def test(): 209 self.assertEqual(PTModule.SomeClass.class_attribute, 210 sentinel.ClassAttribute, "unpatched") 211 test() 212 213 self.assertIsNone(PTModule.SomeClass.class_attribute, 214 "patch not restored") 215 216 217 def test_patchobject_with_default_mock(self): 218 class Test(object): 219 something = sentinel.Original 220 something2 = sentinel.Original2 221 222 @patch.object(Test, 'something') 223 def test(mock): 224 self.assertEqual(mock, Test.something, 225 "Mock not passed into test function") 226 self.assertIsInstance(mock, MagicMock, 227 "patch with two arguments did not create a mock") 228 229 test() 230 231 @patch.object(Test, 'something') 232 @patch.object(Test, 'something2') 233 def test(this1, this2, mock1, mock2): 234 self.assertEqual(this1, sentinel.this1, 235 "Patched function didn't receive initial argument") 236 self.assertEqual(this2, sentinel.this2, 237 "Patched function didn't receive second argument") 238 self.assertEqual(mock1, Test.something2, 239 "Mock not passed into test function") 240 self.assertEqual(mock2, Test.something, 241 "Second Mock not passed into test function") 242 self.assertIsInstance(mock2, MagicMock, 243 "patch with two arguments did not create a mock") 244 self.assertIsInstance(mock2, MagicMock, 245 "patch with two arguments did not create a mock") 246 247 # A hack to test that new mocks are passed the second time 248 self.assertNotEqual(outerMock1, mock1, "unexpected value for mock1") 249 self.assertNotEqual(outerMock2, mock2, "unexpected value for mock1") 250 return mock1, mock2 251 252 outerMock1 = outerMock2 = None 253 outerMock1, outerMock2 = test(sentinel.this1, sentinel.this2) 254 255 # Test that executing a second time creates new mocks 256 test(sentinel.this1, sentinel.this2) 257 258 259 def test_patch_with_spec(self): 260 @patch('%s.SomeClass' % __name__, spec=SomeClass) 261 def test(MockSomeClass): 262 self.assertEqual(SomeClass, MockSomeClass) 263 self.assertTrue(is_instance(SomeClass.wibble, MagicMock)) 264 self.assertRaises(AttributeError, lambda: SomeClass.not_wibble) 265 266 test() 267 268 269 def test_patchobject_with_spec(self): 270 @patch.object(SomeClass, 'class_attribute', spec=SomeClass) 271 def test(MockAttribute): 272 self.assertEqual(SomeClass.class_attribute, MockAttribute) 273 self.assertTrue(is_instance(SomeClass.class_attribute.wibble, 274 MagicMock)) 275 self.assertRaises(AttributeError, 276 lambda: SomeClass.class_attribute.not_wibble) 277 278 test() 279 280 281 def test_patch_with_spec_as_list(self): 282 @patch('%s.SomeClass' % __name__, spec=['wibble']) 283 def test(MockSomeClass): 284 self.assertEqual(SomeClass, MockSomeClass) 285 self.assertTrue(is_instance(SomeClass.wibble, MagicMock)) 286 self.assertRaises(AttributeError, lambda: SomeClass.not_wibble) 287 288 test() 289 290 291 def test_patchobject_with_spec_as_list(self): 292 @patch.object(SomeClass, 'class_attribute', spec=['wibble']) 293 def test(MockAttribute): 294 self.assertEqual(SomeClass.class_attribute, MockAttribute) 295 self.assertTrue(is_instance(SomeClass.class_attribute.wibble, 296 MagicMock)) 297 self.assertRaises(AttributeError, 298 lambda: SomeClass.class_attribute.not_wibble) 299 300 test() 301 302 303 def test_nested_patch_with_spec_as_list(self): 304 # regression test for nested decorators 305 @patch('%s.open' % builtin_string) 306 @patch('%s.SomeClass' % __name__, spec=['wibble']) 307 def test(MockSomeClass, MockOpen): 308 self.assertEqual(SomeClass, MockSomeClass) 309 self.assertTrue(is_instance(SomeClass.wibble, MagicMock)) 310 self.assertRaises(AttributeError, lambda: SomeClass.not_wibble) 311 test() 312 313 314 def test_patch_with_spec_as_boolean(self): 315 @patch('%s.SomeClass' % __name__, spec=True) 316 def test(MockSomeClass): 317 self.assertEqual(SomeClass, MockSomeClass) 318 # Should not raise attribute error 319 MockSomeClass.wibble 320 321 self.assertRaises(AttributeError, lambda: MockSomeClass.not_wibble) 322 323 test() 324 325 326 def test_patch_object_with_spec_as_boolean(self): 327 @patch.object(PTModule, 'SomeClass', spec=True) 328 def test(MockSomeClass): 329 self.assertEqual(SomeClass, MockSomeClass) 330 # Should not raise attribute error 331 MockSomeClass.wibble 332 333 self.assertRaises(AttributeError, lambda: MockSomeClass.not_wibble) 334 335 test() 336 337 338 def test_patch_class_acts_with_spec_is_inherited(self): 339 @patch('%s.SomeClass' % __name__, spec=True) 340 def test(MockSomeClass): 341 self.assertTrue(is_instance(MockSomeClass, MagicMock)) 342 instance = MockSomeClass() 343 self.assertNotCallable(instance) 344 # Should not raise attribute error 345 instance.wibble 346 347 self.assertRaises(AttributeError, lambda: instance.not_wibble) 348 349 test() 350 351 352 def test_patch_with_create_mocks_non_existent_attributes(self): 353 @patch('%s.frooble' % builtin_string, sentinel.Frooble, create=True) 354 def test(): 355 self.assertEqual(frooble, sentinel.Frooble) 356 357 test() 358 self.assertRaises(NameError, lambda: frooble) 359 360 361 def test_patchobject_with_create_mocks_non_existent_attributes(self): 362 @patch.object(SomeClass, 'frooble', sentinel.Frooble, create=True) 363 def test(): 364 self.assertEqual(SomeClass.frooble, sentinel.Frooble) 365 366 test() 367 self.assertFalse(hasattr(SomeClass, 'frooble')) 368 369 370 def test_patch_wont_create_by_default(self): 371 with self.assertRaises(AttributeError): 372 @patch('%s.frooble' % builtin_string, sentinel.Frooble) 373 def test(): pass 374 375 test() 376 self.assertRaises(NameError, lambda: frooble) 377 378 379 def test_patchobject_wont_create_by_default(self): 380 with self.assertRaises(AttributeError): 381 @patch.object(SomeClass, 'ord', sentinel.Frooble) 382 def test(): pass 383 test() 384 self.assertFalse(hasattr(SomeClass, 'ord')) 385 386 387 def test_patch_builtins_without_create(self): 388 @patch(__name__+'.ord') 389 def test_ord(mock_ord): 390 mock_ord.return_value = 101 391 return ord('c') 392 393 @patch(__name__+'.open') 394 def test_open(mock_open): 395 m = mock_open.return_value 396 m.read.return_value = 'abcd' 397 398 fobj = open('doesnotexists.txt') 399 data = fobj.read() 400 fobj.close() 401 return data 402 403 self.assertEqual(test_ord(), 101) 404 self.assertEqual(test_open(), 'abcd') 405 406 407 def test_patch_with_static_methods(self): 408 class Foo(object): 409 @staticmethod 410 def woot(): 411 return sentinel.Static 412 413 @patch.object(Foo, 'woot', staticmethod(lambda: sentinel.Patched)) 414 def anonymous(): 415 self.assertEqual(Foo.woot(), sentinel.Patched) 416 anonymous() 417 418 self.assertEqual(Foo.woot(), sentinel.Static) 419 420 421 def test_patch_local(self): 422 foo = sentinel.Foo 423 @patch.object(sentinel, 'Foo', 'Foo') 424 def anonymous(): 425 self.assertEqual(sentinel.Foo, 'Foo') 426 anonymous() 427 428 self.assertEqual(sentinel.Foo, foo) 429 430 431 def test_patch_slots(self): 432 class Foo(object): 433 __slots__ = ('Foo',) 434 435 foo = Foo() 436 foo.Foo = sentinel.Foo 437 438 @patch.object(foo, 'Foo', 'Foo') 439 def anonymous(): 440 self.assertEqual(foo.Foo, 'Foo') 441 anonymous() 442 443 self.assertEqual(foo.Foo, sentinel.Foo) 444 445 446 def test_patchobject_class_decorator(self): 447 class Something(object): 448 attribute = sentinel.Original 449 450 class Foo(object): 451 def test_method(other_self): 452 self.assertEqual(Something.attribute, sentinel.Patched, 453 "unpatched") 454 def not_test_method(other_self): 455 self.assertEqual(Something.attribute, sentinel.Original, 456 "non-test method patched") 457 458 Foo = patch.object(Something, 'attribute', sentinel.Patched)(Foo) 459 460 f = Foo() 461 f.test_method() 462 f.not_test_method() 463 464 self.assertEqual(Something.attribute, sentinel.Original, 465 "patch not restored") 466 467 468 def test_patch_class_decorator(self): 469 class Something(object): 470 attribute = sentinel.Original 471 472 class Foo(object): 473 474 test_class_attr = 'whatever' 475 476 def test_method(other_self, mock_something): 477 self.assertEqual(PTModule.something, mock_something, 478 "unpatched") 479 def not_test_method(other_self): 480 self.assertEqual(PTModule.something, sentinel.Something, 481 "non-test method patched") 482 Foo = patch('%s.something' % __name__)(Foo) 483 484 f = Foo() 485 f.test_method() 486 f.not_test_method() 487 488 self.assertEqual(Something.attribute, sentinel.Original, 489 "patch not restored") 490 self.assertEqual(PTModule.something, sentinel.Something, 491 "patch not restored") 492 493 494 def test_patchobject_twice(self): 495 class Something(object): 496 attribute = sentinel.Original 497 next_attribute = sentinel.Original2 498 499 @patch.object(Something, 'attribute', sentinel.Patched) 500 @patch.object(Something, 'attribute', sentinel.Patched) 501 def test(): 502 self.assertEqual(Something.attribute, sentinel.Patched, "unpatched") 503 504 test() 505 506 self.assertEqual(Something.attribute, sentinel.Original, 507 "patch not restored") 508 509 510 def test_patch_dict(self): 511 foo = {'initial': object(), 'other': 'something'} 512 original = foo.copy() 513 514 @patch.dict(foo) 515 def test(): 516 foo['a'] = 3 517 del foo['initial'] 518 foo['other'] = 'something else' 519 520 test() 521 522 self.assertEqual(foo, original) 523 524 @patch.dict(foo, {'a': 'b'}) 525 def test(): 526 self.assertEqual(len(foo), 3) 527 self.assertEqual(foo['a'], 'b') 528 529 test() 530 531 self.assertEqual(foo, original) 532 533 @patch.dict(foo, [('a', 'b')]) 534 def test(): 535 self.assertEqual(len(foo), 3) 536 self.assertEqual(foo['a'], 'b') 537 538 test() 539 540 self.assertEqual(foo, original) 541 542 543 def test_patch_dict_with_container_object(self): 544 foo = Container() 545 foo['initial'] = object() 546 foo['other'] = 'something' 547 548 original = foo.values.copy() 549 550 @patch.dict(foo) 551 def test(): 552 foo['a'] = 3 553 del foo['initial'] 554 foo['other'] = 'something else' 555 556 test() 557 558 self.assertEqual(foo.values, original) 559 560 @patch.dict(foo, {'a': 'b'}) 561 def test(): 562 self.assertEqual(len(foo.values), 3) 563 self.assertEqual(foo['a'], 'b') 564 565 test() 566 567 self.assertEqual(foo.values, original) 568 569 570 def test_patch_dict_with_clear(self): 571 foo = {'initial': object(), 'other': 'something'} 572 original = foo.copy() 573 574 @patch.dict(foo, clear=True) 575 def test(): 576 self.assertEqual(foo, {}) 577 foo['a'] = 3 578 foo['other'] = 'something else' 579 580 test() 581 582 self.assertEqual(foo, original) 583 584 @patch.dict(foo, {'a': 'b'}, clear=True) 585 def test(): 586 self.assertEqual(foo, {'a': 'b'}) 587 588 test() 589 590 self.assertEqual(foo, original) 591 592 @patch.dict(foo, [('a', 'b')], clear=True) 593 def test(): 594 self.assertEqual(foo, {'a': 'b'}) 595 596 test() 597 598 self.assertEqual(foo, original) 599 600 601 def test_patch_dict_with_container_object_and_clear(self): 602 foo = Container() 603 foo['initial'] = object() 604 foo['other'] = 'something' 605 606 original = foo.values.copy() 607 608 @patch.dict(foo, clear=True) 609 def test(): 610 self.assertEqual(foo.values, {}) 611 foo['a'] = 3 612 foo['other'] = 'something else' 613 614 test() 615 616 self.assertEqual(foo.values, original) 617 618 @patch.dict(foo, {'a': 'b'}, clear=True) 619 def test(): 620 self.assertEqual(foo.values, {'a': 'b'}) 621 622 test() 623 624 self.assertEqual(foo.values, original) 625 626 627 def test_patch_dict_as_context_manager(self): 628 foo = {'a': 'b'} 629 with patch.dict(foo, a='c') as patched: 630 self.assertEqual(patched, {'a': 'c'}) 631 self.assertEqual(foo, {'a': 'b'}) 632 633 634 def test_name_preserved(self): 635 foo = {} 636 637 @patch('%s.SomeClass' % __name__, object()) 638 @patch('%s.SomeClass' % __name__, object(), autospec=True) 639 @patch.object(SomeClass, object()) 640 @patch.dict(foo) 641 def some_name(): pass 642 643 self.assertEqual(some_name.__name__, 'some_name') 644 645 646 def test_patch_with_exception(self): 647 foo = {} 648 649 @patch.dict(foo, {'a': 'b'}) 650 def test(): 651 raise NameError('Konrad') 652 653 with self.assertRaises(NameError): 654 test() 655 656 self.assertEqual(foo, {}) 657 658 659 def test_patch_dict_with_string(self): 660 @patch.dict('os.environ', {'konrad_delong': 'some value'}) 661 def test(): 662 self.assertIn('konrad_delong', os.environ) 663 664 test() 665 666 667 def test_patch_dict_decorator_resolution(self): 668 # bpo-35512: Ensure that patch with a string target resolves to 669 # the new dictionary during function call 670 original = support.target.copy() 671 672 @patch.dict('unittest.test.testmock.support.target', {'bar': 'BAR'}) 673 def test(): 674 self.assertEqual(support.target, {'foo': 'BAZ', 'bar': 'BAR'}) 675 676 try: 677 support.target = {'foo': 'BAZ'} 678 test() 679 self.assertEqual(support.target, {'foo': 'BAZ'}) 680 finally: 681 support.target = original 682 683 684 def test_patch_spec_set(self): 685 @patch('%s.SomeClass' % __name__, spec=SomeClass, spec_set=True) 686 def test(MockClass): 687 MockClass.z = 'foo' 688 689 self.assertRaises(AttributeError, test) 690 691 @patch.object(support, 'SomeClass', spec=SomeClass, spec_set=True) 692 def test(MockClass): 693 MockClass.z = 'foo' 694 695 self.assertRaises(AttributeError, test) 696 @patch('%s.SomeClass' % __name__, spec_set=True) 697 def test(MockClass): 698 MockClass.z = 'foo' 699 700 self.assertRaises(AttributeError, test) 701 702 @patch.object(support, 'SomeClass', spec_set=True) 703 def test(MockClass): 704 MockClass.z = 'foo' 705 706 self.assertRaises(AttributeError, test) 707 708 709 def test_spec_set_inherit(self): 710 @patch('%s.SomeClass' % __name__, spec_set=True) 711 def test(MockClass): 712 instance = MockClass() 713 instance.z = 'foo' 714 715 self.assertRaises(AttributeError, test) 716 717 718 def test_patch_start_stop(self): 719 original = something 720 patcher = patch('%s.something' % __name__) 721 self.assertIs(something, original) 722 mock = patcher.start() 723 try: 724 self.assertIsNot(mock, original) 725 self.assertIs(something, mock) 726 finally: 727 patcher.stop() 728 self.assertIs(something, original) 729 730 731 def test_stop_without_start(self): 732 # bpo-36366: calling stop without start will return None. 733 patcher = patch(foo_name, 'bar', 3) 734 self.assertIsNone(patcher.stop()) 735 736 737 def test_stop_idempotent(self): 738 # bpo-36366: calling stop on an already stopped patch will return None. 739 patcher = patch(foo_name, 'bar', 3) 740 741 patcher.start() 742 patcher.stop() 743 self.assertIsNone(patcher.stop()) 744 745 746 def test_patchobject_start_stop(self): 747 original = something 748 patcher = patch.object(PTModule, 'something', 'foo') 749 self.assertIs(something, original) 750 replaced = patcher.start() 751 try: 752 self.assertEqual(replaced, 'foo') 753 self.assertIs(something, replaced) 754 finally: 755 patcher.stop() 756 self.assertIs(something, original) 757 758 759 def test_patch_dict_start_stop(self): 760 d = {'foo': 'bar'} 761 original = d.copy() 762 patcher = patch.dict(d, [('spam', 'eggs')], clear=True) 763 self.assertEqual(d, original) 764 765 patcher.start() 766 try: 767 self.assertEqual(d, {'spam': 'eggs'}) 768 finally: 769 patcher.stop() 770 self.assertEqual(d, original) 771 772 773 def test_patch_dict_stop_without_start(self): 774 d = {'foo': 'bar'} 775 original = d.copy() 776 patcher = patch.dict(d, [('spam', 'eggs')], clear=True) 777 self.assertFalse(patcher.stop()) 778 self.assertEqual(d, original) 779 780 781 def test_patch_dict_class_decorator(self): 782 this = self 783 d = {'spam': 'eggs'} 784 original = d.copy() 785 786 class Test(object): 787 def test_first(self): 788 this.assertEqual(d, {'foo': 'bar'}) 789 def test_second(self): 790 this.assertEqual(d, {'foo': 'bar'}) 791 792 Test = patch.dict(d, {'foo': 'bar'}, clear=True)(Test) 793 self.assertEqual(d, original) 794 795 test = Test() 796 797 test.test_first() 798 self.assertEqual(d, original) 799 800 test.test_second() 801 self.assertEqual(d, original) 802 803 test = Test() 804 805 test.test_first() 806 self.assertEqual(d, original) 807 808 test.test_second() 809 self.assertEqual(d, original) 810 811 812 def test_get_only_proxy(self): 813 class Something(object): 814 foo = 'foo' 815 class SomethingElse: 816 foo = 'foo' 817 818 for thing in Something, SomethingElse, Something(), SomethingElse: 819 proxy = _get_proxy(thing) 820 821 @patch.object(proxy, 'foo', 'bar') 822 def test(): 823 self.assertEqual(proxy.foo, 'bar') 824 test() 825 self.assertEqual(proxy.foo, 'foo') 826 self.assertEqual(thing.foo, 'foo') 827 self.assertNotIn('foo', proxy.__dict__) 828 829 830 def test_get_set_delete_proxy(self): 831 class Something(object): 832 foo = 'foo' 833 class SomethingElse: 834 foo = 'foo' 835 836 for thing in Something, SomethingElse, Something(), SomethingElse: 837 proxy = _get_proxy(Something, get_only=False) 838 839 @patch.object(proxy, 'foo', 'bar') 840 def test(): 841 self.assertEqual(proxy.foo, 'bar') 842 test() 843 self.assertEqual(proxy.foo, 'foo') 844 self.assertEqual(thing.foo, 'foo') 845 self.assertNotIn('foo', proxy.__dict__) 846 847 848 def test_patch_keyword_args(self): 849 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33, 850 'foo': MagicMock()} 851 852 patcher = patch(foo_name, **kwargs) 853 mock = patcher.start() 854 patcher.stop() 855 856 self.assertRaises(KeyError, mock) 857 self.assertEqual(mock.foo.bar(), 33) 858 self.assertIsInstance(mock.foo, MagicMock) 859 860 861 def test_patch_object_keyword_args(self): 862 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33, 863 'foo': MagicMock()} 864 865 patcher = patch.object(Foo, 'f', **kwargs) 866 mock = patcher.start() 867 patcher.stop() 868 869 self.assertRaises(KeyError, mock) 870 self.assertEqual(mock.foo.bar(), 33) 871 self.assertIsInstance(mock.foo, MagicMock) 872 873 874 def test_patch_dict_keyword_args(self): 875 original = {'foo': 'bar'} 876 copy = original.copy() 877 878 patcher = patch.dict(original, foo=3, bar=4, baz=5) 879 patcher.start() 880 881 try: 882 self.assertEqual(original, dict(foo=3, bar=4, baz=5)) 883 finally: 884 patcher.stop() 885 886 self.assertEqual(original, copy) 887 888 889 def test_autospec(self): 890 class Boo(object): 891 def __init__(self, a): pass 892 def f(self, a): pass 893 def g(self): pass 894 foo = 'bar' 895 896 class Bar(object): 897 def a(self): pass 898 899 def _test(mock): 900 mock(1) 901 mock.assert_called_with(1) 902 self.assertRaises(TypeError, mock) 903 904 def _test2(mock): 905 mock.f(1) 906 mock.f.assert_called_with(1) 907 self.assertRaises(TypeError, mock.f) 908 909 mock.g() 910 mock.g.assert_called_with() 911 self.assertRaises(TypeError, mock.g, 1) 912 913 self.assertRaises(AttributeError, getattr, mock, 'h') 914 915 mock.foo.lower() 916 mock.foo.lower.assert_called_with() 917 self.assertRaises(AttributeError, getattr, mock.foo, 'bar') 918 919 mock.Bar() 920 mock.Bar.assert_called_with() 921 922 mock.Bar.a() 923 mock.Bar.a.assert_called_with() 924 self.assertRaises(TypeError, mock.Bar.a, 1) 925 926 mock.Bar().a() 927 mock.Bar().a.assert_called_with() 928 self.assertRaises(TypeError, mock.Bar().a, 1) 929 930 self.assertRaises(AttributeError, getattr, mock.Bar, 'b') 931 self.assertRaises(AttributeError, getattr, mock.Bar(), 'b') 932 933 def function(mock): 934 _test(mock) 935 _test2(mock) 936 _test2(mock(1)) 937 self.assertIs(mock, Foo) 938 return mock 939 940 test = patch(foo_name, autospec=True)(function) 941 942 mock = test() 943 self.assertIsNot(Foo, mock) 944 # test patching a second time works 945 test() 946 947 module = sys.modules[__name__] 948 test = patch.object(module, 'Foo', autospec=True)(function) 949 950 mock = test() 951 self.assertIsNot(Foo, mock) 952 # test patching a second time works 953 test() 954 955 956 def test_autospec_function(self): 957 @patch('%s.function' % __name__, autospec=True) 958 def test(mock): 959 function.assert_not_called() 960 self.assertRaises(AssertionError, function.assert_called) 961 self.assertRaises(AssertionError, function.assert_called_once) 962 function(1) 963 self.assertRaises(AssertionError, function.assert_not_called) 964 function.assert_called_with(1) 965 function.assert_called() 966 function.assert_called_once() 967 function(2, 3) 968 function.assert_called_with(2, 3) 969 970 self.assertRaises(TypeError, function) 971 self.assertRaises(AttributeError, getattr, function, 'foo') 972 973 test() 974 975 976 def test_autospec_keywords(self): 977 @patch('%s.function' % __name__, autospec=True, 978 return_value=3) 979 def test(mock_function): 980 #self.assertEqual(function.abc, 'foo') 981 return function(1, 2) 982 983 result = test() 984 self.assertEqual(result, 3) 985 986 987 def test_autospec_staticmethod(self): 988 with patch('%s.Foo.static_method' % __name__, autospec=True) as method: 989 Foo.static_method() 990 method.assert_called_once_with() 991 992 993 def test_autospec_classmethod(self): 994 with patch('%s.Foo.class_method' % __name__, autospec=True) as method: 995 Foo.class_method() 996 method.assert_called_once_with() 997 998 999 def test_autospec_with_new(self): 1000 patcher = patch('%s.function' % __name__, new=3, autospec=True) 1001 self.assertRaises(TypeError, patcher.start) 1002 1003 module = sys.modules[__name__] 1004 patcher = patch.object(module, 'function', new=3, autospec=True) 1005 self.assertRaises(TypeError, patcher.start) 1006 1007 1008 def test_autospec_with_object(self): 1009 class Bar(Foo): 1010 extra = [] 1011 1012 patcher = patch(foo_name, autospec=Bar) 1013 mock = patcher.start() 1014 try: 1015 self.assertIsInstance(mock, Bar) 1016 self.assertIsInstance(mock.extra, list) 1017 finally: 1018 patcher.stop() 1019 1020 1021 def test_autospec_inherits(self): 1022 FooClass = Foo 1023 patcher = patch(foo_name, autospec=True) 1024 mock = patcher.start() 1025 try: 1026 self.assertIsInstance(mock, FooClass) 1027 self.assertIsInstance(mock(3), FooClass) 1028 finally: 1029 patcher.stop() 1030 1031 1032 def test_autospec_name(self): 1033 patcher = patch(foo_name, autospec=True) 1034 mock = patcher.start() 1035 1036 try: 1037 self.assertIn(" name='Foo'", repr(mock)) 1038 self.assertIn(" name='Foo.f'", repr(mock.f)) 1039 self.assertIn(" name='Foo()'", repr(mock(None))) 1040 self.assertIn(" name='Foo().f'", repr(mock(None).f)) 1041 finally: 1042 patcher.stop() 1043 1044 1045 def test_tracebacks(self): 1046 @patch.object(Foo, 'f', object()) 1047 def test(): 1048 raise AssertionError 1049 try: 1050 test() 1051 except: 1052 err = sys.exc_info() 1053 1054 result = unittest.TextTestResult(None, None, 0) 1055 traceback = result._exc_info_to_string(err, self) 1056 self.assertIn('raise AssertionError', traceback) 1057 1058 1059 def test_new_callable_patch(self): 1060 patcher = patch(foo_name, new_callable=NonCallableMagicMock) 1061 1062 m1 = patcher.start() 1063 patcher.stop() 1064 m2 = patcher.start() 1065 patcher.stop() 1066 1067 self.assertIsNot(m1, m2) 1068 for mock in m1, m2: 1069 self.assertNotCallable(m1) 1070 1071 1072 def test_new_callable_patch_object(self): 1073 patcher = patch.object(Foo, 'f', new_callable=NonCallableMagicMock) 1074 1075 m1 = patcher.start() 1076 patcher.stop() 1077 m2 = patcher.start() 1078 patcher.stop() 1079 1080 self.assertIsNot(m1, m2) 1081 for mock in m1, m2: 1082 self.assertNotCallable(m1) 1083 1084 1085 def test_new_callable_keyword_arguments(self): 1086 class Bar(object): 1087 kwargs = None 1088 def __init__(self, **kwargs): 1089 Bar.kwargs = kwargs 1090 1091 patcher = patch(foo_name, new_callable=Bar, arg1=1, arg2=2) 1092 m = patcher.start() 1093 try: 1094 self.assertIs(type(m), Bar) 1095 self.assertEqual(Bar.kwargs, dict(arg1=1, arg2=2)) 1096 finally: 1097 patcher.stop() 1098 1099 1100 def test_new_callable_spec(self): 1101 class Bar(object): 1102 kwargs = None 1103 def __init__(self, **kwargs): 1104 Bar.kwargs = kwargs 1105 1106 patcher = patch(foo_name, new_callable=Bar, spec=Bar) 1107 patcher.start() 1108 try: 1109 self.assertEqual(Bar.kwargs, dict(spec=Bar)) 1110 finally: 1111 patcher.stop() 1112 1113 patcher = patch(foo_name, new_callable=Bar, spec_set=Bar) 1114 patcher.start() 1115 try: 1116 self.assertEqual(Bar.kwargs, dict(spec_set=Bar)) 1117 finally: 1118 patcher.stop() 1119 1120 1121 def test_new_callable_create(self): 1122 non_existent_attr = '%s.weeeee' % foo_name 1123 p = patch(non_existent_attr, new_callable=NonCallableMock) 1124 self.assertRaises(AttributeError, p.start) 1125 1126 p = patch(non_existent_attr, new_callable=NonCallableMock, 1127 create=True) 1128 m = p.start() 1129 try: 1130 self.assertNotCallable(m, magic=False) 1131 finally: 1132 p.stop() 1133 1134 1135 def test_new_callable_incompatible_with_new(self): 1136 self.assertRaises( 1137 ValueError, patch, foo_name, new=object(), new_callable=MagicMock 1138 ) 1139 self.assertRaises( 1140 ValueError, patch.object, Foo, 'f', new=object(), 1141 new_callable=MagicMock 1142 ) 1143 1144 1145 def test_new_callable_incompatible_with_autospec(self): 1146 self.assertRaises( 1147 ValueError, patch, foo_name, new_callable=MagicMock, 1148 autospec=True 1149 ) 1150 self.assertRaises( 1151 ValueError, patch.object, Foo, 'f', new_callable=MagicMock, 1152 autospec=True 1153 ) 1154 1155 1156 def test_new_callable_inherit_for_mocks(self): 1157 class MockSub(Mock): 1158 pass 1159 1160 MockClasses = ( 1161 NonCallableMock, NonCallableMagicMock, MagicMock, Mock, MockSub 1162 ) 1163 for Klass in MockClasses: 1164 for arg in 'spec', 'spec_set': 1165 kwargs = {arg: True} 1166 p = patch(foo_name, new_callable=Klass, **kwargs) 1167 m = p.start() 1168 try: 1169 instance = m.return_value 1170 self.assertRaises(AttributeError, getattr, instance, 'x') 1171 finally: 1172 p.stop() 1173 1174 1175 def test_new_callable_inherit_non_mock(self): 1176 class NotAMock(object): 1177 def __init__(self, spec): 1178 self.spec = spec 1179 1180 p = patch(foo_name, new_callable=NotAMock, spec=True) 1181 m = p.start() 1182 try: 1183 self.assertTrue(is_instance(m, NotAMock)) 1184 self.assertRaises(AttributeError, getattr, m, 'return_value') 1185 finally: 1186 p.stop() 1187 1188 self.assertEqual(m.spec, Foo) 1189 1190 1191 def test_new_callable_class_decorating(self): 1192 test = self 1193 original = Foo 1194 class SomeTest(object): 1195 1196 def _test(self, mock_foo): 1197 test.assertIsNot(Foo, original) 1198 test.assertIs(Foo, mock_foo) 1199 test.assertIsInstance(Foo, SomeClass) 1200 1201 def test_two(self, mock_foo): 1202 self._test(mock_foo) 1203 def test_one(self, mock_foo): 1204 self._test(mock_foo) 1205 1206 SomeTest = patch(foo_name, new_callable=SomeClass)(SomeTest) 1207 SomeTest().test_one() 1208 SomeTest().test_two() 1209 self.assertIs(Foo, original) 1210 1211 1212 def test_patch_multiple(self): 1213 original_foo = Foo 1214 original_f = Foo.f 1215 original_g = Foo.g 1216 1217 patcher1 = patch.multiple(foo_name, f=1, g=2) 1218 patcher2 = patch.multiple(Foo, f=1, g=2) 1219 1220 for patcher in patcher1, patcher2: 1221 patcher.start() 1222 try: 1223 self.assertIs(Foo, original_foo) 1224 self.assertEqual(Foo.f, 1) 1225 self.assertEqual(Foo.g, 2) 1226 finally: 1227 patcher.stop() 1228 1229 self.assertIs(Foo, original_foo) 1230 self.assertEqual(Foo.f, original_f) 1231 self.assertEqual(Foo.g, original_g) 1232 1233 1234 @patch.multiple(foo_name, f=3, g=4) 1235 def test(): 1236 self.assertIs(Foo, original_foo) 1237 self.assertEqual(Foo.f, 3) 1238 self.assertEqual(Foo.g, 4) 1239 1240 test() 1241 1242 1243 def test_patch_multiple_no_kwargs(self): 1244 self.assertRaises(ValueError, patch.multiple, foo_name) 1245 self.assertRaises(ValueError, patch.multiple, Foo) 1246 1247 1248 def test_patch_multiple_create_mocks(self): 1249 original_foo = Foo 1250 original_f = Foo.f 1251 original_g = Foo.g 1252 1253 @patch.multiple(foo_name, f=DEFAULT, g=3, foo=DEFAULT) 1254 def test(f, foo): 1255 self.assertIs(Foo, original_foo) 1256 self.assertIs(Foo.f, f) 1257 self.assertEqual(Foo.g, 3) 1258 self.assertIs(Foo.foo, foo) 1259 self.assertTrue(is_instance(f, MagicMock)) 1260 self.assertTrue(is_instance(foo, MagicMock)) 1261 1262 test() 1263 self.assertEqual(Foo.f, original_f) 1264 self.assertEqual(Foo.g, original_g) 1265 1266 1267 def test_patch_multiple_create_mocks_different_order(self): 1268 original_f = Foo.f 1269 original_g = Foo.g 1270 1271 patcher = patch.object(Foo, 'f', 3) 1272 patcher.attribute_name = 'f' 1273 1274 other = patch.object(Foo, 'g', DEFAULT) 1275 other.attribute_name = 'g' 1276 patcher.additional_patchers = [other] 1277 1278 @patcher 1279 def test(g): 1280 self.assertIs(Foo.g, g) 1281 self.assertEqual(Foo.f, 3) 1282 1283 test() 1284 self.assertEqual(Foo.f, original_f) 1285 self.assertEqual(Foo.g, original_g) 1286 1287 1288 def test_patch_multiple_stacked_decorators(self): 1289 original_foo = Foo 1290 original_f = Foo.f 1291 original_g = Foo.g 1292 1293 @patch.multiple(foo_name, f=DEFAULT) 1294 @patch.multiple(foo_name, foo=DEFAULT) 1295 @patch(foo_name + '.g') 1296 def test1(g, **kwargs): 1297 _test(g, **kwargs) 1298 1299 @patch.multiple(foo_name, f=DEFAULT) 1300 @patch(foo_name + '.g') 1301 @patch.multiple(foo_name, foo=DEFAULT) 1302 def test2(g, **kwargs): 1303 _test(g, **kwargs) 1304 1305 @patch(foo_name + '.g') 1306 @patch.multiple(foo_name, f=DEFAULT) 1307 @patch.multiple(foo_name, foo=DEFAULT) 1308 def test3(g, **kwargs): 1309 _test(g, **kwargs) 1310 1311 def _test(g, **kwargs): 1312 f = kwargs.pop('f') 1313 foo = kwargs.pop('foo') 1314 self.assertFalse(kwargs) 1315 1316 self.assertIs(Foo, original_foo) 1317 self.assertIs(Foo.f, f) 1318 self.assertIs(Foo.g, g) 1319 self.assertIs(Foo.foo, foo) 1320 self.assertTrue(is_instance(f, MagicMock)) 1321 self.assertTrue(is_instance(g, MagicMock)) 1322 self.assertTrue(is_instance(foo, MagicMock)) 1323 1324 test1() 1325 test2() 1326 test3() 1327 self.assertEqual(Foo.f, original_f) 1328 self.assertEqual(Foo.g, original_g) 1329 1330 1331 def test_patch_multiple_create_mocks_patcher(self): 1332 original_foo = Foo 1333 original_f = Foo.f 1334 original_g = Foo.g 1335 1336 patcher = patch.multiple(foo_name, f=DEFAULT, g=3, foo=DEFAULT) 1337 1338 result = patcher.start() 1339 try: 1340 f = result['f'] 1341 foo = result['foo'] 1342 self.assertEqual(set(result), set(['f', 'foo'])) 1343 1344 self.assertIs(Foo, original_foo) 1345 self.assertIs(Foo.f, f) 1346 self.assertIs(Foo.foo, foo) 1347 self.assertTrue(is_instance(f, MagicMock)) 1348 self.assertTrue(is_instance(foo, MagicMock)) 1349 finally: 1350 patcher.stop() 1351 1352 self.assertEqual(Foo.f, original_f) 1353 self.assertEqual(Foo.g, original_g) 1354 1355 1356 def test_patch_multiple_decorating_class(self): 1357 test = self 1358 original_foo = Foo 1359 original_f = Foo.f 1360 original_g = Foo.g 1361 1362 class SomeTest(object): 1363 1364 def _test(self, f, foo): 1365 test.assertIs(Foo, original_foo) 1366 test.assertIs(Foo.f, f) 1367 test.assertEqual(Foo.g, 3) 1368 test.assertIs(Foo.foo, foo) 1369 test.assertTrue(is_instance(f, MagicMock)) 1370 test.assertTrue(is_instance(foo, MagicMock)) 1371 1372 def test_two(self, f, foo): 1373 self._test(f, foo) 1374 def test_one(self, f, foo): 1375 self._test(f, foo) 1376 1377 SomeTest = patch.multiple( 1378 foo_name, f=DEFAULT, g=3, foo=DEFAULT 1379 )(SomeTest) 1380 1381 thing = SomeTest() 1382 thing.test_one() 1383 thing.test_two() 1384 1385 self.assertEqual(Foo.f, original_f) 1386 self.assertEqual(Foo.g, original_g) 1387 1388 1389 def test_patch_multiple_create(self): 1390 patcher = patch.multiple(Foo, blam='blam') 1391 self.assertRaises(AttributeError, patcher.start) 1392 1393 patcher = patch.multiple(Foo, blam='blam', create=True) 1394 patcher.start() 1395 try: 1396 self.assertEqual(Foo.blam, 'blam') 1397 finally: 1398 patcher.stop() 1399 1400 self.assertFalse(hasattr(Foo, 'blam')) 1401 1402 1403 def test_patch_multiple_spec_set(self): 1404 # if spec_set works then we can assume that spec and autospec also 1405 # work as the underlying machinery is the same 1406 patcher = patch.multiple(Foo, foo=DEFAULT, spec_set=['a', 'b']) 1407 result = patcher.start() 1408 try: 1409 self.assertEqual(Foo.foo, result['foo']) 1410 Foo.foo.a(1) 1411 Foo.foo.b(2) 1412 Foo.foo.a.assert_called_with(1) 1413 Foo.foo.b.assert_called_with(2) 1414 self.assertRaises(AttributeError, setattr, Foo.foo, 'c', None) 1415 finally: 1416 patcher.stop() 1417 1418 1419 def test_patch_multiple_new_callable(self): 1420 class Thing(object): 1421 pass 1422 1423 patcher = patch.multiple( 1424 Foo, f=DEFAULT, g=DEFAULT, new_callable=Thing 1425 ) 1426 result = patcher.start() 1427 try: 1428 self.assertIs(Foo.f, result['f']) 1429 self.assertIs(Foo.g, result['g']) 1430 self.assertIsInstance(Foo.f, Thing) 1431 self.assertIsInstance(Foo.g, Thing) 1432 self.assertIsNot(Foo.f, Foo.g) 1433 finally: 1434 patcher.stop() 1435 1436 1437 def test_nested_patch_failure(self): 1438 original_f = Foo.f 1439 original_g = Foo.g 1440 1441 @patch.object(Foo, 'g', 1) 1442 @patch.object(Foo, 'missing', 1) 1443 @patch.object(Foo, 'f', 1) 1444 def thing1(): pass 1445 1446 @patch.object(Foo, 'missing', 1) 1447 @patch.object(Foo, 'g', 1) 1448 @patch.object(Foo, 'f', 1) 1449 def thing2(): pass 1450 1451 @patch.object(Foo, 'g', 1) 1452 @patch.object(Foo, 'f', 1) 1453 @patch.object(Foo, 'missing', 1) 1454 def thing3(): pass 1455 1456 for func in thing1, thing2, thing3: 1457 self.assertRaises(AttributeError, func) 1458 self.assertEqual(Foo.f, original_f) 1459 self.assertEqual(Foo.g, original_g) 1460 1461 1462 def test_new_callable_failure(self): 1463 original_f = Foo.f 1464 original_g = Foo.g 1465 original_foo = Foo.foo 1466 1467 def crasher(): 1468 raise NameError('crasher') 1469 1470 @patch.object(Foo, 'g', 1) 1471 @patch.object(Foo, 'foo', new_callable=crasher) 1472 @patch.object(Foo, 'f', 1) 1473 def thing1(): pass 1474 1475 @patch.object(Foo, 'foo', new_callable=crasher) 1476 @patch.object(Foo, 'g', 1) 1477 @patch.object(Foo, 'f', 1) 1478 def thing2(): pass 1479 1480 @patch.object(Foo, 'g', 1) 1481 @patch.object(Foo, 'f', 1) 1482 @patch.object(Foo, 'foo', new_callable=crasher) 1483 def thing3(): pass 1484 1485 for func in thing1, thing2, thing3: 1486 self.assertRaises(NameError, func) 1487 self.assertEqual(Foo.f, original_f) 1488 self.assertEqual(Foo.g, original_g) 1489 self.assertEqual(Foo.foo, original_foo) 1490 1491 1492 def test_patch_multiple_failure(self): 1493 original_f = Foo.f 1494 original_g = Foo.g 1495 1496 patcher = patch.object(Foo, 'f', 1) 1497 patcher.attribute_name = 'f' 1498 1499 good = patch.object(Foo, 'g', 1) 1500 good.attribute_name = 'g' 1501 1502 bad = patch.object(Foo, 'missing', 1) 1503 bad.attribute_name = 'missing' 1504 1505 for additionals in [good, bad], [bad, good]: 1506 patcher.additional_patchers = additionals 1507 1508 @patcher 1509 def func(): pass 1510 1511 self.assertRaises(AttributeError, func) 1512 self.assertEqual(Foo.f, original_f) 1513 self.assertEqual(Foo.g, original_g) 1514 1515 1516 def test_patch_multiple_new_callable_failure(self): 1517 original_f = Foo.f 1518 original_g = Foo.g 1519 original_foo = Foo.foo 1520 1521 def crasher(): 1522 raise NameError('crasher') 1523 1524 patcher = patch.object(Foo, 'f', 1) 1525 patcher.attribute_name = 'f' 1526 1527 good = patch.object(Foo, 'g', 1) 1528 good.attribute_name = 'g' 1529 1530 bad = patch.object(Foo, 'foo', new_callable=crasher) 1531 bad.attribute_name = 'foo' 1532 1533 for additionals in [good, bad], [bad, good]: 1534 patcher.additional_patchers = additionals 1535 1536 @patcher 1537 def func(): pass 1538 1539 self.assertRaises(NameError, func) 1540 self.assertEqual(Foo.f, original_f) 1541 self.assertEqual(Foo.g, original_g) 1542 self.assertEqual(Foo.foo, original_foo) 1543 1544 1545 def test_patch_multiple_string_subclasses(self): 1546 Foo = type('Foo', (str,), {'fish': 'tasty'}) 1547 foo = Foo() 1548 @patch.multiple(foo, fish='nearly gone') 1549 def test(): 1550 self.assertEqual(foo.fish, 'nearly gone') 1551 1552 test() 1553 self.assertEqual(foo.fish, 'tasty') 1554 1555 1556 @patch('unittest.mock.patch.TEST_PREFIX', 'foo') 1557 def test_patch_test_prefix(self): 1558 class Foo(object): 1559 thing = 'original' 1560 1561 def foo_one(self): 1562 return self.thing 1563 def foo_two(self): 1564 return self.thing 1565 def test_one(self): 1566 return self.thing 1567 def test_two(self): 1568 return self.thing 1569 1570 Foo = patch.object(Foo, 'thing', 'changed')(Foo) 1571 1572 foo = Foo() 1573 self.assertEqual(foo.foo_one(), 'changed') 1574 self.assertEqual(foo.foo_two(), 'changed') 1575 self.assertEqual(foo.test_one(), 'original') 1576 self.assertEqual(foo.test_two(), 'original') 1577 1578 1579 @patch('unittest.mock.patch.TEST_PREFIX', 'bar') 1580 def test_patch_dict_test_prefix(self): 1581 class Foo(object): 1582 def bar_one(self): 1583 return dict(the_dict) 1584 def bar_two(self): 1585 return dict(the_dict) 1586 def test_one(self): 1587 return dict(the_dict) 1588 def test_two(self): 1589 return dict(the_dict) 1590 1591 the_dict = {'key': 'original'} 1592 Foo = patch.dict(the_dict, key='changed')(Foo) 1593 1594 foo =Foo() 1595 self.assertEqual(foo.bar_one(), {'key': 'changed'}) 1596 self.assertEqual(foo.bar_two(), {'key': 'changed'}) 1597 self.assertEqual(foo.test_one(), {'key': 'original'}) 1598 self.assertEqual(foo.test_two(), {'key': 'original'}) 1599 1600 1601 def test_patch_with_spec_mock_repr(self): 1602 for arg in ('spec', 'autospec', 'spec_set'): 1603 p = patch('%s.SomeClass' % __name__, **{arg: True}) 1604 m = p.start() 1605 try: 1606 self.assertIn(" name='SomeClass'", repr(m)) 1607 self.assertIn(" name='SomeClass.class_attribute'", 1608 repr(m.class_attribute)) 1609 self.assertIn(" name='SomeClass()'", repr(m())) 1610 self.assertIn(" name='SomeClass().class_attribute'", 1611 repr(m().class_attribute)) 1612 finally: 1613 p.stop() 1614 1615 1616 def test_patch_nested_autospec_repr(self): 1617 with patch('unittest.test.testmock.support', autospec=True) as m: 1618 self.assertIn(" name='support.SomeClass.wibble()'", 1619 repr(m.SomeClass.wibble())) 1620 self.assertIn(" name='support.SomeClass().wibble()'", 1621 repr(m.SomeClass().wibble())) 1622 1623 1624 1625 def test_mock_calls_with_patch(self): 1626 for arg in ('spec', 'autospec', 'spec_set'): 1627 p = patch('%s.SomeClass' % __name__, **{arg: True}) 1628 m = p.start() 1629 try: 1630 m.wibble() 1631 1632 kalls = [call.wibble()] 1633 self.assertEqual(m.mock_calls, kalls) 1634 self.assertEqual(m.method_calls, kalls) 1635 self.assertEqual(m.wibble.mock_calls, [call()]) 1636 1637 result = m() 1638 kalls.append(call()) 1639 self.assertEqual(m.mock_calls, kalls) 1640 1641 result.wibble() 1642 kalls.append(call().wibble()) 1643 self.assertEqual(m.mock_calls, kalls) 1644 1645 self.assertEqual(result.mock_calls, [call.wibble()]) 1646 self.assertEqual(result.wibble.mock_calls, [call()]) 1647 self.assertEqual(result.method_calls, [call.wibble()]) 1648 finally: 1649 p.stop() 1650 1651 1652 def test_patch_imports_lazily(self): 1653 p1 = patch('squizz.squozz') 1654 self.assertRaises(ImportError, p1.start) 1655 1656 with uncache('squizz'): 1657 squizz = Mock() 1658 sys.modules['squizz'] = squizz 1659 1660 squizz.squozz = 6 1661 p1 = patch('squizz.squozz') 1662 squizz.squozz = 3 1663 p1.start() 1664 p1.stop() 1665 self.assertEqual(squizz.squozz, 3) 1666 1667 def test_patch_propagates_exc_on_exit(self): 1668 class holder: 1669 exc_info = None, None, None 1670 1671 class custom_patch(_patch): 1672 def __exit__(self, etype=None, val=None, tb=None): 1673 _patch.__exit__(self, etype, val, tb) 1674 holder.exc_info = etype, val, tb 1675 stop = __exit__ 1676 1677 def with_custom_patch(target): 1678 getter, attribute = _get_target(target) 1679 return custom_patch( 1680 getter, attribute, DEFAULT, None, False, None, 1681 None, None, {} 1682 ) 1683 1684 @with_custom_patch('squizz.squozz') 1685 def test(mock): 1686 raise RuntimeError 1687 1688 with uncache('squizz'): 1689 squizz = Mock() 1690 sys.modules['squizz'] = squizz 1691 1692 self.assertRaises(RuntimeError, test) 1693 1694 self.assertIs(holder.exc_info[0], RuntimeError) 1695 self.assertIsNotNone(holder.exc_info[1], 1696 'exception value not propagated') 1697 self.assertIsNotNone(holder.exc_info[2], 1698 'exception traceback not propagated') 1699 1700 1701 def test_create_and_specs(self): 1702 for kwarg in ('spec', 'spec_set', 'autospec'): 1703 p = patch('%s.doesnotexist' % __name__, create=True, 1704 **{kwarg: True}) 1705 self.assertRaises(TypeError, p.start) 1706 self.assertRaises(NameError, lambda: doesnotexist) 1707 1708 # check that spec with create is innocuous if the original exists 1709 p = patch(MODNAME, create=True, **{kwarg: True}) 1710 p.start() 1711 p.stop() 1712 1713 1714 def test_multiple_specs(self): 1715 original = PTModule 1716 for kwarg in ('spec', 'spec_set'): 1717 p = patch(MODNAME, autospec=0, **{kwarg: 0}) 1718 self.assertRaises(TypeError, p.start) 1719 self.assertIs(PTModule, original) 1720 1721 for kwarg in ('spec', 'autospec'): 1722 p = patch(MODNAME, spec_set=0, **{kwarg: 0}) 1723 self.assertRaises(TypeError, p.start) 1724 self.assertIs(PTModule, original) 1725 1726 for kwarg in ('spec_set', 'autospec'): 1727 p = patch(MODNAME, spec=0, **{kwarg: 0}) 1728 self.assertRaises(TypeError, p.start) 1729 self.assertIs(PTModule, original) 1730 1731 1732 def test_specs_false_instead_of_none(self): 1733 p = patch(MODNAME, spec=False, spec_set=False, autospec=False) 1734 mock = p.start() 1735 try: 1736 # no spec should have been set, so attribute access should not fail 1737 mock.does_not_exist 1738 mock.does_not_exist = 3 1739 finally: 1740 p.stop() 1741 1742 1743 def test_falsey_spec(self): 1744 for kwarg in ('spec', 'autospec', 'spec_set'): 1745 p = patch(MODNAME, **{kwarg: 0}) 1746 m = p.start() 1747 try: 1748 self.assertRaises(AttributeError, getattr, m, 'doesnotexit') 1749 finally: 1750 p.stop() 1751 1752 1753 def test_spec_set_true(self): 1754 for kwarg in ('spec', 'autospec'): 1755 p = patch(MODNAME, spec_set=True, **{kwarg: True}) 1756 m = p.start() 1757 try: 1758 self.assertRaises(AttributeError, setattr, m, 1759 'doesnotexist', 'something') 1760 self.assertRaises(AttributeError, getattr, m, 'doesnotexist') 1761 finally: 1762 p.stop() 1763 1764 1765 def test_callable_spec_as_list(self): 1766 spec = ('__call__',) 1767 p = patch(MODNAME, spec=spec) 1768 m = p.start() 1769 try: 1770 self.assertTrue(callable(m)) 1771 finally: 1772 p.stop() 1773 1774 1775 def test_not_callable_spec_as_list(self): 1776 spec = ('foo', 'bar') 1777 p = patch(MODNAME, spec=spec) 1778 m = p.start() 1779 try: 1780 self.assertFalse(callable(m)) 1781 finally: 1782 p.stop() 1783 1784 1785 def test_patch_stopall(self): 1786 unlink = os.unlink 1787 chdir = os.chdir 1788 path = os.path 1789 patch('os.unlink', something).start() 1790 patch('os.chdir', something_else).start() 1791 1792 @patch('os.path') 1793 def patched(mock_path): 1794 patch.stopall() 1795 self.assertIs(os.path, mock_path) 1796 self.assertIs(os.unlink, unlink) 1797 self.assertIs(os.chdir, chdir) 1798 1799 patched() 1800 self.assertIs(os.path, path) 1801 1802 def test_stopall_lifo(self): 1803 stopped = [] 1804 class thing(object): 1805 one = two = three = None 1806 1807 def get_patch(attribute): 1808 class mypatch(_patch): 1809 def stop(self): 1810 stopped.append(attribute) 1811 return super(mypatch, self).stop() 1812 return mypatch(lambda: thing, attribute, None, None, 1813 False, None, None, None, {}) 1814 [get_patch(val).start() for val in ("one", "two", "three")] 1815 patch.stopall() 1816 1817 self.assertEqual(stopped, ["three", "two", "one"]) 1818 1819 def test_patch_dict_stopall(self): 1820 dic1 = {} 1821 dic2 = {1: 'a'} 1822 dic3 = {1: 'A', 2: 'B'} 1823 origdic1 = dic1.copy() 1824 origdic2 = dic2.copy() 1825 origdic3 = dic3.copy() 1826 patch.dict(dic1, {1: 'I', 2: 'II'}).start() 1827 patch.dict(dic2, {2: 'b'}).start() 1828 1829 @patch.dict(dic3) 1830 def patched(): 1831 del dic3[1] 1832 1833 patched() 1834 self.assertNotEqual(dic1, origdic1) 1835 self.assertNotEqual(dic2, origdic2) 1836 self.assertEqual(dic3, origdic3) 1837 1838 patch.stopall() 1839 1840 self.assertEqual(dic1, origdic1) 1841 self.assertEqual(dic2, origdic2) 1842 self.assertEqual(dic3, origdic3) 1843 1844 1845 def test_patch_and_patch_dict_stopall(self): 1846 original_unlink = os.unlink 1847 original_chdir = os.chdir 1848 dic1 = {} 1849 dic2 = {1: 'A', 2: 'B'} 1850 origdic1 = dic1.copy() 1851 origdic2 = dic2.copy() 1852 1853 patch('os.unlink', something).start() 1854 patch('os.chdir', something_else).start() 1855 patch.dict(dic1, {1: 'I', 2: 'II'}).start() 1856 patch.dict(dic2).start() 1857 del dic2[1] 1858 1859 self.assertIsNot(os.unlink, original_unlink) 1860 self.assertIsNot(os.chdir, original_chdir) 1861 self.assertNotEqual(dic1, origdic1) 1862 self.assertNotEqual(dic2, origdic2) 1863 patch.stopall() 1864 self.assertIs(os.unlink, original_unlink) 1865 self.assertIs(os.chdir, original_chdir) 1866 self.assertEqual(dic1, origdic1) 1867 self.assertEqual(dic2, origdic2) 1868 1869 1870 def test_special_attrs(self): 1871 def foo(x=0): 1872 """TEST""" 1873 return x 1874 with patch.object(foo, '__defaults__', (1, )): 1875 self.assertEqual(foo(), 1) 1876 self.assertEqual(foo(), 0) 1877 1878 orig_doc = foo.__doc__ 1879 with patch.object(foo, '__doc__', "FUN"): 1880 self.assertEqual(foo.__doc__, "FUN") 1881 self.assertEqual(foo.__doc__, orig_doc) 1882 1883 with patch.object(foo, '__module__', "testpatch2"): 1884 self.assertEqual(foo.__module__, "testpatch2") 1885 self.assertEqual(foo.__module__, 'unittest.test.testmock.testpatch') 1886 1887 with patch.object(foo, '__annotations__', dict([('s', 1, )])): 1888 self.assertEqual(foo.__annotations__, dict([('s', 1, )])) 1889 self.assertEqual(foo.__annotations__, dict()) 1890 1891 def foo(*a, x=0): 1892 return x 1893 with patch.object(foo, '__kwdefaults__', dict([('x', 1, )])): 1894 self.assertEqual(foo(), 1) 1895 self.assertEqual(foo(), 0) 1896 1897 def test_patch_orderdict(self): 1898 foo = OrderedDict() 1899 foo['a'] = object() 1900 foo['b'] = 'python' 1901 1902 original = foo.copy() 1903 update_values = list(zip('cdefghijklmnopqrstuvwxyz', range(26))) 1904 patched_values = list(foo.items()) + update_values 1905 1906 with patch.dict(foo, OrderedDict(update_values)): 1907 self.assertEqual(list(foo.items()), patched_values) 1908 1909 self.assertEqual(foo, original) 1910 1911 with patch.dict(foo, update_values): 1912 self.assertEqual(list(foo.items()), patched_values) 1913 1914 self.assertEqual(foo, original) 1915 1916 def test_dotted_but_module_not_loaded(self): 1917 # This exercises the AttributeError branch of _dot_lookup. 1918 1919 # make sure it's there 1920 import unittest.test.testmock.support 1921 # now make sure it's not: 1922 with patch.dict('sys.modules'): 1923 del sys.modules['unittest.test.testmock.support'] 1924 del sys.modules['unittest.test.testmock'] 1925 del sys.modules['unittest.test'] 1926 del sys.modules['unittest'] 1927 1928 # now make sure we can patch based on a dotted path: 1929 @patch('unittest.test.testmock.support.X') 1930 def test(mock): 1931 pass 1932 test() 1933 1934 1935 def test_invalid_target(self): 1936 with self.assertRaises(TypeError): 1937 patch('') 1938 1939 1940 def test_cant_set_kwargs_when_passing_a_mock(self): 1941 @patch('unittest.test.testmock.support.X', new=object(), x=1) 1942 def test(): pass 1943 with self.assertRaises(TypeError): 1944 test() 1945 1946 1947if __name__ == '__main__': 1948 unittest.main() 1949