1import copy 2import re 3import sys 4import tempfile 5 6from test.support import ALWAYS_EQ 7import unittest 8from unittest.test.testmock.support import is_instance 9from unittest import mock 10from unittest.mock import ( 11 call, DEFAULT, patch, sentinel, 12 MagicMock, Mock, NonCallableMock, 13 NonCallableMagicMock, AsyncMock, _Call, _CallList, 14 create_autospec, InvalidSpecError 15) 16 17 18class Iter(object): 19 def __init__(self): 20 self.thing = iter(['this', 'is', 'an', 'iter']) 21 22 def __iter__(self): 23 return self 24 25 def next(self): 26 return next(self.thing) 27 28 __next__ = next 29 30 31class Something(object): 32 def meth(self, a, b, c, d=None): pass 33 34 @classmethod 35 def cmeth(cls, a, b, c, d=None): pass 36 37 @staticmethod 38 def smeth(a, b, c, d=None): pass 39 40 41class Typos(): 42 autospect = None 43 auto_spec = None 44 set_spec = None 45 46 47def something(a): pass 48 49 50class MockTest(unittest.TestCase): 51 52 def test_all(self): 53 # if __all__ is badly defined then import * will raise an error 54 # We have to exec it because you can't import * inside a method 55 # in Python 3 56 exec("from unittest.mock import *") 57 58 59 def test_constructor(self): 60 mock = Mock() 61 62 self.assertFalse(mock.called, "called not initialised correctly") 63 self.assertEqual(mock.call_count, 0, 64 "call_count not initialised correctly") 65 self.assertTrue(is_instance(mock.return_value, Mock), 66 "return_value not initialised correctly") 67 68 self.assertEqual(mock.call_args, None, 69 "call_args not initialised correctly") 70 self.assertEqual(mock.call_args_list, [], 71 "call_args_list not initialised correctly") 72 self.assertEqual(mock.method_calls, [], 73 "method_calls not initialised correctly") 74 75 # Can't use hasattr for this test as it always returns True on a mock 76 self.assertNotIn('_items', mock.__dict__, 77 "default mock should not have '_items' attribute") 78 79 self.assertIsNone(mock._mock_parent, 80 "parent not initialised correctly") 81 self.assertIsNone(mock._mock_methods, 82 "methods not initialised correctly") 83 self.assertEqual(mock._mock_children, {}, 84 "children not initialised incorrectly") 85 86 87 def test_return_value_in_constructor(self): 88 mock = Mock(return_value=None) 89 self.assertIsNone(mock.return_value, 90 "return value in constructor not honoured") 91 92 93 def test_change_return_value_via_delegate(self): 94 def f(): pass 95 mock = create_autospec(f) 96 mock.mock.return_value = 1 97 self.assertEqual(mock(), 1) 98 99 100 def test_change_side_effect_via_delegate(self): 101 def f(): pass 102 mock = create_autospec(f) 103 mock.mock.side_effect = TypeError() 104 with self.assertRaises(TypeError): 105 mock() 106 107 108 def test_repr(self): 109 mock = Mock(name='foo') 110 self.assertIn('foo', repr(mock)) 111 self.assertIn("'%s'" % id(mock), repr(mock)) 112 113 mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')] 114 for mock, name in mocks: 115 self.assertIn('%s.bar' % name, repr(mock.bar)) 116 self.assertIn('%s.foo()' % name, repr(mock.foo())) 117 self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing)) 118 self.assertIn('%s()' % name, repr(mock())) 119 self.assertIn('%s()()' % name, repr(mock()())) 120 self.assertIn('%s()().foo.bar.baz().bing' % name, 121 repr(mock()().foo.bar.baz().bing)) 122 123 124 def test_repr_with_spec(self): 125 class X(object): 126 pass 127 128 mock = Mock(spec=X) 129 self.assertIn(" spec='X' ", repr(mock)) 130 131 mock = Mock(spec=X()) 132 self.assertIn(" spec='X' ", repr(mock)) 133 134 mock = Mock(spec_set=X) 135 self.assertIn(" spec_set='X' ", repr(mock)) 136 137 mock = Mock(spec_set=X()) 138 self.assertIn(" spec_set='X' ", repr(mock)) 139 140 mock = Mock(spec=X, name='foo') 141 self.assertIn(" spec='X' ", repr(mock)) 142 self.assertIn(" name='foo' ", repr(mock)) 143 144 mock = Mock(name='foo') 145 self.assertNotIn("spec", repr(mock)) 146 147 mock = Mock() 148 self.assertNotIn("spec", repr(mock)) 149 150 mock = Mock(spec=['foo']) 151 self.assertNotIn("spec", repr(mock)) 152 153 154 def test_side_effect(self): 155 mock = Mock() 156 157 def effect(*args, **kwargs): 158 raise SystemError('kablooie') 159 160 mock.side_effect = effect 161 self.assertRaises(SystemError, mock, 1, 2, fish=3) 162 mock.assert_called_with(1, 2, fish=3) 163 164 results = [1, 2, 3] 165 def effect(): 166 return results.pop() 167 mock.side_effect = effect 168 169 self.assertEqual([mock(), mock(), mock()], [3, 2, 1], 170 "side effect not used correctly") 171 172 mock = Mock(side_effect=sentinel.SideEffect) 173 self.assertEqual(mock.side_effect, sentinel.SideEffect, 174 "side effect in constructor not used") 175 176 def side_effect(): 177 return DEFAULT 178 mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN) 179 self.assertEqual(mock(), sentinel.RETURN) 180 181 def test_autospec_side_effect(self): 182 # Test for issue17826 183 results = [1, 2, 3] 184 def effect(): 185 return results.pop() 186 def f(): pass 187 188 mock = create_autospec(f) 189 mock.side_effect = [1, 2, 3] 190 self.assertEqual([mock(), mock(), mock()], [1, 2, 3], 191 "side effect not used correctly in create_autospec") 192 # Test where side effect is a callable 193 results = [1, 2, 3] 194 mock = create_autospec(f) 195 mock.side_effect = effect 196 self.assertEqual([mock(), mock(), mock()], [3, 2, 1], 197 "callable side effect not used correctly") 198 199 def test_autospec_side_effect_exception(self): 200 # Test for issue 23661 201 def f(): pass 202 203 mock = create_autospec(f) 204 mock.side_effect = ValueError('Bazinga!') 205 self.assertRaisesRegex(ValueError, 'Bazinga!', mock) 206 207 208 def test_autospec_mock(self): 209 class A(object): 210 class B(object): 211 C = None 212 213 with mock.patch.object(A, 'B'): 214 with self.assertRaisesRegex(InvalidSpecError, 215 "Cannot autospec attr 'B' from target <MagicMock spec='A'"): 216 create_autospec(A).B 217 with self.assertRaisesRegex(InvalidSpecError, 218 "Cannot autospec attr 'B' from target 'A'"): 219 mock.patch.object(A, 'B', autospec=True).start() 220 with self.assertRaisesRegex(InvalidSpecError, 221 "Cannot autospec attr 'C' as the patch target "): 222 mock.patch.object(A.B, 'C', autospec=True).start() 223 with self.assertRaisesRegex(InvalidSpecError, 224 "Cannot spec attr 'B' as the spec "): 225 mock.patch.object(A, 'B', spec=A.B).start() 226 with self.assertRaisesRegex(InvalidSpecError, 227 "Cannot spec attr 'B' as the spec_set "): 228 mock.patch.object(A, 'B', spec_set=A.B).start() 229 with self.assertRaisesRegex(InvalidSpecError, 230 "Cannot spec attr 'B' as the spec_set "): 231 mock.patch.object(A, 'B', spec_set=A.B).start() 232 with self.assertRaisesRegex(InvalidSpecError, "Cannot spec a Mock object."): 233 mock.Mock(A.B) 234 with mock.patch('builtins.open', mock.mock_open()): 235 mock.mock_open() # should still be valid with open() mocked 236 237 238 def test_reset_mock(self): 239 parent = Mock() 240 spec = ["something"] 241 mock = Mock(name="child", parent=parent, spec=spec) 242 mock(sentinel.Something, something=sentinel.SomethingElse) 243 something = mock.something 244 mock.something() 245 mock.side_effect = sentinel.SideEffect 246 return_value = mock.return_value 247 return_value() 248 249 mock.reset_mock() 250 251 self.assertEqual(mock._mock_name, "child", 252 "name incorrectly reset") 253 self.assertEqual(mock._mock_parent, parent, 254 "parent incorrectly reset") 255 self.assertEqual(mock._mock_methods, spec, 256 "methods incorrectly reset") 257 258 self.assertFalse(mock.called, "called not reset") 259 self.assertEqual(mock.call_count, 0, "call_count not reset") 260 self.assertEqual(mock.call_args, None, "call_args not reset") 261 self.assertEqual(mock.call_args_list, [], "call_args_list not reset") 262 self.assertEqual(mock.method_calls, [], 263 "method_calls not initialised correctly: %r != %r" % 264 (mock.method_calls, [])) 265 self.assertEqual(mock.mock_calls, []) 266 267 self.assertEqual(mock.side_effect, sentinel.SideEffect, 268 "side_effect incorrectly reset") 269 self.assertEqual(mock.return_value, return_value, 270 "return_value incorrectly reset") 271 self.assertFalse(return_value.called, "return value mock not reset") 272 self.assertEqual(mock._mock_children, {'something': something}, 273 "children reset incorrectly") 274 self.assertEqual(mock.something, something, 275 "children incorrectly cleared") 276 self.assertFalse(mock.something.called, "child not reset") 277 278 279 def test_reset_mock_recursion(self): 280 mock = Mock() 281 mock.return_value = mock 282 283 # used to cause recursion 284 mock.reset_mock() 285 286 def test_reset_mock_on_mock_open_issue_18622(self): 287 a = mock.mock_open() 288 a.reset_mock() 289 290 def test_call(self): 291 mock = Mock() 292 self.assertTrue(is_instance(mock.return_value, Mock), 293 "Default return_value should be a Mock") 294 295 result = mock() 296 self.assertEqual(mock(), result, 297 "different result from consecutive calls") 298 mock.reset_mock() 299 300 ret_val = mock(sentinel.Arg) 301 self.assertTrue(mock.called, "called not set") 302 self.assertEqual(mock.call_count, 1, "call_count incorrect") 303 self.assertEqual(mock.call_args, ((sentinel.Arg,), {}), 304 "call_args not set") 305 self.assertEqual(mock.call_args.args, (sentinel.Arg,), 306 "call_args not set") 307 self.assertEqual(mock.call_args.kwargs, {}, 308 "call_args not set") 309 self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})], 310 "call_args_list not initialised correctly") 311 312 mock.return_value = sentinel.ReturnValue 313 ret_val = mock(sentinel.Arg, key=sentinel.KeyArg) 314 self.assertEqual(ret_val, sentinel.ReturnValue, 315 "incorrect return value") 316 317 self.assertEqual(mock.call_count, 2, "call_count incorrect") 318 self.assertEqual(mock.call_args, 319 ((sentinel.Arg,), {'key': sentinel.KeyArg}), 320 "call_args not set") 321 self.assertEqual(mock.call_args_list, [ 322 ((sentinel.Arg,), {}), 323 ((sentinel.Arg,), {'key': sentinel.KeyArg}) 324 ], 325 "call_args_list not set") 326 327 328 def test_call_args_comparison(self): 329 mock = Mock() 330 mock() 331 mock(sentinel.Arg) 332 mock(kw=sentinel.Kwarg) 333 mock(sentinel.Arg, kw=sentinel.Kwarg) 334 self.assertEqual(mock.call_args_list, [ 335 (), 336 ((sentinel.Arg,),), 337 ({"kw": sentinel.Kwarg},), 338 ((sentinel.Arg,), {"kw": sentinel.Kwarg}) 339 ]) 340 self.assertEqual(mock.call_args, 341 ((sentinel.Arg,), {"kw": sentinel.Kwarg})) 342 self.assertEqual(mock.call_args.args, (sentinel.Arg,)) 343 self.assertEqual(mock.call_args.kwargs, {"kw": sentinel.Kwarg}) 344 345 # Comparing call_args to a long sequence should not raise 346 # an exception. See issue 24857. 347 self.assertFalse(mock.call_args == "a long sequence") 348 349 350 def test_calls_equal_with_any(self): 351 # Check that equality and non-equality is consistent even when 352 # comparing with mock.ANY 353 mm = mock.MagicMock() 354 self.assertTrue(mm == mm) 355 self.assertFalse(mm != mm) 356 self.assertFalse(mm == mock.MagicMock()) 357 self.assertTrue(mm != mock.MagicMock()) 358 self.assertTrue(mm == mock.ANY) 359 self.assertFalse(mm != mock.ANY) 360 self.assertTrue(mock.ANY == mm) 361 self.assertFalse(mock.ANY != mm) 362 self.assertTrue(mm == ALWAYS_EQ) 363 self.assertFalse(mm != ALWAYS_EQ) 364 365 call1 = mock.call(mock.MagicMock()) 366 call2 = mock.call(mock.ANY) 367 self.assertTrue(call1 == call2) 368 self.assertFalse(call1 != call2) 369 self.assertTrue(call2 == call1) 370 self.assertFalse(call2 != call1) 371 372 self.assertTrue(call1 == ALWAYS_EQ) 373 self.assertFalse(call1 != ALWAYS_EQ) 374 self.assertFalse(call1 == 1) 375 self.assertTrue(call1 != 1) 376 377 378 def test_assert_called_with(self): 379 mock = Mock() 380 mock() 381 382 # Will raise an exception if it fails 383 mock.assert_called_with() 384 self.assertRaises(AssertionError, mock.assert_called_with, 1) 385 386 mock.reset_mock() 387 self.assertRaises(AssertionError, mock.assert_called_with) 388 389 mock(1, 2, 3, a='fish', b='nothing') 390 mock.assert_called_with(1, 2, 3, a='fish', b='nothing') 391 392 393 def test_assert_called_with_any(self): 394 m = MagicMock() 395 m(MagicMock()) 396 m.assert_called_with(mock.ANY) 397 398 399 def test_assert_called_with_function_spec(self): 400 def f(a, b, c, d=None): pass 401 402 mock = Mock(spec=f) 403 404 mock(1, b=2, c=3) 405 mock.assert_called_with(1, 2, 3) 406 mock.assert_called_with(a=1, b=2, c=3) 407 self.assertRaises(AssertionError, mock.assert_called_with, 408 1, b=3, c=2) 409 # Expected call doesn't match the spec's signature 410 with self.assertRaises(AssertionError) as cm: 411 mock.assert_called_with(e=8) 412 self.assertIsInstance(cm.exception.__cause__, TypeError) 413 414 415 def test_assert_called_with_method_spec(self): 416 def _check(mock): 417 mock(1, b=2, c=3) 418 mock.assert_called_with(1, 2, 3) 419 mock.assert_called_with(a=1, b=2, c=3) 420 self.assertRaises(AssertionError, mock.assert_called_with, 421 1, b=3, c=2) 422 423 mock = Mock(spec=Something().meth) 424 _check(mock) 425 mock = Mock(spec=Something.cmeth) 426 _check(mock) 427 mock = Mock(spec=Something().cmeth) 428 _check(mock) 429 mock = Mock(spec=Something.smeth) 430 _check(mock) 431 mock = Mock(spec=Something().smeth) 432 _check(mock) 433 434 435 def test_assert_called_exception_message(self): 436 msg = "Expected '{0}' to have been called" 437 with self.assertRaisesRegex(AssertionError, msg.format('mock')): 438 Mock().assert_called() 439 with self.assertRaisesRegex(AssertionError, msg.format('test_name')): 440 Mock(name="test_name").assert_called() 441 442 443 def test_assert_called_once_with(self): 444 mock = Mock() 445 mock() 446 447 # Will raise an exception if it fails 448 mock.assert_called_once_with() 449 450 mock() 451 self.assertRaises(AssertionError, mock.assert_called_once_with) 452 453 mock.reset_mock() 454 self.assertRaises(AssertionError, mock.assert_called_once_with) 455 456 mock('foo', 'bar', baz=2) 457 mock.assert_called_once_with('foo', 'bar', baz=2) 458 459 mock.reset_mock() 460 mock('foo', 'bar', baz=2) 461 self.assertRaises( 462 AssertionError, 463 lambda: mock.assert_called_once_with('bob', 'bar', baz=2) 464 ) 465 466 def test_assert_called_once_with_call_list(self): 467 m = Mock() 468 m(1) 469 m(2) 470 self.assertRaisesRegex(AssertionError, 471 re.escape("Calls: [call(1), call(2)]"), 472 lambda: m.assert_called_once_with(2)) 473 474 475 def test_assert_called_once_with_function_spec(self): 476 def f(a, b, c, d=None): pass 477 478 mock = Mock(spec=f) 479 480 mock(1, b=2, c=3) 481 mock.assert_called_once_with(1, 2, 3) 482 mock.assert_called_once_with(a=1, b=2, c=3) 483 self.assertRaises(AssertionError, mock.assert_called_once_with, 484 1, b=3, c=2) 485 # Expected call doesn't match the spec's signature 486 with self.assertRaises(AssertionError) as cm: 487 mock.assert_called_once_with(e=8) 488 self.assertIsInstance(cm.exception.__cause__, TypeError) 489 # Mock called more than once => always fails 490 mock(4, 5, 6) 491 self.assertRaises(AssertionError, mock.assert_called_once_with, 492 1, 2, 3) 493 self.assertRaises(AssertionError, mock.assert_called_once_with, 494 4, 5, 6) 495 496 497 def test_attribute_access_returns_mocks(self): 498 mock = Mock() 499 something = mock.something 500 self.assertTrue(is_instance(something, Mock), "attribute isn't a mock") 501 self.assertEqual(mock.something, something, 502 "different attributes returned for same name") 503 504 # Usage example 505 mock = Mock() 506 mock.something.return_value = 3 507 508 self.assertEqual(mock.something(), 3, "method returned wrong value") 509 self.assertTrue(mock.something.called, 510 "method didn't record being called") 511 512 513 def test_attributes_have_name_and_parent_set(self): 514 mock = Mock() 515 something = mock.something 516 517 self.assertEqual(something._mock_name, "something", 518 "attribute name not set correctly") 519 self.assertEqual(something._mock_parent, mock, 520 "attribute parent not set correctly") 521 522 523 def test_method_calls_recorded(self): 524 mock = Mock() 525 mock.something(3, fish=None) 526 mock.something_else.something(6, cake=sentinel.Cake) 527 528 self.assertEqual(mock.something_else.method_calls, 529 [("something", (6,), {'cake': sentinel.Cake})], 530 "method calls not recorded correctly") 531 self.assertEqual(mock.method_calls, [ 532 ("something", (3,), {'fish': None}), 533 ("something_else.something", (6,), {'cake': sentinel.Cake}) 534 ], 535 "method calls not recorded correctly") 536 537 538 def test_method_calls_compare_easily(self): 539 mock = Mock() 540 mock.something() 541 self.assertEqual(mock.method_calls, [('something',)]) 542 self.assertEqual(mock.method_calls, [('something', (), {})]) 543 544 mock = Mock() 545 mock.something('different') 546 self.assertEqual(mock.method_calls, [('something', ('different',))]) 547 self.assertEqual(mock.method_calls, 548 [('something', ('different',), {})]) 549 550 mock = Mock() 551 mock.something(x=1) 552 self.assertEqual(mock.method_calls, [('something', {'x': 1})]) 553 self.assertEqual(mock.method_calls, [('something', (), {'x': 1})]) 554 555 mock = Mock() 556 mock.something('different', some='more') 557 self.assertEqual(mock.method_calls, [ 558 ('something', ('different',), {'some': 'more'}) 559 ]) 560 561 562 def test_only_allowed_methods_exist(self): 563 for spec in ['something'], ('something',): 564 for arg in 'spec', 'spec_set': 565 mock = Mock(**{arg: spec}) 566 567 # this should be allowed 568 mock.something 569 self.assertRaisesRegex( 570 AttributeError, 571 "Mock object has no attribute 'something_else'", 572 getattr, mock, 'something_else' 573 ) 574 575 576 def test_from_spec(self): 577 class Something(object): 578 x = 3 579 __something__ = None 580 def y(self): pass 581 582 def test_attributes(mock): 583 # should work 584 mock.x 585 mock.y 586 mock.__something__ 587 self.assertRaisesRegex( 588 AttributeError, 589 "Mock object has no attribute 'z'", 590 getattr, mock, 'z' 591 ) 592 self.assertRaisesRegex( 593 AttributeError, 594 "Mock object has no attribute '__foobar__'", 595 getattr, mock, '__foobar__' 596 ) 597 598 test_attributes(Mock(spec=Something)) 599 test_attributes(Mock(spec=Something())) 600 601 602 def test_wraps_calls(self): 603 real = Mock() 604 605 mock = Mock(wraps=real) 606 self.assertEqual(mock(), real()) 607 608 real.reset_mock() 609 610 mock(1, 2, fish=3) 611 real.assert_called_with(1, 2, fish=3) 612 613 614 def test_wraps_prevents_automatic_creation_of_mocks(self): 615 class Real(object): 616 pass 617 618 real = Real() 619 mock = Mock(wraps=real) 620 621 self.assertRaises(AttributeError, lambda: mock.new_attr()) 622 623 624 def test_wraps_call_with_nondefault_return_value(self): 625 real = Mock() 626 627 mock = Mock(wraps=real) 628 mock.return_value = 3 629 630 self.assertEqual(mock(), 3) 631 self.assertFalse(real.called) 632 633 634 def test_wraps_attributes(self): 635 class Real(object): 636 attribute = Mock() 637 638 real = Real() 639 640 mock = Mock(wraps=real) 641 self.assertEqual(mock.attribute(), real.attribute()) 642 self.assertRaises(AttributeError, lambda: mock.fish) 643 644 self.assertNotEqual(mock.attribute, real.attribute) 645 result = mock.attribute.frog(1, 2, fish=3) 646 Real.attribute.frog.assert_called_with(1, 2, fish=3) 647 self.assertEqual(result, Real.attribute.frog()) 648 649 650 def test_customize_wrapped_object_with_side_effect_iterable_with_default(self): 651 class Real(object): 652 def method(self): 653 return sentinel.ORIGINAL_VALUE 654 655 real = Real() 656 mock = Mock(wraps=real) 657 mock.method.side_effect = [sentinel.VALUE1, DEFAULT] 658 659 self.assertEqual(mock.method(), sentinel.VALUE1) 660 self.assertEqual(mock.method(), sentinel.ORIGINAL_VALUE) 661 self.assertRaises(StopIteration, mock.method) 662 663 664 def test_customize_wrapped_object_with_side_effect_iterable(self): 665 class Real(object): 666 def method(self): pass 667 668 real = Real() 669 mock = Mock(wraps=real) 670 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2] 671 672 self.assertEqual(mock.method(), sentinel.VALUE1) 673 self.assertEqual(mock.method(), sentinel.VALUE2) 674 self.assertRaises(StopIteration, mock.method) 675 676 677 def test_customize_wrapped_object_with_side_effect_exception(self): 678 class Real(object): 679 def method(self): pass 680 681 real = Real() 682 mock = Mock(wraps=real) 683 mock.method.side_effect = RuntimeError 684 685 self.assertRaises(RuntimeError, mock.method) 686 687 688 def test_customize_wrapped_object_with_side_effect_function(self): 689 class Real(object): 690 def method(self): pass 691 def side_effect(): 692 return sentinel.VALUE 693 694 real = Real() 695 mock = Mock(wraps=real) 696 mock.method.side_effect = side_effect 697 698 self.assertEqual(mock.method(), sentinel.VALUE) 699 700 701 def test_customize_wrapped_object_with_return_value(self): 702 class Real(object): 703 def method(self): pass 704 705 real = Real() 706 mock = Mock(wraps=real) 707 mock.method.return_value = sentinel.VALUE 708 709 self.assertEqual(mock.method(), sentinel.VALUE) 710 711 712 def test_customize_wrapped_object_with_return_value_and_side_effect(self): 713 # side_effect should always take precedence over return_value. 714 class Real(object): 715 def method(self): pass 716 717 real = Real() 718 mock = Mock(wraps=real) 719 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2] 720 mock.method.return_value = sentinel.WRONG_VALUE 721 722 self.assertEqual(mock.method(), sentinel.VALUE1) 723 self.assertEqual(mock.method(), sentinel.VALUE2) 724 self.assertRaises(StopIteration, mock.method) 725 726 727 def test_customize_wrapped_object_with_return_value_and_side_effect2(self): 728 # side_effect can return DEFAULT to default to return_value 729 class Real(object): 730 def method(self): pass 731 732 real = Real() 733 mock = Mock(wraps=real) 734 mock.method.side_effect = lambda: DEFAULT 735 mock.method.return_value = sentinel.VALUE 736 737 self.assertEqual(mock.method(), sentinel.VALUE) 738 739 740 def test_customize_wrapped_object_with_return_value_and_side_effect_default(self): 741 class Real(object): 742 def method(self): pass 743 744 real = Real() 745 mock = Mock(wraps=real) 746 mock.method.side_effect = [sentinel.VALUE1, DEFAULT] 747 mock.method.return_value = sentinel.RETURN 748 749 self.assertEqual(mock.method(), sentinel.VALUE1) 750 self.assertEqual(mock.method(), sentinel.RETURN) 751 self.assertRaises(StopIteration, mock.method) 752 753 754 def test_magic_method_wraps_dict(self): 755 # bpo-25597: MagicMock with wrap doesn't call wrapped object's 756 # method for magic methods with default values. 757 data = {'foo': 'bar'} 758 759 wrapped_dict = MagicMock(wraps=data) 760 self.assertEqual(wrapped_dict.get('foo'), 'bar') 761 # Accessing key gives a MagicMock 762 self.assertIsInstance(wrapped_dict['foo'], MagicMock) 763 # __contains__ method has a default value of False 764 self.assertFalse('foo' in wrapped_dict) 765 766 # return_value is non-sentinel and takes precedence over wrapped value. 767 wrapped_dict.get.return_value = 'return_value' 768 self.assertEqual(wrapped_dict.get('foo'), 'return_value') 769 770 # return_value is sentinel and hence wrapped value is returned. 771 wrapped_dict.get.return_value = sentinel.DEFAULT 772 self.assertEqual(wrapped_dict.get('foo'), 'bar') 773 774 self.assertEqual(wrapped_dict.get('baz'), None) 775 self.assertIsInstance(wrapped_dict['baz'], MagicMock) 776 self.assertFalse('bar' in wrapped_dict) 777 778 data['baz'] = 'spam' 779 self.assertEqual(wrapped_dict.get('baz'), 'spam') 780 self.assertIsInstance(wrapped_dict['baz'], MagicMock) 781 self.assertFalse('bar' in wrapped_dict) 782 783 del data['baz'] 784 self.assertEqual(wrapped_dict.get('baz'), None) 785 786 787 def test_magic_method_wraps_class(self): 788 789 class Foo: 790 791 def __getitem__(self, index): 792 return index 793 794 def __custom_method__(self): 795 return "foo" 796 797 798 klass = MagicMock(wraps=Foo) 799 obj = klass() 800 self.assertEqual(obj.__getitem__(2), 2) 801 self.assertEqual(obj[2], 2) 802 self.assertEqual(obj.__custom_method__(), "foo") 803 804 805 def test_exceptional_side_effect(self): 806 mock = Mock(side_effect=AttributeError) 807 self.assertRaises(AttributeError, mock) 808 809 mock = Mock(side_effect=AttributeError('foo')) 810 self.assertRaises(AttributeError, mock) 811 812 813 def test_baseexceptional_side_effect(self): 814 mock = Mock(side_effect=KeyboardInterrupt) 815 self.assertRaises(KeyboardInterrupt, mock) 816 817 mock = Mock(side_effect=KeyboardInterrupt('foo')) 818 self.assertRaises(KeyboardInterrupt, mock) 819 820 821 def test_assert_called_with_message(self): 822 mock = Mock() 823 self.assertRaisesRegex(AssertionError, 'not called', 824 mock.assert_called_with) 825 826 827 def test_assert_called_once_with_message(self): 828 mock = Mock(name='geoffrey') 829 self.assertRaisesRegex(AssertionError, 830 r"Expected 'geoffrey' to be called once\.", 831 mock.assert_called_once_with) 832 833 834 def test__name__(self): 835 mock = Mock() 836 self.assertRaises(AttributeError, lambda: mock.__name__) 837 838 mock.__name__ = 'foo' 839 self.assertEqual(mock.__name__, 'foo') 840 841 842 def test_spec_list_subclass(self): 843 class Sub(list): 844 pass 845 mock = Mock(spec=Sub(['foo'])) 846 847 mock.append(3) 848 mock.append.assert_called_with(3) 849 self.assertRaises(AttributeError, getattr, mock, 'foo') 850 851 852 def test_spec_class(self): 853 class X(object): 854 pass 855 856 mock = Mock(spec=X) 857 self.assertIsInstance(mock, X) 858 859 mock = Mock(spec=X()) 860 self.assertIsInstance(mock, X) 861 862 self.assertIs(mock.__class__, X) 863 self.assertEqual(Mock().__class__.__name__, 'Mock') 864 865 mock = Mock(spec_set=X) 866 self.assertIsInstance(mock, X) 867 868 mock = Mock(spec_set=X()) 869 self.assertIsInstance(mock, X) 870 871 872 def test_spec_class_no_object_base(self): 873 class X: 874 pass 875 876 mock = Mock(spec=X) 877 self.assertIsInstance(mock, X) 878 879 mock = Mock(spec=X()) 880 self.assertIsInstance(mock, X) 881 882 self.assertIs(mock.__class__, X) 883 self.assertEqual(Mock().__class__.__name__, 'Mock') 884 885 mock = Mock(spec_set=X) 886 self.assertIsInstance(mock, X) 887 888 mock = Mock(spec_set=X()) 889 self.assertIsInstance(mock, X) 890 891 892 def test_setting_attribute_with_spec_set(self): 893 class X(object): 894 y = 3 895 896 mock = Mock(spec=X) 897 mock.x = 'foo' 898 899 mock = Mock(spec_set=X) 900 def set_attr(): 901 mock.x = 'foo' 902 903 mock.y = 'foo' 904 self.assertRaises(AttributeError, set_attr) 905 906 907 def test_copy(self): 908 current = sys.getrecursionlimit() 909 self.addCleanup(sys.setrecursionlimit, current) 910 911 # can't use sys.maxint as this doesn't exist in Python 3 912 sys.setrecursionlimit(int(10e8)) 913 # this segfaults without the fix in place 914 copy.copy(Mock()) 915 916 917 def test_subclass_with_properties(self): 918 class SubClass(Mock): 919 def _get(self): 920 return 3 921 def _set(self, value): 922 raise NameError('strange error') 923 some_attribute = property(_get, _set) 924 925 s = SubClass(spec_set=SubClass) 926 self.assertEqual(s.some_attribute, 3) 927 928 def test(): 929 s.some_attribute = 3 930 self.assertRaises(NameError, test) 931 932 def test(): 933 s.foo = 'bar' 934 self.assertRaises(AttributeError, test) 935 936 937 def test_setting_call(self): 938 mock = Mock() 939 def __call__(self, a): 940 self._increment_mock_call(a) 941 return self._mock_call(a) 942 943 type(mock).__call__ = __call__ 944 mock('one') 945 mock.assert_called_with('one') 946 947 self.assertRaises(TypeError, mock, 'one', 'two') 948 949 950 def test_dir(self): 951 mock = Mock() 952 attrs = set(dir(mock)) 953 type_attrs = set([m for m in dir(Mock) if not m.startswith('_')]) 954 955 # all public attributes from the type are included 956 self.assertEqual(set(), type_attrs - attrs) 957 958 # creates these attributes 959 mock.a, mock.b 960 self.assertIn('a', dir(mock)) 961 self.assertIn('b', dir(mock)) 962 963 # instance attributes 964 mock.c = mock.d = None 965 self.assertIn('c', dir(mock)) 966 self.assertIn('d', dir(mock)) 967 968 # magic methods 969 mock.__iter__ = lambda s: iter([]) 970 self.assertIn('__iter__', dir(mock)) 971 972 973 def test_dir_from_spec(self): 974 mock = Mock(spec=unittest.TestCase) 975 testcase_attrs = set(dir(unittest.TestCase)) 976 attrs = set(dir(mock)) 977 978 # all attributes from the spec are included 979 self.assertEqual(set(), testcase_attrs - attrs) 980 981 # shadow a sys attribute 982 mock.version = 3 983 self.assertEqual(dir(mock).count('version'), 1) 984 985 986 def test_filter_dir(self): 987 patcher = patch.object(mock, 'FILTER_DIR', False) 988 patcher.start() 989 try: 990 attrs = set(dir(Mock())) 991 type_attrs = set(dir(Mock)) 992 993 # ALL attributes from the type are included 994 self.assertEqual(set(), type_attrs - attrs) 995 finally: 996 patcher.stop() 997 998 999 def test_dir_does_not_include_deleted_attributes(self): 1000 mock = Mock() 1001 mock.child.return_value = 1 1002 1003 self.assertIn('child', dir(mock)) 1004 del mock.child 1005 self.assertNotIn('child', dir(mock)) 1006 1007 1008 def test_configure_mock(self): 1009 mock = Mock(foo='bar') 1010 self.assertEqual(mock.foo, 'bar') 1011 1012 mock = MagicMock(foo='bar') 1013 self.assertEqual(mock.foo, 'bar') 1014 1015 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33, 1016 'foo': MagicMock()} 1017 mock = Mock(**kwargs) 1018 self.assertRaises(KeyError, mock) 1019 self.assertEqual(mock.foo.bar(), 33) 1020 self.assertIsInstance(mock.foo, MagicMock) 1021 1022 mock = Mock() 1023 mock.configure_mock(**kwargs) 1024 self.assertRaises(KeyError, mock) 1025 self.assertEqual(mock.foo.bar(), 33) 1026 self.assertIsInstance(mock.foo, MagicMock) 1027 1028 1029 def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs): 1030 # needed because assertRaisesRegex doesn't work easily with newlines 1031 with self.assertRaises(exception) as context: 1032 func(*args, **kwargs) 1033 msg = str(context.exception) 1034 self.assertEqual(msg, message) 1035 1036 1037 def test_assert_called_with_failure_message(self): 1038 mock = NonCallableMock() 1039 1040 actual = 'not called.' 1041 expected = "mock(1, '2', 3, bar='foo')" 1042 message = 'expected call not found.\nExpected: %s\nActual: %s' 1043 self.assertRaisesWithMsg( 1044 AssertionError, message % (expected, actual), 1045 mock.assert_called_with, 1, '2', 3, bar='foo' 1046 ) 1047 1048 mock.foo(1, '2', 3, foo='foo') 1049 1050 1051 asserters = [ 1052 mock.foo.assert_called_with, mock.foo.assert_called_once_with 1053 ] 1054 for meth in asserters: 1055 actual = "foo(1, '2', 3, foo='foo')" 1056 expected = "foo(1, '2', 3, bar='foo')" 1057 message = 'expected call not found.\nExpected: %s\nActual: %s' 1058 self.assertRaisesWithMsg( 1059 AssertionError, message % (expected, actual), 1060 meth, 1, '2', 3, bar='foo' 1061 ) 1062 1063 # just kwargs 1064 for meth in asserters: 1065 actual = "foo(1, '2', 3, foo='foo')" 1066 expected = "foo(bar='foo')" 1067 message = 'expected call not found.\nExpected: %s\nActual: %s' 1068 self.assertRaisesWithMsg( 1069 AssertionError, message % (expected, actual), 1070 meth, bar='foo' 1071 ) 1072 1073 # just args 1074 for meth in asserters: 1075 actual = "foo(1, '2', 3, foo='foo')" 1076 expected = "foo(1, 2, 3)" 1077 message = 'expected call not found.\nExpected: %s\nActual: %s' 1078 self.assertRaisesWithMsg( 1079 AssertionError, message % (expected, actual), 1080 meth, 1, 2, 3 1081 ) 1082 1083 # empty 1084 for meth in asserters: 1085 actual = "foo(1, '2', 3, foo='foo')" 1086 expected = "foo()" 1087 message = 'expected call not found.\nExpected: %s\nActual: %s' 1088 self.assertRaisesWithMsg( 1089 AssertionError, message % (expected, actual), meth 1090 ) 1091 1092 1093 def test_mock_calls(self): 1094 mock = MagicMock() 1095 1096 # need to do this because MagicMock.mock_calls used to just return 1097 # a MagicMock which also returned a MagicMock when __eq__ was called 1098 self.assertIs(mock.mock_calls == [], True) 1099 1100 mock = MagicMock() 1101 mock() 1102 expected = [('', (), {})] 1103 self.assertEqual(mock.mock_calls, expected) 1104 1105 mock.foo() 1106 expected.append(call.foo()) 1107 self.assertEqual(mock.mock_calls, expected) 1108 # intermediate mock_calls work too 1109 self.assertEqual(mock.foo.mock_calls, [('', (), {})]) 1110 1111 mock = MagicMock() 1112 mock().foo(1, 2, 3, a=4, b=5) 1113 expected = [ 1114 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5)) 1115 ] 1116 self.assertEqual(mock.mock_calls, expected) 1117 self.assertEqual(mock.return_value.foo.mock_calls, 1118 [('', (1, 2, 3), dict(a=4, b=5))]) 1119 self.assertEqual(mock.return_value.mock_calls, 1120 [('foo', (1, 2, 3), dict(a=4, b=5))]) 1121 1122 mock = MagicMock() 1123 mock().foo.bar().baz() 1124 expected = [ 1125 ('', (), {}), ('().foo.bar', (), {}), 1126 ('().foo.bar().baz', (), {}) 1127 ] 1128 self.assertEqual(mock.mock_calls, expected) 1129 self.assertEqual(mock().mock_calls, 1130 call.foo.bar().baz().call_list()) 1131 1132 for kwargs in dict(), dict(name='bar'): 1133 mock = MagicMock(**kwargs) 1134 int(mock.foo) 1135 expected = [('foo.__int__', (), {})] 1136 self.assertEqual(mock.mock_calls, expected) 1137 1138 mock = MagicMock(**kwargs) 1139 mock.a()() 1140 expected = [('a', (), {}), ('a()', (), {})] 1141 self.assertEqual(mock.mock_calls, expected) 1142 self.assertEqual(mock.a().mock_calls, [call()]) 1143 1144 mock = MagicMock(**kwargs) 1145 mock(1)(2)(3) 1146 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list()) 1147 self.assertEqual(mock().mock_calls, call(2)(3).call_list()) 1148 self.assertEqual(mock()().mock_calls, call(3).call_list()) 1149 1150 mock = MagicMock(**kwargs) 1151 mock(1)(2)(3).a.b.c(4) 1152 self.assertEqual(mock.mock_calls, 1153 call(1)(2)(3).a.b.c(4).call_list()) 1154 self.assertEqual(mock().mock_calls, 1155 call(2)(3).a.b.c(4).call_list()) 1156 self.assertEqual(mock()().mock_calls, 1157 call(3).a.b.c(4).call_list()) 1158 1159 mock = MagicMock(**kwargs) 1160 int(mock().foo.bar().baz()) 1161 last_call = ('().foo.bar().baz().__int__', (), {}) 1162 self.assertEqual(mock.mock_calls[-1], last_call) 1163 self.assertEqual(mock().mock_calls, 1164 call.foo.bar().baz().__int__().call_list()) 1165 self.assertEqual(mock().foo.bar().mock_calls, 1166 call.baz().__int__().call_list()) 1167 self.assertEqual(mock().foo.bar().baz.mock_calls, 1168 call().__int__().call_list()) 1169 1170 1171 def test_child_mock_call_equal(self): 1172 m = Mock() 1173 result = m() 1174 result.wibble() 1175 # parent looks like this: 1176 self.assertEqual(m.mock_calls, [call(), call().wibble()]) 1177 # but child should look like this: 1178 self.assertEqual(result.mock_calls, [call.wibble()]) 1179 1180 1181 def test_mock_call_not_equal_leaf(self): 1182 m = Mock() 1183 m.foo().something() 1184 self.assertNotEqual(m.mock_calls[1], call.foo().different()) 1185 self.assertEqual(m.mock_calls[0], call.foo()) 1186 1187 1188 def test_mock_call_not_equal_non_leaf(self): 1189 m = Mock() 1190 m.foo().bar() 1191 self.assertNotEqual(m.mock_calls[1], call.baz().bar()) 1192 self.assertNotEqual(m.mock_calls[0], call.baz()) 1193 1194 1195 def test_mock_call_not_equal_non_leaf_params_different(self): 1196 m = Mock() 1197 m.foo(x=1).bar() 1198 # This isn't ideal, but there's no way to fix it without breaking backwards compatibility: 1199 self.assertEqual(m.mock_calls[1], call.foo(x=2).bar()) 1200 1201 1202 def test_mock_call_not_equal_non_leaf_attr(self): 1203 m = Mock() 1204 m.foo.bar() 1205 self.assertNotEqual(m.mock_calls[0], call.baz.bar()) 1206 1207 1208 def test_mock_call_not_equal_non_leaf_call_versus_attr(self): 1209 m = Mock() 1210 m.foo.bar() 1211 self.assertNotEqual(m.mock_calls[0], call.foo().bar()) 1212 1213 1214 def test_mock_call_repr(self): 1215 m = Mock() 1216 m.foo().bar().baz.bob() 1217 self.assertEqual(repr(m.mock_calls[0]), 'call.foo()') 1218 self.assertEqual(repr(m.mock_calls[1]), 'call.foo().bar()') 1219 self.assertEqual(repr(m.mock_calls[2]), 'call.foo().bar().baz.bob()') 1220 1221 1222 def test_mock_call_repr_loop(self): 1223 m = Mock() 1224 m.foo = m 1225 repr(m.foo()) 1226 self.assertRegex(repr(m.foo()), r"<Mock name='mock\(\)' id='\d+'>") 1227 1228 1229 def test_mock_calls_contains(self): 1230 m = Mock() 1231 self.assertFalse([call()] in m.mock_calls) 1232 1233 1234 def test_subclassing(self): 1235 class Subclass(Mock): 1236 pass 1237 1238 mock = Subclass() 1239 self.assertIsInstance(mock.foo, Subclass) 1240 self.assertIsInstance(mock(), Subclass) 1241 1242 class Subclass(Mock): 1243 def _get_child_mock(self, **kwargs): 1244 return Mock(**kwargs) 1245 1246 mock = Subclass() 1247 self.assertNotIsInstance(mock.foo, Subclass) 1248 self.assertNotIsInstance(mock(), Subclass) 1249 1250 1251 def test_arg_lists(self): 1252 mocks = [ 1253 Mock(), 1254 MagicMock(), 1255 NonCallableMock(), 1256 NonCallableMagicMock() 1257 ] 1258 1259 def assert_attrs(mock): 1260 names = 'call_args_list', 'method_calls', 'mock_calls' 1261 for name in names: 1262 attr = getattr(mock, name) 1263 self.assertIsInstance(attr, _CallList) 1264 self.assertIsInstance(attr, list) 1265 self.assertEqual(attr, []) 1266 1267 for mock in mocks: 1268 assert_attrs(mock) 1269 1270 if callable(mock): 1271 mock() 1272 mock(1, 2) 1273 mock(a=3) 1274 1275 mock.reset_mock() 1276 assert_attrs(mock) 1277 1278 mock.foo() 1279 mock.foo.bar(1, a=3) 1280 mock.foo(1).bar().baz(3) 1281 1282 mock.reset_mock() 1283 assert_attrs(mock) 1284 1285 1286 def test_call_args_two_tuple(self): 1287 mock = Mock() 1288 mock(1, a=3) 1289 mock(2, b=4) 1290 1291 self.assertEqual(len(mock.call_args), 2) 1292 self.assertEqual(mock.call_args.args, (2,)) 1293 self.assertEqual(mock.call_args.kwargs, dict(b=4)) 1294 1295 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))] 1296 for expected, call_args in zip(expected_list, mock.call_args_list): 1297 self.assertEqual(len(call_args), 2) 1298 self.assertEqual(expected[0], call_args[0]) 1299 self.assertEqual(expected[1], call_args[1]) 1300 1301 1302 def test_side_effect_iterator(self): 1303 mock = Mock(side_effect=iter([1, 2, 3])) 1304 self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) 1305 self.assertRaises(StopIteration, mock) 1306 1307 mock = MagicMock(side_effect=['a', 'b', 'c']) 1308 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) 1309 self.assertRaises(StopIteration, mock) 1310 1311 mock = Mock(side_effect='ghi') 1312 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i']) 1313 self.assertRaises(StopIteration, mock) 1314 1315 class Foo(object): 1316 pass 1317 mock = MagicMock(side_effect=Foo) 1318 self.assertIsInstance(mock(), Foo) 1319 1320 mock = Mock(side_effect=Iter()) 1321 self.assertEqual([mock(), mock(), mock(), mock()], 1322 ['this', 'is', 'an', 'iter']) 1323 self.assertRaises(StopIteration, mock) 1324 1325 1326 def test_side_effect_iterator_exceptions(self): 1327 for Klass in Mock, MagicMock: 1328 iterable = (ValueError, 3, KeyError, 6) 1329 m = Klass(side_effect=iterable) 1330 self.assertRaises(ValueError, m) 1331 self.assertEqual(m(), 3) 1332 self.assertRaises(KeyError, m) 1333 self.assertEqual(m(), 6) 1334 1335 1336 def test_side_effect_setting_iterator(self): 1337 mock = Mock() 1338 mock.side_effect = iter([1, 2, 3]) 1339 self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) 1340 self.assertRaises(StopIteration, mock) 1341 side_effect = mock.side_effect 1342 self.assertIsInstance(side_effect, type(iter([]))) 1343 1344 mock.side_effect = ['a', 'b', 'c'] 1345 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) 1346 self.assertRaises(StopIteration, mock) 1347 side_effect = mock.side_effect 1348 self.assertIsInstance(side_effect, type(iter([]))) 1349 1350 this_iter = Iter() 1351 mock.side_effect = this_iter 1352 self.assertEqual([mock(), mock(), mock(), mock()], 1353 ['this', 'is', 'an', 'iter']) 1354 self.assertRaises(StopIteration, mock) 1355 self.assertIs(mock.side_effect, this_iter) 1356 1357 def test_side_effect_iterator_default(self): 1358 mock = Mock(return_value=2) 1359 mock.side_effect = iter([1, DEFAULT]) 1360 self.assertEqual([mock(), mock()], [1, 2]) 1361 1362 def test_assert_has_calls_any_order(self): 1363 mock = Mock() 1364 mock(1, 2) 1365 mock(a=3) 1366 mock(3, 4) 1367 mock(b=6) 1368 mock(b=6) 1369 1370 kalls = [ 1371 call(1, 2), ({'a': 3},), 1372 ((3, 4),), ((), {'a': 3}), 1373 ('', (1, 2)), ('', {'a': 3}), 1374 ('', (1, 2), {}), ('', (), {'a': 3}) 1375 ] 1376 for kall in kalls: 1377 mock.assert_has_calls([kall], any_order=True) 1378 1379 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo': 1380 self.assertRaises( 1381 AssertionError, mock.assert_has_calls, 1382 [kall], any_order=True 1383 ) 1384 1385 kall_lists = [ 1386 [call(1, 2), call(b=6)], 1387 [call(3, 4), call(1, 2)], 1388 [call(b=6), call(b=6)], 1389 ] 1390 1391 for kall_list in kall_lists: 1392 mock.assert_has_calls(kall_list, any_order=True) 1393 1394 kall_lists = [ 1395 [call(b=6), call(b=6), call(b=6)], 1396 [call(1, 2), call(1, 2)], 1397 [call(3, 4), call(1, 2), call(5, 7)], 1398 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)], 1399 ] 1400 for kall_list in kall_lists: 1401 self.assertRaises( 1402 AssertionError, mock.assert_has_calls, 1403 kall_list, any_order=True 1404 ) 1405 1406 def test_assert_has_calls(self): 1407 kalls1 = [ 1408 call(1, 2), ({'a': 3},), 1409 ((3, 4),), call(b=6), 1410 ('', (1,), {'b': 6}), 1411 ] 1412 kalls2 = [call.foo(), call.bar(1)] 1413 kalls2.extend(call.spam().baz(a=3).call_list()) 1414 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list()) 1415 1416 mocks = [] 1417 for mock in Mock(), MagicMock(): 1418 mock(1, 2) 1419 mock(a=3) 1420 mock(3, 4) 1421 mock(b=6) 1422 mock(1, b=6) 1423 mocks.append((mock, kalls1)) 1424 1425 mock = Mock() 1426 mock.foo() 1427 mock.bar(1) 1428 mock.spam().baz(a=3) 1429 mock.bam(set(), foo={}).fish([1]) 1430 mocks.append((mock, kalls2)) 1431 1432 for mock, kalls in mocks: 1433 for i in range(len(kalls)): 1434 for step in 1, 2, 3: 1435 these = kalls[i:i+step] 1436 mock.assert_has_calls(these) 1437 1438 if len(these) > 1: 1439 self.assertRaises( 1440 AssertionError, 1441 mock.assert_has_calls, 1442 list(reversed(these)) 1443 ) 1444 1445 1446 def test_assert_has_calls_nested_spec(self): 1447 class Something: 1448 1449 def __init__(self): pass 1450 def meth(self, a, b, c, d=None): pass 1451 1452 class Foo: 1453 1454 def __init__(self, a): pass 1455 def meth1(self, a, b): pass 1456 1457 mock_class = create_autospec(Something) 1458 1459 for m in [mock_class, mock_class()]: 1460 m.meth(1, 2, 3, d=1) 1461 m.assert_has_calls([call.meth(1, 2, 3, d=1)]) 1462 m.assert_has_calls([call.meth(1, 2, 3, 1)]) 1463 1464 mock_class.reset_mock() 1465 1466 for m in [mock_class, mock_class()]: 1467 self.assertRaises(AssertionError, m.assert_has_calls, [call.Foo()]) 1468 m.Foo(1).meth1(1, 2) 1469 m.assert_has_calls([call.Foo(1), call.Foo(1).meth1(1, 2)]) 1470 m.Foo.assert_has_calls([call(1), call().meth1(1, 2)]) 1471 1472 mock_class.reset_mock() 1473 1474 invalid_calls = [call.meth(1), 1475 call.non_existent(1), 1476 call.Foo().non_existent(1), 1477 call.Foo().meth(1, 2, 3, 4)] 1478 1479 for kall in invalid_calls: 1480 self.assertRaises(AssertionError, 1481 mock_class.assert_has_calls, 1482 [kall] 1483 ) 1484 1485 1486 def test_assert_has_calls_nested_without_spec(self): 1487 m = MagicMock() 1488 m().foo().bar().baz() 1489 m.one().two().three() 1490 calls = call.one().two().three().call_list() 1491 m.assert_has_calls(calls) 1492 1493 1494 def test_assert_has_calls_with_function_spec(self): 1495 def f(a, b, c, d=None): pass 1496 1497 mock = Mock(spec=f) 1498 1499 mock(1, b=2, c=3) 1500 mock(4, 5, c=6, d=7) 1501 mock(10, 11, c=12) 1502 calls = [ 1503 ('', (1, 2, 3), {}), 1504 ('', (4, 5, 6), {'d': 7}), 1505 ((10, 11, 12), {}), 1506 ] 1507 mock.assert_has_calls(calls) 1508 mock.assert_has_calls(calls, any_order=True) 1509 mock.assert_has_calls(calls[1:]) 1510 mock.assert_has_calls(calls[1:], any_order=True) 1511 mock.assert_has_calls(calls[:-1]) 1512 mock.assert_has_calls(calls[:-1], any_order=True) 1513 # Reversed order 1514 calls = list(reversed(calls)) 1515 with self.assertRaises(AssertionError): 1516 mock.assert_has_calls(calls) 1517 mock.assert_has_calls(calls, any_order=True) 1518 with self.assertRaises(AssertionError): 1519 mock.assert_has_calls(calls[1:]) 1520 mock.assert_has_calls(calls[1:], any_order=True) 1521 with self.assertRaises(AssertionError): 1522 mock.assert_has_calls(calls[:-1]) 1523 mock.assert_has_calls(calls[:-1], any_order=True) 1524 1525 def test_assert_has_calls_not_matching_spec_error(self): 1526 def f(x=None): pass 1527 1528 mock = Mock(spec=f) 1529 mock(1) 1530 1531 with self.assertRaisesRegex( 1532 AssertionError, 1533 '^{}$'.format( 1534 re.escape('Calls not found.\n' 1535 'Expected: [call()]\n' 1536 'Actual: [call(1)]'))) as cm: 1537 mock.assert_has_calls([call()]) 1538 self.assertIsNone(cm.exception.__cause__) 1539 1540 1541 with self.assertRaisesRegex( 1542 AssertionError, 1543 '^{}$'.format( 1544 re.escape( 1545 'Error processing expected calls.\n' 1546 "Errors: [None, TypeError('too many positional arguments')]\n" 1547 "Expected: [call(), call(1, 2)]\n" 1548 'Actual: [call(1)]'))) as cm: 1549 mock.assert_has_calls([call(), call(1, 2)]) 1550 self.assertIsInstance(cm.exception.__cause__, TypeError) 1551 1552 def test_assert_any_call(self): 1553 mock = Mock() 1554 mock(1, 2) 1555 mock(a=3) 1556 mock(1, b=6) 1557 1558 mock.assert_any_call(1, 2) 1559 mock.assert_any_call(a=3) 1560 mock.assert_any_call(1, b=6) 1561 1562 self.assertRaises( 1563 AssertionError, 1564 mock.assert_any_call 1565 ) 1566 self.assertRaises( 1567 AssertionError, 1568 mock.assert_any_call, 1569 1, 3 1570 ) 1571 self.assertRaises( 1572 AssertionError, 1573 mock.assert_any_call, 1574 a=4 1575 ) 1576 1577 1578 def test_assert_any_call_with_function_spec(self): 1579 def f(a, b, c, d=None): pass 1580 1581 mock = Mock(spec=f) 1582 1583 mock(1, b=2, c=3) 1584 mock(4, 5, c=6, d=7) 1585 mock.assert_any_call(1, 2, 3) 1586 mock.assert_any_call(a=1, b=2, c=3) 1587 mock.assert_any_call(4, 5, 6, 7) 1588 mock.assert_any_call(a=4, b=5, c=6, d=7) 1589 self.assertRaises(AssertionError, mock.assert_any_call, 1590 1, b=3, c=2) 1591 # Expected call doesn't match the spec's signature 1592 with self.assertRaises(AssertionError) as cm: 1593 mock.assert_any_call(e=8) 1594 self.assertIsInstance(cm.exception.__cause__, TypeError) 1595 1596 1597 def test_mock_calls_create_autospec(self): 1598 def f(a, b): pass 1599 obj = Iter() 1600 obj.f = f 1601 1602 funcs = [ 1603 create_autospec(f), 1604 create_autospec(obj).f 1605 ] 1606 for func in funcs: 1607 func(1, 2) 1608 func(3, 4) 1609 1610 self.assertEqual( 1611 func.mock_calls, [call(1, 2), call(3, 4)] 1612 ) 1613 1614 #Issue21222 1615 def test_create_autospec_with_name(self): 1616 m = mock.create_autospec(object(), name='sweet_func') 1617 self.assertIn('sweet_func', repr(m)) 1618 1619 #Issue23078 1620 def test_create_autospec_classmethod_and_staticmethod(self): 1621 class TestClass: 1622 @classmethod 1623 def class_method(cls): pass 1624 1625 @staticmethod 1626 def static_method(): pass 1627 for method in ('class_method', 'static_method'): 1628 with self.subTest(method=method): 1629 mock_method = mock.create_autospec(getattr(TestClass, method)) 1630 mock_method() 1631 mock_method.assert_called_once_with() 1632 self.assertRaises(TypeError, mock_method, 'extra_arg') 1633 1634 #Issue21238 1635 def test_mock_unsafe(self): 1636 m = Mock() 1637 msg = "is not a valid assertion. Use a spec for the mock" 1638 with self.assertRaisesRegex(AttributeError, msg): 1639 m.assert_foo_call() 1640 with self.assertRaisesRegex(AttributeError, msg): 1641 m.assret_foo_call() 1642 with self.assertRaisesRegex(AttributeError, msg): 1643 m.asert_foo_call() 1644 with self.assertRaisesRegex(AttributeError, msg): 1645 m.aseert_foo_call() 1646 with self.assertRaisesRegex(AttributeError, msg): 1647 m.assrt_foo_call() 1648 m = Mock(unsafe=True) 1649 m.assert_foo_call() 1650 m.assret_foo_call() 1651 m.asert_foo_call() 1652 m.aseert_foo_call() 1653 m.assrt_foo_call() 1654 1655 # gh-100739 1656 def test_mock_safe_with_spec(self): 1657 class Foo(object): 1658 def assert_bar(self): 1659 pass 1660 1661 def assertSome(self): 1662 pass 1663 1664 m = Mock(spec=Foo) 1665 m.assert_bar() 1666 m.assertSome() 1667 1668 m.assert_bar.assert_called_once() 1669 m.assertSome.assert_called_once() 1670 1671 #Issue21262 1672 def test_assert_not_called(self): 1673 m = Mock() 1674 m.hello.assert_not_called() 1675 m.hello() 1676 with self.assertRaises(AssertionError): 1677 m.hello.assert_not_called() 1678 1679 def test_assert_not_called_message(self): 1680 m = Mock() 1681 m(1, 2) 1682 self.assertRaisesRegex(AssertionError, 1683 re.escape("Calls: [call(1, 2)]"), 1684 m.assert_not_called) 1685 1686 def test_assert_called(self): 1687 m = Mock() 1688 with self.assertRaises(AssertionError): 1689 m.hello.assert_called() 1690 m.hello() 1691 m.hello.assert_called() 1692 1693 m.hello() 1694 m.hello.assert_called() 1695 1696 def test_assert_called_once(self): 1697 m = Mock() 1698 with self.assertRaises(AssertionError): 1699 m.hello.assert_called_once() 1700 m.hello() 1701 m.hello.assert_called_once() 1702 1703 m.hello() 1704 with self.assertRaises(AssertionError): 1705 m.hello.assert_called_once() 1706 1707 def test_assert_called_once_message(self): 1708 m = Mock() 1709 m(1, 2) 1710 m(3) 1711 self.assertRaisesRegex(AssertionError, 1712 re.escape("Calls: [call(1, 2), call(3)]"), 1713 m.assert_called_once) 1714 1715 def test_assert_called_once_message_not_called(self): 1716 m = Mock() 1717 with self.assertRaises(AssertionError) as e: 1718 m.assert_called_once() 1719 self.assertNotIn("Calls:", str(e.exception)) 1720 1721 #Issue37212 printout of keyword args now preserves the original order 1722 def test_ordered_call_signature(self): 1723 m = Mock() 1724 m.hello(name='hello', daddy='hero') 1725 text = "call(name='hello', daddy='hero')" 1726 self.assertEqual(repr(m.hello.call_args), text) 1727 1728 #Issue21270 overrides tuple methods for mock.call objects 1729 def test_override_tuple_methods(self): 1730 c = call.count() 1731 i = call.index(132,'hello') 1732 m = Mock() 1733 m.count() 1734 m.index(132,"hello") 1735 self.assertEqual(m.method_calls[0], c) 1736 self.assertEqual(m.method_calls[1], i) 1737 1738 def test_reset_return_sideeffect(self): 1739 m = Mock(return_value=10, side_effect=[2,3]) 1740 m.reset_mock(return_value=True, side_effect=True) 1741 self.assertIsInstance(m.return_value, Mock) 1742 self.assertEqual(m.side_effect, None) 1743 1744 def test_reset_return(self): 1745 m = Mock(return_value=10, side_effect=[2,3]) 1746 m.reset_mock(return_value=True) 1747 self.assertIsInstance(m.return_value, Mock) 1748 self.assertNotEqual(m.side_effect, None) 1749 1750 def test_reset_sideeffect(self): 1751 m = Mock(return_value=10, side_effect=[2, 3]) 1752 m.reset_mock(side_effect=True) 1753 self.assertEqual(m.return_value, 10) 1754 self.assertEqual(m.side_effect, None) 1755 1756 def test_reset_return_with_children(self): 1757 m = MagicMock(f=MagicMock(return_value=1)) 1758 self.assertEqual(m.f(), 1) 1759 m.reset_mock(return_value=True) 1760 self.assertNotEqual(m.f(), 1) 1761 1762 def test_reset_return_with_children_side_effect(self): 1763 m = MagicMock(f=MagicMock(side_effect=[2, 3])) 1764 self.assertNotEqual(m.f.side_effect, None) 1765 m.reset_mock(side_effect=True) 1766 self.assertEqual(m.f.side_effect, None) 1767 1768 def test_mock_add_spec(self): 1769 class _One(object): 1770 one = 1 1771 class _Two(object): 1772 two = 2 1773 class Anything(object): 1774 one = two = three = 'four' 1775 1776 klasses = [ 1777 Mock, MagicMock, NonCallableMock, NonCallableMagicMock 1778 ] 1779 for Klass in list(klasses): 1780 klasses.append(lambda K=Klass: K(spec=Anything)) 1781 klasses.append(lambda K=Klass: K(spec_set=Anything)) 1782 1783 for Klass in klasses: 1784 for kwargs in dict(), dict(spec_set=True): 1785 mock = Klass() 1786 #no error 1787 mock.one, mock.two, mock.three 1788 1789 for One, Two in [(_One, _Two), (['one'], ['two'])]: 1790 for kwargs in dict(), dict(spec_set=True): 1791 mock.mock_add_spec(One, **kwargs) 1792 1793 mock.one 1794 self.assertRaises( 1795 AttributeError, getattr, mock, 'two' 1796 ) 1797 self.assertRaises( 1798 AttributeError, getattr, mock, 'three' 1799 ) 1800 if 'spec_set' in kwargs: 1801 self.assertRaises( 1802 AttributeError, setattr, mock, 'three', None 1803 ) 1804 1805 mock.mock_add_spec(Two, **kwargs) 1806 self.assertRaises( 1807 AttributeError, getattr, mock, 'one' 1808 ) 1809 mock.two 1810 self.assertRaises( 1811 AttributeError, getattr, mock, 'three' 1812 ) 1813 if 'spec_set' in kwargs: 1814 self.assertRaises( 1815 AttributeError, setattr, mock, 'three', None 1816 ) 1817 # note that creating a mock, setting an instance attribute, and 1818 # *then* setting a spec doesn't work. Not the intended use case 1819 1820 1821 def test_mock_add_spec_magic_methods(self): 1822 for Klass in MagicMock, NonCallableMagicMock: 1823 mock = Klass() 1824 int(mock) 1825 1826 mock.mock_add_spec(object) 1827 self.assertRaises(TypeError, int, mock) 1828 1829 mock = Klass() 1830 mock['foo'] 1831 mock.__int__.return_value =4 1832 1833 mock.mock_add_spec(int) 1834 self.assertEqual(int(mock), 4) 1835 self.assertRaises(TypeError, lambda: mock['foo']) 1836 1837 1838 def test_adding_child_mock(self): 1839 for Klass in (NonCallableMock, Mock, MagicMock, NonCallableMagicMock, 1840 AsyncMock): 1841 mock = Klass() 1842 1843 mock.foo = Mock() 1844 mock.foo() 1845 1846 self.assertEqual(mock.method_calls, [call.foo()]) 1847 self.assertEqual(mock.mock_calls, [call.foo()]) 1848 1849 mock = Klass() 1850 mock.bar = Mock(name='name') 1851 mock.bar() 1852 self.assertEqual(mock.method_calls, []) 1853 self.assertEqual(mock.mock_calls, []) 1854 1855 # mock with an existing _new_parent but no name 1856 mock = Klass() 1857 mock.baz = MagicMock()() 1858 mock.baz() 1859 self.assertEqual(mock.method_calls, []) 1860 self.assertEqual(mock.mock_calls, []) 1861 1862 1863 def test_adding_return_value_mock(self): 1864 for Klass in Mock, MagicMock: 1865 mock = Klass() 1866 mock.return_value = MagicMock() 1867 1868 mock()() 1869 self.assertEqual(mock.mock_calls, [call(), call()()]) 1870 1871 1872 def test_manager_mock(self): 1873 class Foo(object): 1874 one = 'one' 1875 two = 'two' 1876 manager = Mock() 1877 p1 = patch.object(Foo, 'one') 1878 p2 = patch.object(Foo, 'two') 1879 1880 mock_one = p1.start() 1881 self.addCleanup(p1.stop) 1882 mock_two = p2.start() 1883 self.addCleanup(p2.stop) 1884 1885 manager.attach_mock(mock_one, 'one') 1886 manager.attach_mock(mock_two, 'two') 1887 1888 Foo.two() 1889 Foo.one() 1890 1891 self.assertEqual(manager.mock_calls, [call.two(), call.one()]) 1892 1893 1894 def test_magic_methods_mock_calls(self): 1895 for Klass in Mock, MagicMock: 1896 m = Klass() 1897 m.__int__ = Mock(return_value=3) 1898 m.__float__ = MagicMock(return_value=3.0) 1899 int(m) 1900 float(m) 1901 1902 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()]) 1903 self.assertEqual(m.method_calls, []) 1904 1905 def test_mock_open_reuse_issue_21750(self): 1906 mocked_open = mock.mock_open(read_data='data') 1907 f1 = mocked_open('a-name') 1908 f1_data = f1.read() 1909 f2 = mocked_open('another-name') 1910 f2_data = f2.read() 1911 self.assertEqual(f1_data, f2_data) 1912 1913 def test_mock_open_dunder_iter_issue(self): 1914 # Test dunder_iter method generates the expected result and 1915 # consumes the iterator. 1916 mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue') 1917 f1 = mocked_open('a-name') 1918 lines = [line for line in f1] 1919 self.assertEqual(lines[0], 'Remarkable\n') 1920 self.assertEqual(lines[1], 'Norwegian Blue') 1921 self.assertEqual(list(f1), []) 1922 1923 def test_mock_open_using_next(self): 1924 mocked_open = mock.mock_open(read_data='1st line\n2nd line\n3rd line') 1925 f1 = mocked_open('a-name') 1926 line1 = next(f1) 1927 line2 = f1.__next__() 1928 lines = [line for line in f1] 1929 self.assertEqual(line1, '1st line\n') 1930 self.assertEqual(line2, '2nd line\n') 1931 self.assertEqual(lines[0], '3rd line') 1932 self.assertEqual(list(f1), []) 1933 with self.assertRaises(StopIteration): 1934 next(f1) 1935 1936 def test_mock_open_next_with_readline_with_return_value(self): 1937 mopen = mock.mock_open(read_data='foo\nbarn') 1938 mopen.return_value.readline.return_value = 'abc' 1939 self.assertEqual('abc', next(mopen())) 1940 1941 def test_mock_open_write(self): 1942 # Test exception in file writing write() 1943 mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV')) 1944 with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp): 1945 mock_filehandle = mock_namedtemp.return_value 1946 mock_write = mock_filehandle.write 1947 mock_write.side_effect = OSError('Test 2 Error') 1948 def attempt(): 1949 tempfile.NamedTemporaryFile().write('asd') 1950 self.assertRaises(OSError, attempt) 1951 1952 def test_mock_open_alter_readline(self): 1953 mopen = mock.mock_open(read_data='foo\nbarn') 1954 mopen.return_value.readline.side_effect = lambda *args:'abc' 1955 first = mopen().readline() 1956 second = mopen().readline() 1957 self.assertEqual('abc', first) 1958 self.assertEqual('abc', second) 1959 1960 def test_mock_open_after_eof(self): 1961 # read, readline and readlines should work after end of file. 1962 _open = mock.mock_open(read_data='foo') 1963 h = _open('bar') 1964 h.read() 1965 self.assertEqual('', h.read()) 1966 self.assertEqual('', h.read()) 1967 self.assertEqual('', h.readline()) 1968 self.assertEqual('', h.readline()) 1969 self.assertEqual([], h.readlines()) 1970 self.assertEqual([], h.readlines()) 1971 1972 def test_mock_parents(self): 1973 for Klass in Mock, MagicMock: 1974 m = Klass() 1975 original_repr = repr(m) 1976 m.return_value = m 1977 self.assertIs(m(), m) 1978 self.assertEqual(repr(m), original_repr) 1979 1980 m.reset_mock() 1981 self.assertIs(m(), m) 1982 self.assertEqual(repr(m), original_repr) 1983 1984 m = Klass() 1985 m.b = m.a 1986 self.assertIn("name='mock.a'", repr(m.b)) 1987 self.assertIn("name='mock.a'", repr(m.a)) 1988 m.reset_mock() 1989 self.assertIn("name='mock.a'", repr(m.b)) 1990 self.assertIn("name='mock.a'", repr(m.a)) 1991 1992 m = Klass() 1993 original_repr = repr(m) 1994 m.a = m() 1995 m.a.return_value = m 1996 1997 self.assertEqual(repr(m), original_repr) 1998 self.assertEqual(repr(m.a()), original_repr) 1999 2000 2001 def test_attach_mock(self): 2002 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock 2003 for Klass in classes: 2004 for Klass2 in classes: 2005 m = Klass() 2006 2007 m2 = Klass2(name='foo') 2008 m.attach_mock(m2, 'bar') 2009 2010 self.assertIs(m.bar, m2) 2011 self.assertIn("name='mock.bar'", repr(m2)) 2012 2013 m.bar.baz(1) 2014 self.assertEqual(m.mock_calls, [call.bar.baz(1)]) 2015 self.assertEqual(m.method_calls, [call.bar.baz(1)]) 2016 2017 2018 def test_attach_mock_return_value(self): 2019 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock 2020 for Klass in Mock, MagicMock: 2021 for Klass2 in classes: 2022 m = Klass() 2023 2024 m2 = Klass2(name='foo') 2025 m.attach_mock(m2, 'return_value') 2026 2027 self.assertIs(m(), m2) 2028 self.assertIn("name='mock()'", repr(m2)) 2029 2030 m2.foo() 2031 self.assertEqual(m.mock_calls, call().foo().call_list()) 2032 2033 2034 def test_attach_mock_patch_autospec(self): 2035 parent = Mock() 2036 2037 with mock.patch(f'{__name__}.something', autospec=True) as mock_func: 2038 self.assertEqual(mock_func.mock._extract_mock_name(), 'something') 2039 parent.attach_mock(mock_func, 'child') 2040 parent.child(1) 2041 something(2) 2042 mock_func(3) 2043 2044 parent_calls = [call.child(1), call.child(2), call.child(3)] 2045 child_calls = [call(1), call(2), call(3)] 2046 self.assertEqual(parent.mock_calls, parent_calls) 2047 self.assertEqual(parent.child.mock_calls, child_calls) 2048 self.assertEqual(something.mock_calls, child_calls) 2049 self.assertEqual(mock_func.mock_calls, child_calls) 2050 self.assertIn('mock.child', repr(parent.child.mock)) 2051 self.assertEqual(mock_func.mock._extract_mock_name(), 'mock.child') 2052 2053 2054 def test_attach_mock_patch_autospec_signature(self): 2055 with mock.patch(f'{__name__}.Something.meth', autospec=True) as mocked: 2056 manager = Mock() 2057 manager.attach_mock(mocked, 'attach_meth') 2058 obj = Something() 2059 obj.meth(1, 2, 3, d=4) 2060 manager.assert_has_calls([call.attach_meth(mock.ANY, 1, 2, 3, d=4)]) 2061 obj.meth.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)]) 2062 mocked.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)]) 2063 2064 with mock.patch(f'{__name__}.something', autospec=True) as mocked: 2065 manager = Mock() 2066 manager.attach_mock(mocked, 'attach_func') 2067 something(1) 2068 manager.assert_has_calls([call.attach_func(1)]) 2069 something.assert_has_calls([call(1)]) 2070 mocked.assert_has_calls([call(1)]) 2071 2072 with mock.patch(f'{__name__}.Something', autospec=True) as mocked: 2073 manager = Mock() 2074 manager.attach_mock(mocked, 'attach_obj') 2075 obj = Something() 2076 obj.meth(1, 2, 3, d=4) 2077 manager.assert_has_calls([call.attach_obj(), 2078 call.attach_obj().meth(1, 2, 3, d=4)]) 2079 obj.meth.assert_has_calls([call(1, 2, 3, d=4)]) 2080 mocked.assert_has_calls([call(), call().meth(1, 2, 3, d=4)]) 2081 2082 2083 def test_attribute_deletion(self): 2084 for mock in (Mock(), MagicMock(), NonCallableMagicMock(), 2085 NonCallableMock()): 2086 self.assertTrue(hasattr(mock, 'm')) 2087 2088 del mock.m 2089 self.assertFalse(hasattr(mock, 'm')) 2090 2091 del mock.f 2092 self.assertFalse(hasattr(mock, 'f')) 2093 self.assertRaises(AttributeError, getattr, mock, 'f') 2094 2095 2096 def test_mock_does_not_raise_on_repeated_attribute_deletion(self): 2097 # bpo-20239: Assigning and deleting twice an attribute raises. 2098 for mock in (Mock(), MagicMock(), NonCallableMagicMock(), 2099 NonCallableMock()): 2100 mock.foo = 3 2101 self.assertTrue(hasattr(mock, 'foo')) 2102 self.assertEqual(mock.foo, 3) 2103 2104 del mock.foo 2105 self.assertFalse(hasattr(mock, 'foo')) 2106 2107 mock.foo = 4 2108 self.assertTrue(hasattr(mock, 'foo')) 2109 self.assertEqual(mock.foo, 4) 2110 2111 del mock.foo 2112 self.assertFalse(hasattr(mock, 'foo')) 2113 2114 2115 def test_mock_raises_when_deleting_nonexistent_attribute(self): 2116 for mock in (Mock(), MagicMock(), NonCallableMagicMock(), 2117 NonCallableMock()): 2118 del mock.foo 2119 with self.assertRaises(AttributeError): 2120 del mock.foo 2121 2122 2123 def test_reset_mock_does_not_raise_on_attr_deletion(self): 2124 # bpo-31177: reset_mock should not raise AttributeError when attributes 2125 # were deleted in a mock instance 2126 mock = Mock() 2127 mock.child = True 2128 del mock.child 2129 mock.reset_mock() 2130 self.assertFalse(hasattr(mock, 'child')) 2131 2132 2133 def test_class_assignable(self): 2134 for mock in Mock(), MagicMock(): 2135 self.assertNotIsInstance(mock, int) 2136 2137 mock.__class__ = int 2138 self.assertIsInstance(mock, int) 2139 mock.foo 2140 2141 def test_name_attribute_of_call(self): 2142 # bpo-35357: _Call should not disclose any attributes whose names 2143 # may clash with popular ones (such as ".name") 2144 self.assertIsNotNone(call.name) 2145 self.assertEqual(type(call.name), _Call) 2146 self.assertEqual(type(call.name().name), _Call) 2147 2148 def test_parent_attribute_of_call(self): 2149 # bpo-35357: _Call should not disclose any attributes whose names 2150 # may clash with popular ones (such as ".parent") 2151 self.assertIsNotNone(call.parent) 2152 self.assertEqual(type(call.parent), _Call) 2153 self.assertEqual(type(call.parent().parent), _Call) 2154 2155 2156 def test_parent_propagation_with_create_autospec(self): 2157 2158 def foo(a, b): pass 2159 2160 mock = Mock() 2161 mock.child = create_autospec(foo) 2162 mock.child(1, 2) 2163 2164 self.assertRaises(TypeError, mock.child, 1) 2165 self.assertEqual(mock.mock_calls, [call.child(1, 2)]) 2166 self.assertIn('mock.child', repr(mock.child.mock)) 2167 2168 def test_parent_propagation_with_autospec_attach_mock(self): 2169 2170 def foo(a, b): pass 2171 2172 parent = Mock() 2173 parent.attach_mock(create_autospec(foo, name='bar'), 'child') 2174 parent.child(1, 2) 2175 2176 self.assertRaises(TypeError, parent.child, 1) 2177 self.assertEqual(parent.child.mock_calls, [call.child(1, 2)]) 2178 self.assertIn('mock.child', repr(parent.child.mock)) 2179 2180 2181 def test_isinstance_under_settrace(self): 2182 # bpo-36593 : __class__ is not set for a class that has __class__ 2183 # property defined when it's used with sys.settrace(trace) set. 2184 # Delete the module to force reimport with tracing function set 2185 # restore the old reference later since there are other tests that are 2186 # dependent on unittest.mock.patch. In testpatch.PatchTest 2187 # test_patch_dict_test_prefix and test_patch_test_prefix not restoring 2188 # causes the objects patched to go out of sync 2189 2190 old_patch = unittest.mock.patch 2191 2192 # Directly using __setattr__ on unittest.mock causes current imported 2193 # reference to be updated. Use a lambda so that during cleanup the 2194 # re-imported new reference is updated. 2195 self.addCleanup(lambda patch: setattr(unittest.mock, 'patch', patch), 2196 old_patch) 2197 2198 with patch.dict('sys.modules'): 2199 del sys.modules['unittest.mock'] 2200 2201 # This trace will stop coverage being measured ;-) 2202 def trace(frame, event, arg): # pragma: no cover 2203 return trace 2204 2205 self.addCleanup(sys.settrace, sys.gettrace()) 2206 sys.settrace(trace) 2207 2208 from unittest.mock import ( 2209 Mock, MagicMock, NonCallableMock, NonCallableMagicMock 2210 ) 2211 2212 mocks = [ 2213 Mock, MagicMock, NonCallableMock, NonCallableMagicMock, AsyncMock 2214 ] 2215 2216 for mock in mocks: 2217 obj = mock(spec=Something) 2218 self.assertIsInstance(obj, Something) 2219 2220 def test_bool_not_called_when_passing_spec_arg(self): 2221 class Something: 2222 def __init__(self): 2223 self.obj_with_bool_func = unittest.mock.MagicMock() 2224 2225 obj = Something() 2226 with unittest.mock.patch.object(obj, 'obj_with_bool_func', spec=object): pass 2227 2228 self.assertEqual(obj.obj_with_bool_func.__bool__.call_count, 0) 2229 2230 def test_misspelled_arguments(self): 2231 class Foo(): 2232 one = 'one' 2233 # patch, patch.object and create_autospec need to check for misspelled 2234 # arguments explicitly and throw a RuntimError if found. 2235 with self.assertRaises(RuntimeError): 2236 with patch(f'{__name__}.Something.meth', autospect=True): pass 2237 with self.assertRaises(RuntimeError): 2238 with patch.object(Foo, 'one', autospect=True): pass 2239 with self.assertRaises(RuntimeError): 2240 with patch(f'{__name__}.Something.meth', auto_spec=True): pass 2241 with self.assertRaises(RuntimeError): 2242 with patch.object(Foo, 'one', auto_spec=True): pass 2243 with self.assertRaises(RuntimeError): 2244 with patch(f'{__name__}.Something.meth', set_spec=True): pass 2245 with self.assertRaises(RuntimeError): 2246 with patch.object(Foo, 'one', set_spec=True): pass 2247 with self.assertRaises(RuntimeError): 2248 m = create_autospec(Foo, set_spec=True) 2249 # patch.multiple, on the other hand, should flag misspelled arguments 2250 # through an AttributeError, when trying to find the keys from kwargs 2251 # as attributes on the target. 2252 with self.assertRaises(AttributeError): 2253 with patch.multiple( 2254 f'{__name__}.Something', meth=DEFAULT, autospect=True): pass 2255 with self.assertRaises(AttributeError): 2256 with patch.multiple( 2257 f'{__name__}.Something', meth=DEFAULT, auto_spec=True): pass 2258 with self.assertRaises(AttributeError): 2259 with patch.multiple( 2260 f'{__name__}.Something', meth=DEFAULT, set_spec=True): pass 2261 2262 with patch(f'{__name__}.Something.meth', unsafe=True, autospect=True): 2263 pass 2264 with patch.object(Foo, 'one', unsafe=True, autospect=True): pass 2265 with patch(f'{__name__}.Something.meth', unsafe=True, auto_spec=True): 2266 pass 2267 with patch.object(Foo, 'one', unsafe=True, auto_spec=True): pass 2268 with patch(f'{__name__}.Something.meth', unsafe=True, set_spec=True): 2269 pass 2270 with patch.object(Foo, 'one', unsafe=True, set_spec=True): pass 2271 m = create_autospec(Foo, set_spec=True, unsafe=True) 2272 with patch.multiple( 2273 f'{__name__}.Typos', autospect=True, set_spec=True, auto_spec=True): 2274 pass 2275 2276 2277if __name__ == '__main__': 2278 unittest.main() 2279